Python DataURI
A small Python library for manipulating data URIs, as defined in RFC2397. It provides functionalities for parsing existing data URIs into structured objects and creating new ones from various inputs. The library is currently at version 3.0.2 and appears to have an infrequent release cadence, driven by feature additions and Python version compatibility.
Warnings
- breaking The library underwent a major version bump from 2.x to 3.x (v3.0.0 released Jan 3, 2025). While explicit breaking changes are not extensively documented in the README for this specific jump, major version changes typically introduce backwards-incompatible changes. Users upgrading from 2.x should review their code for compatibility.
- gotcha The `DataURI.data` attribute always returns the decoded data as `bytes`. If you need a string representation (assuming the data is textual and decodable), you must use the `DataURI.text` attribute.
- gotcha The library's GitHub README notes that it is 'not very robust, and will reject a number of valid data URIs.' It primarily supports cases with a mimetype, charset, and base64 flag. Complex or non-standard data URIs might not parse correctly.
Install
-
pip install python-datauri
Imports
- DataURI
from datauri import DataURI
Quickstart
from datauri import DataURI
# Parsing a data URI
uri_string = 'data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu'
parsed_uri = DataURI(uri_string)
print(f"MIME Type: {parsed_uri.mimetype}")
print(f"Charset: {parsed_uri.charset}")
print(f"Is Base64: {parsed_uri.is_base64}")
print(f"Decoded data (bytes): {parsed_uri.data}")
print(f"Decoded data (text): {parsed_uri.text}")
# Creating a data URI
made_uri = DataURI.make('image/png', base64=True, data=b'\x89PNG\r\n...') # Example with bytes
print(f"Created URI: {made_uri}")
# Creating from a string directly
text_uri = DataURI.make('text/plain', data='Hello, World!')
print(f"Text URI: {text_uri}")