7

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?

DennisLi
  • 3,915
  • 6
  • 30
  • 66
Charlie Morton
  • 737
  • 1
  • 7
  • 17
  • 2
    Are you sure you are calling the `base64` functions in the right order? Just to check, what you want is: Storing `object` `->` `pickle` `->` `base64-encode` `->` `DB`. Reading back: `DB` `->` `base64-decode` `->` `unpickle` `->` `object`. – Sergio Pulgarin Aug 24 '19 at 23:45
  • 1
    I think this answer would help you. https://stackoverflow.com/questions/30469575/how-to-pickle-and-unpickle-to-portable-string-in-python-3 – Terry Jo Aug 25 '19 at 03:05
  • @SergioPulgarin I wasn't encoding before sending to the database. If I do that, should I store it as text or binary in the db? – Charlie Morton Aug 25 '19 at 08:32

1 Answers1

7

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!

Charlie Morton
  • 737
  • 1
  • 7
  • 17