在Python的Django框架的視圖中使用Session的方法
SessionMiddleware 激活后,每個(gè)傳給視圖(view)函數(shù)的第一個(gè)參數(shù)``HttpRequest`` 對(duì)象都有一個(gè) session 屬性,這是一個(gè)字典型的對(duì)象。 你可以象用普通字典一樣來(lái)用它。 例如,在視圖(view)中你可以這樣用:
# 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() 對(duì) request.session 同樣有效:
下面是一些有效使用Django sessions的簡(jiǎn)單規(guī)則:
用正常的字符串作為key來(lái)訪問(wèn)字典 request.session , 而不是整數(shù)、對(duì)象或其它什么的。
Session字典中以下劃線開(kāi)頭的key值是Django內(nèi)部保留key值。 框架只會(huì)用很少的幾個(gè)下劃線 開(kāi)頭的session變量,除非你知道他們的具體含義,而且愿意跟上Django的變化,否則,最好 不要用這些下劃線開(kāi)頭的變量,它們會(huì)讓Django攪亂你的應(yīng)用。
比如,不要象這樣使用`` _fav_color`` 會(huì)話密鑰(session key):
request.session['_fav_color'] = 'blue' # Don't do this!
不要用一個(gè)新對(duì)象來(lái)替換掉 request.session ,也不要存取其屬性。 可以像Python中的字典那樣使用。 例如:
request.session = some_other_object # Don't do this! request.session.foo = 'bar' # Don't do this!
我們來(lái)看個(gè)簡(jiǎn)單的例子。 這是個(gè)簡(jiǎn)單到不能再簡(jiǎn)單的例子:在用戶發(fā)了一次評(píng)論后將has_commented設(shè)置為True。 這是個(gè)簡(jiǎn)單(但不很安全)的、防止用戶多次評(píng)論的方法。
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!')
下面是一個(gè)很簡(jiǎn)單的站點(diǎn)登錄視圖(view):
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.")
下面的例子將登出一個(gè)在上面已通過(guò)`` login()`` 登錄的用戶:
def logout(request):
try:
del request.session['member_id']
except KeyError:
pass
return HttpResponse("You're logged out.")
注意
在實(shí)踐中,這是很爛的用戶登錄方式,稍后討論的認(rèn)證(authentication )框架會(huì)幫你以更健壯和有利的方式來(lái)處理這些問(wèn)題。 這些非常簡(jiǎn)單的例子只是想讓你知道這一切是如何工作的。 這些實(shí)例盡量簡(jiǎn)單,這樣你可以更容易看到發(fā)生了什么
設(shè)置測(cè)試Cookies
就像前面提到的,你不能指望所有的瀏覽器都可以接受cookie。 因此,為了使用方便,Django提供了一個(gè)簡(jiǎn)單的方法來(lái)測(cè)試用戶的瀏覽器是否接受cookie。 你只需在視圖(view)中調(diào)用 request.session.set_test_cookie(),并在后續(xù)的視圖(view)、而不是當(dāng)前的視圖(view)中檢查 request.session.test_cookie_worked() 。
雖然把 set_test_cookie() 和 test_cookie_worked() 分開(kāi)的做法看起來(lái)有些笨拙,但由于cookie的工作方式,這無(wú)可避免。 當(dāng)設(shè)置一個(gè)cookie時(shí)候,只能等瀏覽器下次訪問(wèn)的時(shí)候,你才能知道瀏覽器是否接受cookie。
檢查cookie是否可以正常工作后,你得自己用 delete_test_cookie() 來(lái)清除它,這是個(gè)好習(xí)慣。 在你證實(shí)了測(cè)試cookie已工作了之后這樣操作。
這是個(gè)典型例子:
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')
注意
再次強(qiáng)調(diào),內(nèi)置的認(rèn)證函數(shù)會(huì)幫你做檢查的。
相關(guān)文章
通過(guò)python掃描二維碼/條形碼并打印數(shù)據(jù)
這篇文章主要介紹了通過(guò)python掃描二維碼/條形碼并打印數(shù)據(jù),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
python進(jìn)階學(xué)習(xí)實(shí)時(shí)目標(biāo)跟蹤示例詳解
這篇文章主要為大家介紹了python進(jìn)階學(xué)習(xí)實(shí)時(shí)目標(biāo)跟蹤示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
Pygame Transform圖像變形的實(shí)現(xiàn)示例
pygame.transform 模塊允許您對(duì)加載、創(chuàng)建后的圖像進(jìn)行一系列操作,比如調(diào)整圖像大小、旋轉(zhuǎn)圖片等操作,感興趣的可以了解一下2021-11-11

