【发布时间】:2011-11-21 18:23:32
【问题描述】:
我正在尝试序列化我的一个具有ImageField 的模型。内置的序列化程序似乎无法序列化,因此我想编写一个自定义序列化程序。你能告诉我如何序列化图像并将其与 Django 中的默认 JSON 序列化程序一起使用吗?
谢谢
【问题讨论】:
标签: python django json serialization django-models
我正在尝试序列化我的一个具有ImageField 的模型。内置的序列化程序似乎无法序列化,因此我想编写一个自定义序列化程序。你能告诉我如何序列化图像并将其与 Django 中的默认 JSON 序列化程序一起使用吗?
谢谢
【问题讨论】:
标签: python django json serialization django-models
我为 simplejson 编码器编写了一个扩展。它不是将图像序列化为 base643,而是返回图像的路径。这是一个sn-p:
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")
【讨论】:
ImageFieldFile 开箱即用相当...... Django 荒谬。
你不能序列化对象,因为它是一个图像。您必须序列化其路径的字符串表示形式。
实现它的最简单方法是在你对它进行序列化时调用它的 str() 方法。
json.dumps(unicode(my_imagefield)) # py2
json.dumps(str(my_imagefield)) # py3
应该可以。
【讨论】:
您可以尝试使用base64 encoding 来序列化要在 JSON 中使用的图像
【讨论】:
使用另一个编码器,这样:
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models.fields.files import ImageFieldFile
class ExtendedEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, ImageFieldFile):
return str(o)
else:
return super().default(o)
result = json.dumps(your_object, cls=ExtendedEncoder)
【讨论】: