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

yipeiwu_com5年前Python基础

这两天为用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聊天室实例程序分享

上一篇 我们学习了简单的Python TCP Socket 编程,通过分别写服务端和客户端的代码了解基本的 Python Socket 编程模型。本文再通过一个例子来加强一下对 Sock...

pyQT5 实现窗体之间传值的示例

pyQT5 实现窗体之间传值的示例

准备 一个MainWindow和一个WidgetForm,总代码如下 # -*- coding: utf-8 -*- from PyQt5 import QtWidgets fr...

在 Jupyter 中重新导入特定的 Python 文件(场景分析)

在 Jupyter 中重新导入特定的 Python 文件(场景分析)

Jupyter 是数据分析领域非常有名的开发环境,使用 Jupyter 写数据分析相关的代码会大大节约开发时间。 设想这样一个场景:别的部门的同事传给你一个数据分析的模块,用于实现对数据...

Python验证企业工商注册码

中国企业工商注册码前六位为行政区代码,中间8位顺序编码,最后一位为根据ISO 7064:1983.MOD 11-2校验码计算出来的检验码,本算法根据最后一位校验码的算法来判断企业注册码是...

python实现决策树分类算法

python实现决策树分类算法

本文实例为大家分享了python实现决策树分类算法的具体代码,供大家参考,具体内容如下 1、概述 决策树(decision tree)——是一种被广泛使用的分类算法。 相比贝叶斯算法,决...