diff --git a/.gitignore b/.gitignore index 2c362ab..745bf36 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ /dist /htmlcov __pycache__ +venv/ +.idea/ +.vscode/ diff --git a/datauri/__init__.py b/datauri/__init__.py index 1a2f5ba..b74c3ad 100644 --- a/datauri/__init__.py +++ b/datauri/__init__.py @@ -5,4 +5,5 @@ from .datauri import ( # noqa: F401 DataURIError, discover, - parse) + parse, + build) diff --git a/datauri/datauri.py b/datauri/datauri.py index 673a4df..764af13 100644 --- a/datauri/datauri.py +++ b/datauri/datauri.py @@ -1,6 +1,8 @@ import base64 import re import urllib.parse +from pathlib import Path +import mimetypes # RFC 3986: reserved characters, unreserved characters, and percent. @@ -89,3 +91,31 @@ def discover(s): yield parse(match.group()) except DataURIError: continue + + +def build(fp): + """ + Build data URI according to RFC 2397 + (data:[][;base64],) + + :param str|Path|bytes fp: + :return: + """ + if isinstance(fp, (str, Path)) and Path(fp).is_file(): + b = Path(fp).read_bytes() + try: + import magic + mime = magic.from_file(fp, mime=True) + except ImportError: + mime, _ = mimetypes.guess_type(str(fp)) + + if mime is None: + raise DataURIError('Invalid MIME type') + else: + import magic + b = fp + mime = magic.from_buffer(fp, mime=True) + + data64 = base64.b64encode(b).decode() + + return 'data:{};base64,{}'.format(mime, data64) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6863aff --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +python-magic==0.4.15 diff --git a/setup.py b/setup.py index c84f471..3eb7646 100644 --- a/setup.py +++ b/setup.py @@ -8,10 +8,12 @@ name='datauri', description="implementation of the data uri scheme defined in rfc2397", long_description=long_description, - version='1.0.0', + version='1.0.1', author="EclecticIQ", author_email="info@eclecticiq.com", packages=['datauri'], + install_requires=['python-magic'], + tests_require=['pytest'], url='https://github.com/eclecticiq/python-data-uri', license="BSD", classifiers=[ diff --git a/tox.ini b/tox.ini index de50511..be132f4 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = py33,py34,py35,py36 +envlist = py34,py35,py36 [testenv] deps=-rrequirements-test.txt