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:
pythonfrom 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:
- We first import
Flask,request, andmake_responsefrom the Flask module. - We create a Flask application instance.
- We define a route
/delete_cookiethat executes thedelete_cookiefunction upon access. - Within the
delete_cookiefunction, we create a response object containing a message confirming the cookie has been deleted. - Using the
response.set_cookie()method, we set thesession_idcookie's value to an empty string and specify an expiration time of 0, instructing the browser to immediately remove the cookie. - 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 回复