俾斯麦--瓶子--饼干不断变化[英] Python- bottle - cookies keep changing

本文是小编为大家收集整理的关于俾斯麦--瓶子--饼干不断变化的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

以下是我在瓶中设置和阅读cookie的代码.

if request.get_cookie('mycookiename'):
        cookie_id = request.get_cookie('mycookiename')
    else:
        cookie_id=str(uuid4())
        response.set_cookie('mycookiename', cookie_id , max_age=31556952*2, domain='%s' % (cookie_domain))

当我去Firefox和Firebug时,我可以看到cookie设置了.但是,当我刷新页面时,我会得到一个新的cookie.每个请求都是新的cookie ID.

那么,我如何解决?

推荐答案

此代码有效.如果尚未定义cookie,则使用uuid4设置一个新的值cookie.

在您的代码中,我想您的" else"条件不好.

# -*- coding: utf-8 -*-
#!/usr/bin/env python
from uuid import uuid4
import bottle

@bottle.route('/cookie')
    def cookie():
        cookie_id = bottle.request.get_cookie('mycookiename', str(uuid4()))
        bottle.response.set_cookie('mycookiename', cookie_id)
        return 'hello cookie'

if __name__ == '__main__':
    bottle.run(host='localhost', port=8080)

本文地址:https://www.itbaoku.cn/post/549501.html

问题描述

Below is my code for setting and reading cookies in bottle.

if request.get_cookie('mycookiename'):
        cookie_id = request.get_cookie('mycookiename')
    else:
        cookie_id=str(uuid4())
        response.set_cookie('mycookiename', cookie_id , max_age=31556952*2, domain='%s' % (cookie_domain))

When I go to firefox and firebug, I can see that the cookie is set. But, when I refresh the page, I get a new cookie. Every request is a new cookie id.

So, how do I resolve?

推荐答案

This code works. You set a new value cookie with uuid4 if you have not a cookie already define.

In your code, i guess your "else" condition is bad.

# -*- coding: utf-8 -*-
#!/usr/bin/env python
from uuid import uuid4
import bottle

@bottle.route('/cookie')
    def cookie():
        cookie_id = bottle.request.get_cookie('mycookiename', str(uuid4()))
        bottle.response.set_cookie('mycookiename', cookie_id)
        return 'hello cookie'

if __name__ == '__main__':
    bottle.run(host='localhost', port=8080)