如何在 Python Flask 中设置 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46661083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:44:57  来源:igfitidea点击:

How to set cookie in Python Flask?

pythoncookiesflask

提问by Shaon shaonty

In this way, I want to set my cookie. But it fails to set.

这样,我想设置我的cookie。但是设置失败。

@app.route('/')
def index():
    res = flask.make_response()
    res.set_cookie("name", value="I am cookie")

When I print resit shows <Response 0 bytes [200 OK]But not set cookie

当我打印res它时显示<Response 0 bytes [200 OK]但未设置 cookie

回答by Sahid Hossen

You have return the response after set the cookie.

您已在设置 cookie 后返回响应。

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('somecookiename', 'I am cookie')
    return resp 

This way cookie will generate in your browser but you can get this cookie in next request.

这样 cookie 将在您的浏览器中生成,但您可以在下一个请求中获取此 cookie。

@app.route('/get-cookie/')
def get_cookie():
    username = request.cookies.get('somecookiename')