在Python的Django框架的视图中使用Session的方法


Posted in Python onJuly 23, 2015

SessionMiddleware 激活后,每个传给视图(view)函数的第一个参数``HttpRequest`` 对象都有一个 session 属性,这是一个字典型的对象。 你可以象用普通字典一样来用它。 例如,在视图(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的简单规则:

    用正常的字符串作为key来访问字典 request.session , 而不是整数、对象或其它什么的。

    Session字典中以下划线开头的key值是Django内部保留key值。 框架只会用很少的几个下划线 开头的session变量,除非你知道他们的具体含义,而且愿意跟上Django的变化,否则,最好 不要用这些下划线开头的变量,它们会让Django搅乱你的应用。

    比如,不要象这样使用`` _fav_color`` 会话密钥(session key):

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

    不要用一个新对象来替换掉 request.session ,也不要存取其属性。 可以像Python中的字典那样使用。 例如:

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

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

我们来看个简单的例子。 这是个简单到不能再简单的例子:在用户发了一次评论后将has_commented设置为True。 这是个简单(但不很安全)的、防止用户多次评论的方法。

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

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()`` 登录的用户:

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已工作了之后这样操作。

这是个典型例子:

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

注意

再次强调,内置的认证函数会帮你做检查的。

 

Python 相关文章推荐
python使用PyGame播放Midi和Mp3文件的方法
Apr 24 Python
python中关于for循环的碎碎念
Jun 30 Python
Python代码实现KNN算法
Dec 20 Python
Python实现简单的文本相似度分析操作详解
Jun 16 Python
python抓取网页内容并进行语音播报的方法
Dec 24 Python
使用Python批量修改文件名的代码实例
Jan 24 Python
树莓派使用USB摄像头和motion实现监控
Jun 22 Python
python多进程间通信代码实例
Sep 30 Python
pyqt5 QlistView列表显示的实现示例
Mar 24 Python
Python优秀开源项目Rich源码解析的流程分析
Jul 06 Python
python 实现压缩和解压缩的示例
Sep 22 Python
python基础之函数的定义和调用
Oct 24 Python
详解Python的Django框架中的Cookie相关处理
Jul 22 #Python
在Django中使用Sitemap的方法讲解
Jul 22 #Python
用Python的Django框架来制作一个RSS阅读器
Jul 22 #Python
利用Python的Django框架生成PDF文件的教程
Jul 22 #Python
在Python的Django框架中生成CSV文件的方法
Jul 22 #Python
在主机商的共享服务器上部署Django站点的方法
Jul 22 #Python
在Lighttpd服务器中运行Django应用的方法
Jul 22 #Python
You might like
PHP模块memcached使用指南
2014/12/08 PHP
php版阿里大于(阿里大鱼)短信发送实例详解
2016/11/30 PHP
javascript编程起步(第五课)
2007/01/10 Javascript
js实现收缩菜单效果实例代码
2013/10/30 Javascript
window.location.href IE下跳转失效的解决方法
2014/03/27 Javascript
javascript数组随机排序实例分析
2015/07/22 Javascript
20分钟成功编写bootstrap响应式页面 就这么简单
2016/05/12 Javascript
Jquery Easyui选项卡组件Tab使用详解(10)
2016/12/18 Javascript
js实现带缓动动画的导航栏效果
2017/01/16 Javascript
详解vue2.0 不同屏幕适配及px与rem转换问题
2018/02/23 Javascript
jquery ajaxfileuplod 上传文件 essyui laoding 效果【防止重复上传文件】
2018/05/26 jQuery
微信小程序左滑动显示菜单功能的实现
2018/06/14 Javascript
解决vue项目使用font-awesome,build后路径的问题
2018/09/01 Javascript
ztree加载完成后显示勾选节点的实现代码
2018/10/22 Javascript
如何使用VuePress搭建一个类型element ui文档
2019/02/14 Javascript
在vue中使用console.log无效的解决
2020/08/09 Javascript
JavaScript实现点击图片换背景
2020/11/20 Javascript
python模拟登录并且保持cookie的方法详解
2017/04/04 Python
Python编程实现的简单Web服务器示例
2017/06/22 Python
Python Selenium Cookie 绕过验证码实现登录示例代码
2018/04/10 Python
快速解决vue.js 模板和jinja 模板冲突的问题
2019/07/26 Python
python多线程实现TCP服务端
2019/09/03 Python
详解Django配置JWT认证方式
2020/05/09 Python
Jupyter notebook如何实现指定浏览器打开
2020/05/13 Python
Python验证码截取识别代码实例
2020/05/16 Python
简述python&pytorch 随机种子的实现
2020/10/07 Python
html5 postMessage解决跨域、跨窗口消息传递方案
2016/12/20 HTML / CSS
Easy Spirit官网:美国休闲鞋履中的代表品牌
2019/04/12 全球购物
房地产融资计划书
2014/01/10 职场文书
军训 自我鉴定
2014/02/03 职场文书
校园游戏活动新闻稿
2014/10/15 职场文书
幼儿园安全工作总结2015
2015/04/20 职场文书
2015年医院药剂科工作总结
2015/05/04 职场文书
60条职场经典语录,总有一条能触动你的心
2019/08/21 职场文书
Python使用openpyxl批量处理数据
2021/06/23 Python
Nginx如何获取自定义请求header头和URL参数详解
2022/07/23 Servers