Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

postgresql - saving python object in postgres table with pickle

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...