【问题标题】:How to save an image in postgres bytea field in ascii encoding with django如何使用 django 以 ascii 编码将图像保存在 postgres bytea 字段中
【发布时间】:2012-10-03 09:35:09
【问题描述】:

我正在尝试通过将图像转换为 base64 并将其保存到 postgresql 中的“bytea”字段来在 django 中保存图像。我设法做到了,但字符串是用 UTF8 编码的。有没有办法只为这个字段编码为 ascii?

这是我的自定义 Base64 模型字段的代码:

import base64
from django.db import models

class Base64Field(models.TextField):

    def contribute_to_class(self, cls, name):
        if self.db_column is None:
            self.db_column = name
        self.field_name = name + '_base64'
        super(Base64Field, self).contribute_to_class(cls, self.field_name)
        setattr(cls, name, property(self.get_data, self.set_data))

    def get_data(self, obj):
        #return obj.data_base64 #this works if the image is ascii-encoded
        return base64.b64decode(getattr(obj, self.field_name)) #this also works well with the setter below

    def set_data(self, obj, data):
        setattr(obj, self.field_name, base64.encodestring(data)) #is encoded to UTF8

    def db_type(self, connection):
        return 'longtext'

【问题讨论】:

    标签: django postgresql


    【解决方案1】:

    要么使用带有base64编码文本的text字段,要么将二进制数据存储在bytea字段中。不要将 base64 编码的二进制文件存储在 bytea 字段中,这只会令人困惑。

    我推荐使用bytea 和bytea_output = 'hex'(9.0 及以上版本默认)。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2017-01-27
    • 2011-12-15
    • 2021-06-25
    相关资源
    最近更新 更多