开发者

Using Django's memcache API on Dynamically created models

开发者 https://www.devze.com 2023-01-02 08:22 出处:网络
So I have a function which creates a dynamic model. I accomplish this in a way very similar to A开发者_运维知识库uditTrail (see django wiki).

So I have a function which creates a dynamic model. I accomplish this in a way very similar to A开发者_运维知识库uditTrail (see django wiki).

Sample of code is here:

https://gist.github.com/0212845ae00891efe555

Is there any way I can make a dynamically-generated class pickle-able? Ideally something thats not a crazy monkeypatch/hack?


I am aware of the problem where pickle can't store a generated or dynamic class. I solved this by rigging in my dynamic type into the modules dict like so:

new_class = type(name, (models.Model,), attrs)
mod = sys.modules[new_class.__module__]
mod.__dict__[new_class.__name__] = new_class

It's FAR from a clean or elegant solution, so if someone can think of a more django-friendly way to make this happen, I am all ears. However, the above code does work.


The reason there aren't answers for this is because the answer is likely hackish. I don't think you can unpickle an object in Python without knowing the structure of the class on the receiving end without some sort of hackish solution. A big reason pickle doesn't support it is probably because it's a fantastic way to introduce malicious code into your application.

http://www.mofeel.net/871-comp-lang-python/2898.aspx explains a bit why dynamically created classes can't be unpickled.

In every case, I've either just serialized a dictionary of the attributes of the object using the dict method, or just figured out some awful work around. I hope you come up with something better.

Good Luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消