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 dict.get()和dict['key']的区别详解
Jun 30 Python
numpy.transpose对三维数组的转置方法
Apr 17 Python
python内置数据类型之列表操作
Nov 12 Python
浅谈Pycharm调用同级目录下的py脚本bug
Dec 03 Python
python tornado使用流生成图片的例子
Nov 18 Python
python的range和linspace使用详解
Nov 27 Python
opencv python 图片读取与显示图片窗口未响应问题的解决
Apr 24 Python
Django admin管理工具TabularInline类用法详解
May 14 Python
Python3创建Django项目的几种方法(3种)
Jun 03 Python
Python selenium模块实现定位过程解析
Jul 09 Python
pytest配置文件pytest.ini的详细使用
Apr 17 Python
Python基础详解之邮件处理
Apr 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开发入门教程之面向对象
2006/12/05 PHP
php md5下16位和32位的实现代码
2008/04/09 PHP
PHP源码之explode使用说明
2011/08/05 PHP
浅析PHP中Session可能会引起并发问题
2015/07/23 PHP
PHP实现简单实用的验证码类
2015/07/29 PHP
ThinkPHP框架获取最后一次执行SQL语句及变量调试简单操作示例
2018/06/13 PHP
Domino中运用jQuery读取视图内容的方法
2009/10/21 Javascript
读jQuery之三(构建选择器)
2011/06/11 Javascript
JS 实现获取打开一个界面中输入的值
2013/03/19 Javascript
jquery中change()用法实例分析
2015/02/06 Javascript
JavaScript识别网页关键字并进行描红的方法
2015/11/09 Javascript
JS隐藏号码中间4位代码实例
2019/04/09 Javascript
vue cli3 配置proxy代理无效的解决
2019/10/30 Javascript
three.js欧拉角和四元数的使用方法
2020/07/26 Javascript
[01:45]2014DOTA2 TI预选赛预选赛 大神专访第二弹!
2014/05/20 DOTA
python求众数问题实例
2014/09/26 Python
详解Python在七牛云平台的应用(一)
2017/12/05 Python
浅谈Django学习migrate和makemigrations的差别
2018/01/18 Python
Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制)
2018/04/30 Python
python smtplib模块实现发送邮件带附件sendmail
2018/05/22 Python
Python实现的NN神经网络算法完整示例
2018/06/19 Python
python字符串替换第一个字符串的方法
2019/06/26 Python
linux中如何使用python3获取ip地址
2019/07/15 Python
PIL包中Image模块的convert()函数的具体使用
2020/02/26 Python
Anaconda配置pytorch-gpu虚拟环境的图文教程
2020/04/16 Python
HTML5 Canvas如何实现纹理填充与描边(Fill And Stroke)
2013/07/15 HTML / CSS
编写函数,将一个3*3矩阵转置
2013/10/09 面试题
社区包粽子活动方案
2014/01/21 职场文书
初中三好学生自我鉴定
2014/04/07 职场文书
cf战队收人口号
2014/06/21 职场文书
领导干部四风问题自我剖析材料
2014/09/25 职场文书
先进教育工作者事迹材料
2014/12/23 职场文书
硕士毕业论文导师评语
2014/12/31 职场文书
浅谈Web Storage API的使用
2021/06/23 Javascript
golang实现一个简单的websocket聊天室功能
2021/10/05 Golang
德生TECSUN S-2000使用手册文字版
2022/05/10 无线电