django中cookies和session

django中cookies和session是两个经常使用的用户认证工具。都是类似于字典的数据类型,都是request的内部属性

cookies的读写方法

cookies读,比如username
username=request.COOKIES['username']
cookies写,比如username='book'.需要使用 HttpResponse对象的 set_cookie()方法
response.set_cookie("username","book")

sessions设置就比较简单

session读
username=request.session['username']
session写
session['username']='book'

2 session中一般使用字符串作为key来操作,尽量不要使用下划线开始的字符串来作为key,常常会导致糟糕的结果。

3 在使用cookies之前一般需要认证用户是否可以使用cookies,测试cookies的方法如下

在view试图函数中调用request.session.set_test_cookie()来设置是不够的,一般需要两部操作。在提交数据的时候检查 request.session.test_cookie_worked(),他会返回True或False。如果成功需要删除cookies。使用request.session.delete_test_cookie()。

def login(request):

    # If we submitted the form...
    if request.method == 'POST':

        # Check that the test cookie worked (we set it below):
        if request.session.test_cookie_worked():

            # The test cookie worked, so delete it.
            request.session.delete_test_cookie()

            # In practice, we'd need some logic to check username/password
            # here, but since this is an example...
            return HttpResponse("You're logged in.")

        # The test cookie failed, so display an error message. If this
        # were a real site, we'd want to display a friendlier message.
        else:
            return HttpResponse("Please enable cookies and try again.")

    # If we didn't post, send the test cookie along with the login form.
    request.session.set_test_cookie()
    return render_to_response('foo/login_form.html')

4 设置cookies和session失效时间,在setting文件中

默认情况下SESSION_EXPIRE_AT_BROWSER_CLOSE 设置为 False ,这样,会话cookie可以在用户浏览器中保持有效达 SESSION_COOKIE_AGE 秒(缺省设置是两周,即1,209,600 秒)

如果 SESSION_EXPIRE_AT_BROWSER_CLOSE = True ,当浏览器关闭时,Django会使cookie失效。

5 django何时会修改session中的值

默认情况下,Django只会在session发生变化的时候才会存入数据库,比如说,字典赋值或删除

# Session is modified.
request.session['foo'] = 'bar'

# Session is modified.
del request.session['foo']

# Session is modified.
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'

你可以设置 SESSION_SAVE_EVERY_REQUEST 为 True 来改变这一缺省行为。如果置为True的话,Django会在每次收到请求的时候保存session,即使没发生变化。

原文地址:https://www.cnblogs.com/zhaopengcheng/p/5541535.html