python中用于数据uri操作的li'l类
python-datauri的Python项目详细描述
数据uri操作变得简单。
这不是很健壮,并且会拒绝一些有效的数据uri。但是,它遇到了最有用的情况:mimetype、字符集和base64标志。
安装
$ pip install python-datauri
解析
>>>fromdatauriimportDataURI>>>uri=DataURI('data:text/plain;charset=utf-8;base64,VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wZWQgb3ZlciB0aGUgbGF6eSBkb2cu')>>>uri.mimetype'text/plain'>>>uri.charset'utf-8'>>>uri.is_base64True>>>uri.datab'The quick brown fox jumped over the lazy dog.'
注意,DataURI.data将始终返回字节(在python 2中,字节与字符串相同)。 使用DataURI.text获取文本类型(python 3.x上的str,python 2.x上的unicode)。
从字符串创建
>>>fromdatauriimportDataURI>>>made=DataURI.make('text/plain',charset='us-ascii',base64=True,data='This is a message.')>>>madeDataURI('data:text/plain;charset=us-ascii;base64,VGhpcyBpcyBhIG1lc3NhZ2Uu')>>>made.datab'This is a message.'
从文件创建
这其实只是一种方便的方法。
>>>fromdatauriimportDataURI>>>png_uri=DataURI.from_file('somefile.png')>>>png_uri.mimetype'image/png'>>>png_uri.datab'\x89PNG\r\n...'
许可证
此代码在Unlicense下发布。
学分
这是this Gist的重新包装 最初由Zachary Voase撰写。