虽然文档上没有但是还有一种操作cookie的方式:

frombottleimportrequest,response

@route('/login',method="POST")
deflogin():
user=request.POST['user']
passwd=request.POST['passwd']

ifcheck_user_right(user,passwd):
response.COOKIES['account']=user
else:
pass

@route('/admin')
defadmin():
user=request.COOKIES['user']
ifuser:
pass

但是无论我用哪种方式操作我都无法获取cookie,为什么呢.百思不得其解.但是我的一个处理文章点击率的提醒了我,代码如下:

@route('/archrives/:aid#\d+#')
defarticle_show(aid):
db=dbconn.ConnDB()
artid=int(aid)
#获取客户端ip
remoteip=request.environ.get('REMOTE_ADDR')

artcookie=remoteip+'ip'+aid
printrequest.COOKIES.keys()

#判断cookie是否存在
ifartcookieinrequest.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())

returntemplate('article.html',TEMPLATE)

这里是可以正常获取到cookie的,而且代码没有任何区别.唯一的区别就是用户认证是跳转了页面.所以我help了一下:

frombottleimportresponse
help(response.set_cookie)

help的结果其中有两个参数一个是path,和domain:

:paramdomain:thedomainthatisallowedtoreadthecookie.
(default:currentdomain)
:parampath:limitsthecookietoagivenpath(default:currentpath)

明显bottle的cookie默认只在当前路径下能读取的到,所以要别的页面读取到cookie我们的代码须改成如下:

frombottleimportrequest,response

@route('/login',method="POST")
deflogin():
user=request.POST['user']
passwd=request.POST['passwd']

ifcheck_user_right(user,passwd):
response.COOKIES['account']=user
response.COOKIES['account']['path']='/admin'
else:
pass

@route('/admin')
defadmin():
user=request.COOKIES['user']

这样我们就能在别的路径下访问我们设定的cookie.

热门推荐

1 退伍祝福语老师简短
2 给新娘彩礼祝福语简短
3 自由 生日祝福语简短独特
4 春节文章开头祝福语简短
5 订婚典礼文案祝福语简短
6 爷爷庆生文案祝福语简短
7 宿舍迎新祝福语简短英文
8 长辈鲜花祝福语卡片简短
9 培训机构升班祝福语简短
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短