SessionMiddleware 激活后,每個傳給視圖(view)函數的第一個參數``HttpRequest`` 對象都有一個 session 屬性,這是一個字典型的對象。 你可以象用普通字典一樣來用它。 例如,在視圖(view)中你可以這樣用:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# Set a session value: request.session[ "fav_color" ] = "blue" # Get a session value -- this could be called in a different view, # or many requests later (or both): fav_color = request.session[ "fav_color" ] # Clear an item from the session: del request.session[ "fav_color" ] # Check if the session has a given key: if "fav_color" in request.session: ... |
其他的映射方法,如 keys() 和 items() 對 request.session 同樣有效:
下面是一些有效使用Django sessions的簡單規則:
用正常的字符串作為key來訪問字典 request.session , 而不是整數、對象或其它什么的。
Session字典中以下劃線開頭的key值是Django內部保留key值。 框架只會用很少的幾個下劃線 開頭的session變量,除非你知道他們的具體含義,而且愿意跟上Django的變化,否則,最好 不要用這些下劃線開頭的變量,它們會讓Django攪亂你的應用。
比如,不要象這樣使用`` _fav_color`` 會話密鑰(session key):
1
|
request.session[ '_fav_color' ] = 'blue' # Don't do this! |
不要用一個新對象來替換掉 request.session ,也不要存取其屬性。 可以像Python中的字典那樣使用。 例如:
1
2
3
|
request.session = some_other_object # Don't do this! request.session.foo = 'bar' # Don't do this! |
我們來看個簡單的例子。 這是個簡單到不能再簡單的例子:在用戶發了一次評論后將has_commented設置為True。 這是個簡單(但不很安全)的、防止用戶多次評論的方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
def post_comment(request): if request.method ! = 'POST' : raise Http404( 'Only POSTs are allowed' ) if 'comment' not in request.POST: raise Http404( 'Comment not submitted' ) if request.session.get( 'has_commented' , False ): return HttpResponse( "You've already commented." ) c = comments.Comment(comment = request.POST[ 'comment' ]) c.save() request.session[ 'has_commented' ] = True return HttpResponse( 'Thanks for your comment!' ) |
下面是一個很簡單的站點登錄視圖(view):
1
2
3
4
5
6
7
8
9
10
|
def login(request): if request.method ! = 'POST' : raise Http404( 'Only POSTs are allowed' ) try : m = Member.objects.get(username = request.POST[ 'username' ]) if m.password = = request.POST[ 'password' ]: request.session[ 'member_id' ] = m. id return HttpResponseRedirect( '/you-are-logged-in/' ) except Member.DoesNotExist: return HttpResponse( "Your username and password didn't match." ) |
下面的例子將登出一個在上面已通過`` login()`` 登錄的用戶:
1
2
3
4
5
6
|
def logout(request): try : del request.session[ 'member_id' ] except KeyError: pass return HttpResponse( "You're logged out." ) |
注意
在實踐中,這是很爛的用戶登錄方式,稍后討論的認證(authentication )框架會幫你以更健壯和有利的方式來處理這些問題。 這些非常簡單的例子只是想讓你知道這一切是如何工作的。 這些實例盡量簡單,這樣你可以更容易看到發生了什么
設置測試Cookies
就像前面提到的,你不能指望所有的瀏覽器都可以接受cookie。 因此,為了使用方便,Django提供了一個簡單的方法來測試用戶的瀏覽器是否接受cookie。 你只需在視圖(view)中調用 request.session.set_test_cookie(),并在后續的視圖(view)、而不是當前的視圖(view)中檢查 request.session.test_cookie_worked() 。
雖然把 set_test_cookie() 和 test_cookie_worked() 分開的做法看起來有些笨拙,但由于cookie的工作方式,這無可避免。 當設置一個cookie時候,只能等瀏覽器下次訪問的時候,你才能知道瀏覽器是否接受cookie。
檢查cookie是否可以正常工作后,你得自己用 delete_test_cookie() 來清除它,這是個好習慣。 在你證實了測試cookie已工作了之后這樣操作。
這是個典型例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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' ) |
注意
再次強調,內置的認證函數會幫你做檢查的。