Python的Bottle框架中获取制定cookie的教程


Posted in Python onApril 24, 2015

这两天为用bottle+mongodb写的一个项目加上登录功能,无奈怎么都获取不到保存的cookie,文档给出让我们这样操作cookie的代码片段:

@route('/login')
def login ():
   username = request .forms .get('username ')
   password = request .forms .get('password ')
   if check_user_credentials(username, password):
      response .set_cookie("account", username, secret= 'some-secret-key')
      return "Welcome %s!You are now logged in." % username
   else :
      return "Login failed." 

@route('/restricted')
def restricted_area ():
   username = request .get_cookie("account", secret= 'some-secret-key')
   if username:
      return "Hello %s.Welcome back." % username

虽然文档上没有但是还有一种操作cookie的方式:

from bottle import request, response

@route('/login', method="POST")
def login():
  user = request.POST['user']
  passwd = request.POST['passwd']

  if check_user_right(user,passwd):
    response.COOKIES['account'] = user
  else:
    pass

@route('/admin')
def admin():
  user = request.COOKIES['user']
  if user:
    pass

但是无论我用哪种方式操作我都无法获取cookie,为什么呢.百思不得其解.但是我的一个处理文章点击率的提醒了我,代码如下:

@route('/archrives/:aid#\d+#')
def article_show(aid):
  db = dbconn.ConnDB()
  artid = int(aid)
  # 获取客户端ip
  remoteip = request.environ.get('REMOTE_ADDR')

  artcookie = remoteip+'ip'+aid
  print request.COOKIES.keys()

  # 判断cookie是否存在
  if artcookie in request.COOKIES.keys():
    # 存在则更新有效时间
    response.COOKIES[artcookie] = True
    response.COOKIES[artcookie]['max-age'] = 500
  else:
    # 不存在则更新文章查看次数
    db.posts.update({"id":artid}, {"$inc":{"views":1}})

    # 并设置cookie
    response.COOKIES[artcookie] = True
    response.COOKIES[artcookie]['max-age'] = 500

  TEMPLATE['posts'] = getArtList({"id":artid})
  TEMPLATE.update(setTempVar())

  return template('article.html', TEMPLATE)

这里是可以正常获取到cookie的,而且代码没有任何区别.唯一的区别就是用户认证是跳转了页面.所以我help了一下:

from bottle import response
help(response.set_cookie)

help的结果其中有两个参数一个是path,和domain:

   

:param domain: the domain that is allowed to read the cookie.
   (default: current domain)
  :param path: limits the cookie to a given path (default: current path)

明显bottle的cookie默认只在当前路径下能读取的到,所以要别的页面读取到cookie我们的代码须改成如下:

from bottle import request, response

@route('/login', method="POST")
def login():
  user = request.POST['user']
  passwd = request.POST['passwd']

  if check_user_right(user,passwd):
    response.COOKIES['account'] = user
    response.COOKIES['account']['path'] = '/admin'
  else:
    pass

@route('/admin')
def admin():
  user = request.COOKIES['user']

这样我们就能在别的路径下访问我们设定的cookie.

Python 相关文章推荐
跟老齐学Python之Import 模块
Oct 13 Python
Python中的下划线详解
Jun 24 Python
Python 数据结构之堆栈实例代码
Jan 22 Python
Python实现图片转字符画的示例代码
Aug 21 Python
python 随机数使用方法,推导以及字符串,双色球小程序实例
Sep 12 Python
如何使用Python自动控制windows桌面
Jul 11 Python
简单了解django orm中介模型
Jul 30 Python
Python Web框架之Django框架cookie和session用法分析
Aug 16 Python
Python中PyQt5/PySide2的按钮控件使用实例
Aug 17 Python
使用python的turtle绘画滑稽脸实例
Nov 21 Python
Django模板获取field的verbose_name实例
May 19 Python
解决python3安装pandas出错的问题
May 20 Python
利用Python的装饰器解决Bottle框架中用户验证问题
Apr 24 #Python
在Python中使用mongoengine操作MongoDB教程
Apr 24 #Python
python使用arp欺骗伪造网关的方法
Apr 24 #Python
python使用wxPython打开并播放wav文件的方法
Apr 24 #Python
python使用PyGame播放Midi和Mp3文件的方法
Apr 24 #Python
python使用PyGame绘制图像并保存为图片文件的方法
Apr 24 #Python
python使用PIL缩放网络图片并保存的方法
Apr 24 #Python
You might like
用PHP4访问Oracle815
2006/10/09 PHP
PHP与SQL注入攻击防范小技巧
2011/09/16 PHP
表格展示无限级分类(PHP版)
2012/08/21 PHP
thinkphp普通查询与表达式查询实例分析
2014/11/24 PHP
Add a Table to a Word Document
2007/06/15 Javascript
json格式化/压缩工具 Chrome插件扩展版
2010/05/25 Javascript
判定是否原生方法的JS代码
2013/11/12 Javascript
javascript的动态加载、缓存、更新以及复用(一)
2014/06/09 Javascript
JavaScript列表框listbox全选和反选的实现方法
2015/03/18 Javascript
BootStrap点击下拉菜单项后显示一个新的输入框实现代码
2016/05/16 Javascript
JavaScript 对象字面量讲解
2016/06/06 Javascript
JS请求servlet功能示例
2017/06/01 Javascript
Vue-router 类似Vuex实现组件化开发的示例
2017/09/15 Javascript
element 结合vue 在表单验证时有值却提示错误的解决办法
2018/01/22 Javascript
总结js函数相关知识点
2018/02/27 Javascript
如何从零开始手写Koa2框架
2019/03/22 Javascript
react使用antd表单赋值,用于修改弹框的操作
2020/10/29 Javascript
python实现去除下载电影和电视剧文件名中的多余字符的方法
2014/09/23 Python
Python两个内置函数 locals 和globals(学习笔记)
2016/08/28 Python
深入理解Django的自定义过滤器
2017/10/17 Python
Python生成器以及应用实例解析
2018/02/08 Python
tensorflow 输出权重到csv或txt的实例
2018/06/14 Python
Python实现二维曲线拟合的方法
2018/12/29 Python
详解pandas数据合并与重塑(pd.concat篇)
2019/07/09 Python
解析Python3中的Import
2019/10/13 Python
Python Tkinter模块 GUI 可视化实例
2019/11/20 Python
django处理select下拉表单实例(从model到前端到post到form)
2020/03/13 Python
详解python中groupby函数通俗易懂
2020/05/14 Python
Python 如何测试文件是否存在
2020/07/31 Python
next在python中返回迭代器的实例方法
2020/12/15 Python
深入解析HTML5 Canvas控制图形矩阵变换的方法
2016/03/24 HTML / CSS
HTML5头部标签的一些常用信息小结
2016/10/23 HTML / CSS
大龄毕业生求职别忘职业规划
2014/03/11 职场文书
2014年中秋寄语
2014/08/11 职场文书
写给女朋友的检讨书
2015/05/06 职场文书
销售合作意向书范本
2015/05/08 职场文书