Python Flask:如何删除 cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14386304/
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-18 11:16:10  来源:igfitidea点击:

Flask: How to remove cookies?

pythoncookiesflask

提问by Oliver

I set cookies with the code suggested in the docs:

我使用文档中建议的代码设置 cookie:

from flask import make_response

@app.route('/')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp

But how do I remove them? There is no remove_cookie method. I tried:

但是我如何删除它们?没有 remove_cookie 方法。我试过:

if request.cookies.get('sessionID');
    request.cookies.pop('sessionID', None)

but it turns out that the request.cookies object is immutable. What do I do?

但事实证明 request.cookies 对象是不可变的。我该怎么办?

采纳答案by Eevee

There's no HTTP header for deleting a cookie. Traditionally you just set the cookie to a dummy value with an expiration date in the past, so it immediately expires.

没有用于删除 cookie 的 HTTP 标头。传统上,您只需将 cookie 设置为具有过去过期日期的虚拟值,因此它会立即过期。

resp.set_cookie('sessionID', '', expires=0)

This will set the session id cookie to an empty string that expires at unixtime 0, which is almost certainly in the past.

这会将会话 id cookie 设置为在 unixtime 到期的空字符串0,这几乎可以肯定是过去的。

回答by ThiefMaster

You need to set the cookie with an expiry that's in the past.

您需要将 cookie 设置为过去的过期时间。

resp = make_response(render_template(...))
resp.set_cookie('username', expires=0)
return resp

By the way, I hope you don't actually expect that username cookie to be safe. Because it's not. The user can put anything he wants in there. The solution is usually to use the Flask session which uses a signed cookie that cannot be modified by the user.

顺便说一句,我希望您实际上并不期望用户名 cookie 是安全的。因为它不是。用户可以把他想要的任何东西放进去。解决方案通常是使用 Flask 会话,该会话使用用户无法修改的签名 cookie。

回答by Reck

We can make us of delete_cookie() available from flask.Response.

我们可以从flask.Response 中使用delete_cookie()。

resp.delete_cookie('username')

This will delete the cookie on response. Here is delete_cookie documentation.

这将删除响应中的 cookie。这是delete_cookie 文档

Also you may want to have add path(default set to '/') and domain(default set to None).

此外,您可能希望添加路径(默认设置为“/”)和(默认设置为无)。

resp.delete_cookie('username', path='/', domain='yourdomain.com')

Here is the interpreter screenshot which shows delete_cookie object in flask.Response.

这是解释器屏幕截图,显示了 flask.Response 中的 delete_cookie 对象。

Python Interpreter Screenshot

Python 解释器截图