问题描述
我在Django中腌制Python对象并将其保存在MySQL数据库中。到目前为止,我已经遵循了这些简单的规则:
-
cPickle.dumps(object)
#将python对象转换为pickled对象 -
cPickle.loads(pickled_object)
#从腌制对象加载python对象 -
我的Django
模型字段
是文本字段
-
MySQL数据库字段类型为
longblob
属性二进制
-
MySQL数据库编码是
utf8_unicode_ci
不幸的是,我在加载python对象时收到以下错误。
类型错误:('需要整数',< type'datetime.date'>,('x07xb6x0bx06'))
在我看来,通过查看错误值 x07xb6x0bx06
这是一个编码问题。
我想念一些重要的一步吗?可以有人帮我解决这个问题吗?
如果你试图存储 cPickle.dumps 在 VARCHAR
列中,那么您的问题是您尝试将字符串存储在字符列中。在这种情况下的修复是将您的对象编码为 unicode(base64.encode(cPickle.dumps(myobject)))
然后存储。
或者:
object2varchar = lambda obj:unicode(base64.encode(cPickle.dumps )))
store(object2varchar([1,'foo']))
I am pickling Python Objects in Django and saving it in MySQL db.So far i have followed these simple rules:
cPickle.dumps(object)
#to convert python object to pickled objectcPickle.loads(pickled_object)
# to load back the python object from pickled objectMy Django
Model Field
isText Field
MySQL db field Type is
longblob
Attributesbinary
MySQL db encoding is
utf8_unicode_ci
Unfortunately i am getting following error while loading back python object.
Type Error: ('an integer is required', <type 'datetime.date'>, ('x07xb6x0bx06',))
It seems to me by looking on error value x07xb6x0bx06
this is an encoding problem.Did i miss some important step?? Can any one help me to solve this problem??
If you are trying to store the output of cPickle.dumps
in a VARCHAR
column, then your issue is that you are trying to store a byte-string in a character column. The fix in that case is to encode your object as unicode(base64.encode(cPickle.dumps(myobject)))
and then store it.
Alternatively:
object2varchar = lambda obj: unicode(base64.encode(cPickle.dumps(obj)))
store(object2varchar([1, 'foo']))
这篇关于在Python中保存Python Pickled对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!