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正则匹配查询港澳通行证办理进度示例分享
Dec 27 Python
python创建线程示例
May 06 Python
Python中还原JavaScript的escape函数编码后字符串的方法
Aug 22 Python
python字符类型的一些方法小结
May 16 Python
在Pycharm中设置默认自动换行的方法
Jan 16 Python
实例介绍Python中整型
Feb 11 Python
Python中查看变量的类型内存地址所占字节的大小
Jun 26 Python
python global关键字的用法详解
Sep 05 Python
Python使用Pandas库常见操作详解
Jan 16 Python
Python反爬虫伪装浏览器进行爬虫
Feb 28 Python
Python导入模块包原理及相关注意事项
Mar 25 Python
vue.js刷新当前页面的实例讲解
Dec 29 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
php array_key_exists() 与 isset() 的区别
2016/10/24 PHP
不间断滚动JS打包类,基本可以实现所有的滚动效果,太强了
2007/12/08 Javascript
JavaScript的public、private和privileged模式
2009/12/28 Javascript
Extjs学习过程中新手容易碰到的低级错误积累
2010/02/11 Javascript
从零开始学习jQuery (四) jQuery中操作元素的属性与样式
2011/02/23 Javascript
基于jquery实现拆分姓名的方法(纯JS版)
2013/05/08 Javascript
JS实现图片横向滚动效果示例代码
2013/09/04 Javascript
jQuery中Dom的基本操作小结
2014/01/23 Javascript
JQuery CheckBox(复选框)操作方法汇总
2015/04/15 Javascript
jquery分隔Url的param方法(推荐)
2016/05/25 Javascript
jQuery实现的购物车物品数量加减功能代码
2016/11/16 Javascript
浅析Ajax语法
2016/12/05 Javascript
使用Webpack提高Vue.js应用的方式汇总(四种)
2017/07/10 Javascript
Vue项目中设置背景图片方法
2018/02/21 Javascript
js实现web调用摄像头 js截取视频画面
2019/04/21 Javascript
iphone刘海屏页面适配方法
2019/05/07 Javascript
vue实现行列转换的一种方法
2019/08/06 Javascript
[32:56]完美世界DOTA2联赛PWL S3 Rebirth vs CPG 第二场 12.11
2020/12/16 DOTA
使用python编写android截屏脚本双击运行即可
2014/07/21 Python
python脚本替换指定行实现步骤
2017/07/11 Python
Python设计模式之门面模式简单示例
2018/01/09 Python
python3 kmp 字符串匹配的方法
2018/07/07 Python
Python实现合并excel表格的方法分析
2019/04/13 Python
tensorflow 保存模型和取出中间权重例子
2020/01/24 Python
python字典和json.dumps()的遇到的坑分析
2020/03/11 Python
python zip,lambda,map函数代码实例
2020/04/04 Python
Python浮点型(float)运算结果不正确的解决方案
2020/09/22 Python
HTML5的download属性详细介绍和使用实例
2014/04/23 HTML / CSS
HTML5中drawImage用法分析
2014/12/01 HTML / CSS
行政专员岗位职责
2014/01/02 职场文书
新教师工作感言
2014/02/16 职场文书
英文自荐信常用句子
2014/03/26 职场文书
《祁黄羊》教学反思
2014/04/22 职场文书
农村党员一句话承诺
2014/05/30 职场文书
写给导师的自荐信
2015/03/06 职场文书
扩展多台相同的Web服务器
2021/04/01 Servers