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通过OpenCV的findContours获取轮廓并切割实例
Jan 05 Python
python通过伪装头部数据抵抗反爬虫的实例
May 07 Python
详解python数据结构和算法
Apr 18 Python
记录Python脚本的运行日志的方法
Jun 05 Python
Python3实现zip分卷压缩过程解析
Oct 09 Python
关于Python3 lambda函数的深入浅出
Nov 27 Python
python实现名片管理器的示例代码
Dec 17 Python
Python抓新型冠状病毒肺炎疫情数据并绘制全国疫情分布的代码实例
Feb 05 Python
Python可以实现栈的结构吗
May 27 Python
详解Python中Pyyaml模块的使用
Oct 08 Python
python IP地址转整数
Nov 20 Python
如何在Python项目中引入日志
May 31 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
DC这些乐高系列动画电影你看过几部?
2020/04/09 欧美动漫
我的论坛源代码(三)
2006/10/09 PHP
关于mysql字符集设置了character_set_client=binary 在gbk情况下会出现表描述是乱码的情况
2013/01/06 PHP
php实现文件上传及头像预览功能
2017/01/15 PHP
java解析json方法总结
2019/05/16 PHP
CSS心形加载的动画源码的实现
2021/03/09 HTML / CSS
List the Stored Procedures in a SQL Server database
2007/06/20 Javascript
jQuery取id有.的值的方法
2014/05/21 Javascript
JavaScript常用基础知识强化学习
2015/12/09 Javascript
基于JavaScript代码实现自动生成表格
2016/06/15 Javascript
Bootstrap基本样式学习笔记之按钮(4)
2016/12/07 Javascript
angular ng-repeat数组中的数组实例
2017/02/18 Javascript
JS实现控制图片显示大小的方法【图片等比例缩放功能】
2017/02/18 Javascript
vue 中swiper的使用教程
2018/05/22 Javascript
es6 symbol的实现方法示例
2019/04/02 Javascript
详解vue-cli 脚手架 安装
2019/04/16 Javascript
javascript浅层克隆、深度克隆对比及实例解析
2020/02/09 Javascript
Python基于DES算法加密解密实例
2015/06/03 Python
详解Python的Flask框架中的signals信号机制
2016/06/13 Python
python3+PyQt5泛型委托详解
2018/04/24 Python
解决python3 网络请求路径包含中文的问题
2018/05/10 Python
Python字典的核心底层原理讲解
2019/01/24 Python
Django 创建新App及其常用命令的实现方法
2019/08/04 Python
使用python代码进行身份证号校验的实现示例
2019/11/21 Python
flask框架json数据的拿取和返回操作示例
2019/11/28 Python
python线程信号量semaphore使用解析
2019/11/30 Python
python使用numpy实现直方图反向投影示例
2020/01/17 Python
浅析python字符串前加r、f、u、l 的区别
2021/01/24 Python
Canvas 像素处理之改变透明度的实现代码
2019/01/08 HTML / CSS
万得城电器土耳其网站:欧洲第一大电子产品零售商
2016/10/07 全球购物
Currentbody澳大利亚:美容仪专家
2019/11/11 全球购物
优秀少先队员主要事迹材料
2014/05/28 职场文书
市级绿色学校申报材料
2014/08/25 职场文书
2014年国庆节活动总结
2014/08/26 职场文书
浅谈Python从全局与局部变量到装饰器的相关知识
2021/06/21 Python
MYSQL事务的隔离级别与MVCC
2022/05/25 MySQL