Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add build(filename_or_bytes) #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@
/dist
/htmlcov
__pycache__
venv/
.idea/
.vscode/
3 changes: 2 additions & 1 deletion datauri/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@
from .datauri import ( # noqa: F401
DataURIError,
discover,
parse)
parse,
build)
30 changes: 30 additions & 0 deletions datauri/datauri.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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:[<mediatype>][;base64],<data>)

: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)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
python-magic==0.4.15
4 changes: 3 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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="[email protected]",
packages=['datauri'],
install_requires=['python-magic'],
tests_require=['pytest'],
url='https://github.com/eclecticiq/python-data-uri',
license="BSD",
classifiers=[
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tox]
envlist = py33,py34,py35,py36
envlist = py34,py35,py36

[testenv]
deps=-rrequirements-test.txt
Expand Down