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中对list去重的多种方法
Sep 18 Python
python中django框架通过正则搜索页面上email地址的方法
Mar 21 Python
Python三种遍历文件目录的方法实例代码
Jan 19 Python
PyQt5每天必学之QSplitter实现窗口分隔
Apr 19 Python
Python运维开发之psutil库的使用详解
Oct 18 Python
利用Python+阿里云实现DDNS动态域名解析的方法
Apr 01 Python
Python 绘制酷炫的三维图步骤详解
Jul 12 Python
安装PyInstaller失败问题解决
Dec 14 Python
在Keras中利用np.random.shuffle()打乱数据集实例
Jun 15 Python
python rsa-oaep加密的示例代码
Sep 23 Python
pandas中DataFrame数据合并连接(merge、join、concat)
May 30 Python
总结Python变量的相关知识
Jun 28 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中时间轴开发(刚刚、5分钟前、昨天10:23等)
2011/10/03 PHP
PHP的反射类ReflectionClass、ReflectionMethod使用实例
2014/08/05 PHP
Thinkphp5.0 框架实现控制器向视图view赋值及视图view取值操作示例
2019/10/12 PHP
开发跨浏览器javascript常见注意事项
2009/01/01 Javascript
Javascript学习笔记6 prototype的提出
2010/01/11 Javascript
js函数调用常用方法详解
2012/12/03 Javascript
javascript游戏开发之《三国志曹操传》零部件开发(四)用地图块拼成大地图
2013/01/23 Javascript
基于jQuery实现的文字按钮表单特效整理
2014/12/07 Javascript
node.js中的fs.createReadStream方法使用说明
2014/12/17 Javascript
JavaScript实现列出数组中最长的连续数
2014/12/29 Javascript
jquery实现页面关键词高亮显示的方法
2015/03/12 Javascript
js动态修改表格行colspan列跨度的方法
2015/03/30 Javascript
js获取微信版本号的方法
2015/05/12 Javascript
JavaScript中Number.MIN_VALUE属性的使用示例
2015/06/04 Javascript
通过原生JS实现为元素添加事件的方法
2016/11/23 Javascript
从零学习node.js之利用express搭建简易论坛(七)
2017/02/25 Javascript
jQuery 控制文本框自动缩小字体填充
2017/06/16 jQuery
JS实现数组简单去重及数组根据对象中的元素去重操作示例
2018/01/05 Javascript
NodeJS 文件夹拷贝以及删除功能
2019/09/03 NodeJs
[02:11]完美世界DOTA2联赛10月28日赛事精彩集锦:来吧展示实力强劲
2020/10/29 DOTA
python模拟Django框架实例
2016/05/17 Python
Python从Excel中读取日期一列的方法
2018/11/28 Python
python Tcp协议发送和接收信息的例子
2019/07/22 Python
python2 中 unicode 和 str 之间的转换及与python3 str 的区别
2019/07/25 Python
python 对象真假值的实例(哪些视为False)
2020/12/11 Python
建筑项目策划书
2014/01/13 职场文书
经营管理策划方案
2014/05/22 职场文书
以幸福为主题的活动方案
2014/08/22 职场文书
清明节扫墓活动总结
2015/02/09 职场文书
教师工作表现自我评价
2015/03/05 职场文书
幼儿园开学报名通知
2015/07/16 职场文书
2017春节晚会开幕词
2016/03/03 职场文书
python必学知识之文件操作(建议收藏)
2021/05/30 Python
logback 实现给变量指定默认值
2021/08/30 Java/Android
浅谈Redis变慢的原因及排查方法
2022/06/21 Redis
CSS中理解层叠性及权重如何分配
2022/12/24 HTML / CSS