乐闻世界logo
搜索文章和话题

How to remove cookies in Flask?

1个答案

1

In Flask, deleting cookies primarily involves setting the corresponding response object and using it to clear specific cookies. This is typically performed when the response is sent back to the client. The fundamental approach to remove a cookie is to set its expiration time to a past date, prompting the browser to automatically delete it.

Here is a specific example code demonstrating how to delete a cookie named session_id in a Flask application:

python
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/delete_cookie') def delete_cookie(): response = make_response("Cookie 'session_id' has been deleted") response.set_cookie('session_id', '', expires=0) return response if __name__ == "__main__": app.run(debug=True)

In this example:

  1. We first import Flask, request, and make_response from the Flask module.
  2. We create a Flask application instance.
  3. We define a route /delete_cookie that executes the delete_cookie function upon access.
  4. Within the delete_cookie function, we create a response object containing a message confirming the cookie has been deleted.
  5. Using the response.set_cookie() method, we set the session_id cookie's value to an empty string and specify an expiration time of 0, instructing the browser to immediately remove the cookie.
  6. Finally, the function returns the response object, which includes the cookie deletion operation.

This method, which sets the cookie's expiration time to 0 to ensure client-side deletion, is a general and widely adopted technique.

2024年8月12日 11:37 回复

你的答案