国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2019-11-25 17:08:46
字體:
供稿:網(wǎng)友

SessionMiddleware 激活后,每個(gè)傳給視圖(view)函數(shù)的第一個(gè)參數(shù)``HttpRequest`` 對象都有一個(gè) session 屬性,這是一個(gè)字典型的對象。 你可以象用普通字典一樣來用它。 例如,在視圖(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() 對 request.session 同樣有效:

下面是一些有效使用Django sessions的簡單規(guī)則:

    用正常的字符串作為key來訪問字典 request.session , 而不是整數(shù)、對象或其它什么的。

    Session字典中以下劃線開頭的key值是Django內(nèi)部保留key值。 框架只會(huì)用很少的幾個(gè)下劃線 開頭的session變量,除非你知道他們的具體含義,而且愿意跟上Django的變化,否則,最好 不要用這些下劃線開頭的變量,它們會(huì)讓Django攪亂你的應(yīng)用。

    比如,不要象這樣使用`` _fav_color`` 會(huì)話密鑰(session key):

request.session['_fav_color'] = 'blue' # Don't do this!

    不要用一個(gè)新對象來替換掉 request.session ,也不要存取其屬性。 可以像Python中的字典那樣使用。 例如:

request.session = some_other_object # Don't do this!request.session.foo = 'bar' # Don't do this!

我們來看個(gè)簡單的例子。 這是個(gè)簡單到不能再簡單的例子:在用戶發(fā)了一次評論后將has_commented設(shè)置為True。 這是個(gè)簡單(但不很安全)的、防止用戶多次評論的方法。

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è)很簡單的站點(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è)在上面已通過`` login()`` 登錄的用戶:

def logout(request): try:  del request.session['member_id'] except KeyError:  pass return HttpResponse("You're logged out.")

注意

在實(shí)踐中,這是很爛的用戶登錄方式,稍后討論的認(rèn)證(authentication )框架會(huì)幫你以更健壯和有利的方式來處理這些問題。 這些非常簡單的例子只是想讓你知道這一切是如何工作的。 這些實(shí)例盡量簡單,這樣你可以更容易看到發(fā)生了什么
設(shè)置測試Cookies

就像前面提到的,你不能指望所有的瀏覽器都可以接受cookie。 因此,為了使用方便,Django提供了一個(gè)簡單的方法來測試用戶的瀏覽器是否接受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() 分開的做法看起來有些笨拙,但由于cookie的工作方式,這無可避免。 當(dāng)設(shè)置一個(gè)cookie時(shí)候,只能等瀏覽器下次訪問的時(shí)候,你才能知道瀏覽器是否接受cookie。

檢查cookie是否可以正常工作后,你得自己用 delete_test_cookie() 來清除它,這是個(gè)好習(xí)慣。 在你證實(shí)了測試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ì)幫你做檢查的。

 

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 鄂尔多斯市| 广丰县| 博野县| 渝北区| 陆河县| 铅山县| 浠水县| 泸溪县| 印江| 报价| 通道| 安西县| 西丰县| 克什克腾旗| 尚志市| 金昌市| 江达县| 卢湾区| 融水| 宣城市| 洛扎县| 河北区| 绍兴县| 张家口市| 汉中市| 上杭县| 湖南省| 光山县| 郴州市| 许昌市| 万安县| 怀宁县| 平江县| 原阳县| 东兴市| 吉林市| 乡城县| 盐池县| 乌审旗| 娄烦县| 荔浦县|