如何在Django中通过注销/重新登录来保存和恢复会话数据? [英] How to save and restore session data across logout/relogin in Django?

查看:70
本文介绍了如何在Django中通过注销/重新登录来保存和恢复会话数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个学习网站,该网站存储有关用户进度的各种数据.目前,我正在使用会话来执行此操作.我想要以下行为:

I'm building a learning website that stores various data about the user's progress. Currently, I'm using sessions to do this. I want the following behaviour:

  1. 未注册的用户可以稍后返回该站点,该站点将记住他们的进度.
  2. 用户创建帐户后,他们不会丢失任何有关已收集进度的数据.
  3. 注册用户注销后,其进度应被隐藏.
  4. 注册用户重新登录后,应恢复其进度.

会话对于行为1-3非常有用,但是在步骤4上,进度无法恢复.如果我了解Django如何正确处理会话,那么当用户注销时,所有会话数据都会被销毁.当用户重新登录时,保存此数据并再次还原的最佳方法是什么?

Sessions work great for behaviors 1-3, but on step 4 the progress fails to be restored. If I understand how Django handles sessions correctly, all of the session data is destroyed when the user logs out. What would be the best way to save this data and restore it again when the user logs back in?

推荐答案

似乎没有最好的方法,但是我想出的解决方案效果很好,所以我想我会分享它.

It seems like there's no best one way to do this, but the solution I came up with works well so I thought I would share it.

我创建了一个单独的表,用于永久存储注册用户的键/值对.理想情况下,您可能希望将数据存储为序列化JSON,类似于django_sesssion表的工作方式,但是简单的字符字段也可以工作:

I created a separate table for storing key/value pairs permanently for registered users. Ideally, you might want to store the data as serialized JSON similar to how the django_sesssion table works, but simple character fields will also work:

class account_data(models.Model):
    username = models.CharField(max_length=30)
    key = models.CharField(max_length=30)
    value = models.CharField(max_length=30, null=True, blank=True)
    class Meta:
        unique_together = ("username", "key")

每次我要保存或检索一个键值对时,我都会检查用户是否登录.如果不是,则将数据保存到会话中.如果是这样,我将数据保存到account_data表中.我构建了一些函数来处理此问题:

Each time I want to save or retrieve a key value pair, I check if the user is logged in. If they aren't, I save the data to the session. If they are, I save the data to the account_data table. I built some functions to handle this:

from account_manager.models import account_data

def getSessionOrAccountData(request, key):
    if request.user.is_authenticated():
        username = request.user.username
        try:
            record = account_data.objects.get(username=username, key=key)
            return record.value
        except:
            return None
    else:
        if key in request.session.keys():
            return request.session[key]
        else:
            return None

def setSessionOrAccountData(request, key, value):
    if request.user.is_authenticated():
        username = request.user.username
        try:
            record = account_data.objects.get(username=username, key=key)
            record.value = value
            record.save()
        except account_data.DoesNotExist:
            record = account_data(username=username, key=key, value=str(value))
            record.save()
    else:
        request.session[key] = value

def deleteSessionOrAccountData(request, key):
    if request.user.is_authenticated():
        username = request.user.username
        account_data.objects.filter(username=username).filter(key=key).delete()
    else:
        del request.session[key]

最后,当用户创建一个新帐户时,我想将他们可能拥有的所有会话数据复制到account_data表中.创建新用户帐户后,将立即运行以下代码:

Finally, when a user creates a new account, I want to copy any session data they might have over to the account_data table. The following code is run right after the new user account is created:

# save all existing session data to new user account
for key in request.session.keys():
    record = account_data(username=request.POST['username'], 
                                  key=key, 
                                  value=str(request.session[key]))
    record.save()

这篇关于如何在Django中通过注销/重新登录来保存和恢复会话数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆