Mri*_*lla 1 python django serialization json django-models
我正在尝试序列化我的一个模型ImageField.内置的序列化程序似乎无法序列化,因此我想到编写自定义序列化程序.你能告诉我如何序列化图像并将其与Django中的默认JSON序列化器一起使用吗?
谢谢
你不能序列化对象,因为它是一个图像。您必须序列化其路径的字符串表示形式。
实现它的最简单方法是在序列化它时调用它的 str() 方法。
json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3
Run Code Online (Sandbox Code Playgroud)
应该管用。
我写了一个simplejson编码器的扩展.而是将图像序列化为base643,它返回图像的路径.这是一个片段:
def encode_datetime(obj):
"""
Extended encoder function that helps to serialize dates and images
"""
if isinstance(obj, datetime.date):
try:
return obj.strftime('%Y-%m-%d')
except ValueError, e:
return ''
if isinstance(obj, ImageFieldFile):
try:
return obj.path
except ValueError, e:
return ''
raise TypeError(repr(obj) + " is not JSON serializable")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9513 次 |
| 最近记录: |