Pickle / zodb: how to handle .py files with class definitions?

I use ZODB , which, as I understand it, uses pickle to store class instances. I am refactoring where I want to split my models.py file into several files. However, if I do this, I don’t think pickle will be able to find class definitions and therefore will not be able to load objects that I have already saved in the database. What is the best way to deal with this problem?

+6
source share
3 answers

You can create aliases; because one models.py module breaks down into several new modules, you can do this by importing your classes into the same location.

Both methods make new copies of your salty individuals access a new location; if you can force all instances of relocated classes to be written, you don't need to keep aliases. You can do this by setting _p_changed to True in your instances that you want to write again.

So, to create aliases, import the moved classes in the same place:

 from newmodule1 import MyClass1, MyClass2 from newmodule2 import MyClass3 

If you are only renaming a module (so the same classes are all in the same new place, it could be the set of imports themselves), you can also create a sys.modules entry for the old name:

 import sys import newmodule sys.modules['full.path.to.old.module] = newmodule 
+4
source

As long as you want to make the boot pendulum loaded without switching to the new structure of the class model: you can use aliases of imported refactored classes inside the location of the old model.py.

+3
source

Unfortunately, there is no easy solution. You can convert old-style objects with refactored ones (I mean classes that are in another file / module) according to the following scheme

  • add reprocessed classes to your code without deleting old ones
  • go through your database starting from the root and replacing all old objects with new equivalents.
  • compress your database (which is important)
  • now you can remove old classes from sources
+1
source

Source: https://habr.com/ru/post/923982/


All Articles