一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - 在Python的Django框架的視圖中使用Session的方法

在Python的Django框架的視圖中使用Session的方法

2020-07-26 11:04Python教程網 Python

這篇文章主要介紹了在Python的Django框架的視圖中使用Session的方法,包括相關的設置測試Cookies的方法,需要的朋友可以參考下

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')

注意

再次強調,內置的認證函數會幫你做檢查的。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 色播影院性播影院私人影院 | 欧美透逼视频 | porno movie hd高清 | 春光乍泄在线 | 免费国产午夜高清在线视频 | h网站国产| 99热国产这里只有精品99 | 欧美色青 | 国产三级跑 | 国内自拍网红在线自拍综合 | 天天爽天天操 | 小兰被扒开内裤露出p | 星空无限传媒xk8129 | 共妻高h | 日本加勒比一区 | 欧美x×x| 糖心在线观看网 | 四虎影视永久在线观看 | 亚洲乱码尤物193yw在线播放 | 我被黑人彻底征服的全文 | 免费高清观看 | 国产视频一区二区 | 久久永久视频 | 四虎伊人 | 太大了轻点阿受不了小说h 四色6677最新永久网站 | 91超级碰| 国产成人福利免费观看 | 午夜精品亚洲 | juliaann厨房大战 | 秋霞黄色网 | 九九热视频免费 | 91九色视频无限观看免费 | 不良小说 | 欧美人xxxxxbbbb | 国产亚洲欧美在线中文bt天堂网 | 欧美高清乌克兰精品另类 | 久久免费资源福利资源站 | 高中生放荡日记高h娜娜 | 91国内在线国内在线播放 | 秋葵丝瓜茄子草莓榴莲樱桃 | 色先锋av资源中文字幕 |