saving python object in postgres table with pickle

半腔热情 提交于 2021-02-04 07:31:12

问题


I have a python script which creates some objects. I would like to be able to save these objects into my postgres database for use later.

My thinking was I could pickle an object, then store that in a field in the db. But I'm going round in circles about how to store and retrieve and use the data.

I've tried storing the pickle binary string as text but I can't work out how to encode / escape it. Then how to load the string as a binary string to unpickle.

I've tried storing the data as bytea both with psycopg2.Binary(data) and without. Then reading into buffer and encoding with base64.b64encode(result) but it's not coming out the same and cannot be unpickled.

Is there a simple way to store and retrieve python objects in a SQL (postgres) database?


回答1:


Following the comment from @SergioPulgarin I tried the following which worked!

N.B Edit2 following comment by @Tomalak

Storing:

  1. Pickle the object to a binary string

    pickle_string = pickle.dumps(object)

  2. Store the pickle string in a bytea (binary) field in postgres. Use simple INSERT query in Psycopg2

Retrieval:

  1. Select the field in Psycopg2. (simple SELECT query)

  2. Unpickle the decoded result

    retrieved_pickle_string = pickle.loads(decoded_result)

Hope that helps anybody trying to do something similar!



来源:https://stackoverflow.com/questions/57642165/saving-python-object-in-postgres-table-with-pickle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!