Saving Python Pickled objects in MySQL db

后端 未结 4 1658
北海茫月
北海茫月 2020-12-14 22:55

I am pickling Python Objects in Django and saving it in MySQL db. So far i have followed these simple rules:

  1. cPickle.dumps(object) #to convert

相关标签:
4条回答
  • 2020-12-14 23:13

    Newtover's answer is probably the correct one, but have a look at

    https://github.com/bradjasper/django-pickledfield

    It really saved me some time, and can store pretty much anything you want.

    0 讨论(0)
  • 2020-12-14 23:28

    You can try this, now! django-picklefield https://pypi.org/project/django-picklefield/

    To use, just define a field in your model:

    >>> from picklefield.fields import PickledObjectField
    ... class SomeObject(models.Model):
    ...     args = PickledObjectField()
    

    and assign whatever you like (as long as it's picklable) to the field:

    >>> obj = SomeObject()
    >>> obj.args = ['fancy', {'objects': 'inside'}]
    >>> obj.save()
    
    0 讨论(0)
  • 2020-12-14 23:35

    one more rule: connect to mysql with option charset=utf8?

    UPD1: Sometimes it is a good idea to look at the complete SQL query, I usually do it that way:

    >>> conn = MySQLdb.connect(**db_params)
    >>> "INSERT INTO tbl VALUES (%s)" % conn.literal((your_pickled_item, ))
    
    0 讨论(0)
  • 2020-12-14 23:40

    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']))
    
    0 讨论(0)
提交回复
热议问题