Skip to content

fcurella/python-datauri

Repository files navigation

DataURI

Build status of the master branch on Mac/Linux

image

Data URI manipulation made easy.

This isn't very robust, and will reject a number of valid data URIs. However, it meets the most useful case: a mimetype, a charset, and the base64 flag.

Installation

$ pip install python-datauri

Parsing

>>> from datauri import DataURI
>>> uri = DataURI('data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')
>>> uri.mimetype
'text/plain'
>>> uri.charset
'utf-8'
>>> uri.is_base64
True
>>> uri.data
b'The quick brown fox jumped over the lazy dog.'

Note that DataURI.data will always return bytes. Use DataURI.text to get a string.

Creating from a string

>>> from datauri import DataURI
>>> made = DataURI.make('text/plain', charset='us-ascii', base64=True, data='This is a message.')
>>> made
DataURI('data:text/plain;charset=us-ascii;base64,VGhpcyBpcyBhIG1lc3NhZ2Uu')
>>> made.data
b'This is a message.'

Creating from a file

This is really just a convenience method.

>>> from datauri import DataURI
>>> png_uri = DataURI.from_file('somefile.png')
>>> png_uri.mimetype
'image/png'
>>> png_uri.data
b'\x89PNG\r\n...'

Serializing

DataURI is a subclass of str, so you can just use str() to print it out:

>>> from datauri import DataURI
>>> png_uri = DataURI.from_file('somefile.png')
>>> str(png_uri)
'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIA...'

Pydantic Support

You can use DataURI as a type for Pydantic v1:

from datauri import DataURI
from pydantic import BaseModel


class ProfilePicture(BaseModel):
  image_data: DataURI

License

This code is released under the Unlicense.

Credits

This is a repackaging of this Gist originally written by Zachary Voase.