我有一个叫
Chat
可以从自身存储和检索Cookie,如下所示:
>>> chat = Chat.objects.get(pk=43265)
>>> chat.cookies
>>> chat.set_cookie('1','2')
>>> chat.cookies
'{"1": "2"}'
这个
set_cookies
方法是用一个简单的
json.dumps
:
def set_cookie(self, key, value):
if self.cookies:
current_cookies = json.loads(self.cookies)
else:
current_cookies = dict()
current_cookies.update({key: value})
self.cookies = json.dumps(current_cookies)
self.save()
问题是,如果
chat
对象在两个不同的名称空间中检索,它们独立更新其Cookie,每一个都覆盖另一个的结果。
例子:
import django
django.setup()
from bots.models import Chat
# Let's clean all the cookies beforehand
c = Chat.objects.get(pk=43265)
c.cookies = None
c.save()
def outer_namespace():
chat = Chat.objects.get(pk=43265)
# here chat.cookies are empty
inner_namespace()
# Now we are supposed to have inner cookie here - right? Let's set another one.
chat.set_cookie('outer namespace cookie', '1')
# Let's retrieve the model again and see
print(Chat.objects.get(pk=43265).cookies)
def inner_namespace():
inner_chat = Chat.objects.get(pk=43265)
inner_chat.set_cookie('inner namespace cookie', '2')
outer_namespace()
如果我运行这个,我会得到:
>>> {"outer namespace cookie": "1"}
>>> # we lost one of the cookies!
如何避免这种情况?
我提出的唯一解决方案是重新检索
闲聊
对象位于其自身的中间
set_cookies
方法但这看起来很笨拙。
def set_cookie(self, key, value):
cookies = self.__class__.objects.get(pk=self.pk).cookies
#
# ... rest of the method stays the same