1. Related HTTP Header Information
HTTP headers are used to control the interaction rules between the client and the server (such as cross-origin, caching, content type, etc.). Below are commonly used header properties and methods in the Response object:
1. access_control_allow_credentials
-
Type: Boolean
-
Function: Indicates whether cross-origin requests are allowed to carry credentials (such as Cookies, HTTP authentication information)
-
Description: When set to True, cross-origin requests can carry sensitive information and must be used in conjunction with access_control_allow_origin (cannot be set to *)
-
Example:
response = make_response("Cross-origin response")
response.access_control_allow_credentials = True
response.access_control_allow_origin = "https://example.com" # Must specify a specific origin
2. access_control_allow_headers
-
Type: String
-
Function: Specifies the custom header fields allowed in cross-origin requests, separated by commas
-
Example:
response.access_control_allow_headers = "Content-Type,Authorization,X-Custom-Header"
3. access_control_allow_methods
-
Type: String
-
Function: Specifies the HTTP methods allowed for cross-origin requests, separated by commas
-
Example:
response.access_control_allow_methods = "GET,POST,PUT,DELETE,OPTIONS"
4. access_control_allow_origin
-
Type: String
-
Function: Specifies the origin address allowed for cross-origin requests, which is the core field of cross-origin configuration
-
Description: Setting to “*” means allowing all origins (but cannot be used with credentials=True), it is recommended to specify a specific domain name in production environments
-
Example:
# Allow all origins in development environment
response.access_control_allow_origin = "*"
# Specify a specific origin in production environment
response.access_control_allow_origin = "https://app.example.com"
5. access_control_expose_headers
-
Type: String
-
Function: Specifies the response header fields that are allowed for client JavaScript access (by default, only a few basic headers are exposed)
-
Example:
# Allow client to access custom header X-Data-Count
response.access_control_expose_headers = "X-Data-Count"
6. access_control_max_age
-
Type: Numeric (seconds)
-
Function: Sets the cache validity period for cross-origin preflight requests (OPTIONS), within which preflight requests do not need to be sent repeatedly
-
Example:
response.access_control_max_age = 3600 # Cache preflight results for 1 hour
7. age
-
Type: Numeric (seconds)
-
Function: Indicates the time the response has been cached in the proxy server, automatically set by the proxy server, developers usually do not need to modify it manually
8. allow
-
Type: String
-
Function: Lists the HTTP request methods supported by the server, separated by commas
-
Example:
# Inform the client that the current interface only supports GET and POST
response.allow = "GET,POST"
response.status_code = 405 # Used with 405 Method Not Allowed status code
9. cache_control
-
Type: String
-
Function: Controls the caching behavior of the client and proxy server, supports multiple directive combinations
-
Common directives: no-cache (must validate cache), no-store (do not cache), must-revalidate (must validate after expiration), max-age=seconds (cache validity period)
-
Example:
# Prohibit caching of response content
response.cache_control = "no-cache, no-store, must-revalidate"
# Cache for 10 minutes
response.cache_control = "public, max-age=600"
10. content_md5
-
Type: String
-
Function: Stores the MD5 checksum of the response body for client data integrity verification
-
Example:
import hashlib
data = "Response content".encode("utf-8")
response.data = data
response.content_md5 = hashlib.md5(data).hexdigest()
11. content_range
-
Type: String
-
Function: Indicates the content range of the response body (used for resuming downloads, chunked downloads), format is “bytes start-end/total”
-
Example:
# Return bytes 0-999 of the file, total size 10000 bytes
response.content_range = "bytes 0-999/10000"
response.status_code = 206 # Used with 206 Partial Content status code
12. content_security_policy (CSP)
-
Type: String
-
Function: Defines the security policy for web content, restricting the sources of resource loading (such as scripts, images, styles), preventing XSS and other attacks
-
Example:
# Only allow loading scripts from the same origin and HTTPS images
response.content_security_policy = "script-src 'self'; img-src https:"
13. content_type
-
Type: String
-
Function: Specifies the MIME type and character encoding of the response body, one of the most commonly used headers
-
Common values: text/html; charset=utf-8 (HTML page), application/json; charset=utf-8 (JSON data), image/png (image)
-
Example:
# Return JSON response (recommended to use jsonify for automatic setting, this is a manual example)
response.content_type = "application/json; charset=utf-8"
response.data = json.dumps({"code": 0, "msg": "success"})
14. cross_origin_embedder_policy
-
Type: String
-
Function: Controls the embedding permissions of cross-origin resources, preventing cross-origin data leakage
-
Common values: require-corp (only allows same-origin or cross-origin resources with CORP header), unsafe-none (default, allows any embedding)
-
Example:
response.cross_origin_embedder_policy = "require-corp"
15. cross_origin_opener_policy
-
Type: String
-
Function: Controls the communication permissions of cross-origin windows, affecting the availability of window.opener
-
Common values: same-origin (only allows same-origin window communication), unsafe-none (default, allows cross-origin communication)
-
Example:
# Prevent cross-origin windows from stealing data through opener
response.cross_origin_opener_policy = "same-origin"
16. date
-
Type: String
-
Function: Represents the date and time the response was generated, format follows RFC 7231 (e.g., “Wed, 21 Oct 2015 07:28:00 GMT”)
-
Description: Automatically generated by Flask, no need to set manually
17. expires
-
Type: String
-
Function: Specifies the expiration time of the response, format follows RFC 7231, after expiration the client needs to re-request
-
Example:
from datetime import datetime, timedelta
expire_time = datetime.utcnow() + timedelta(hours=1)
response.expires = expire_time.strftime("%a, %d %b %Y %H:%M:%S GMT")
18. location
-
Type: String
-
Function: Specifies the target URL for redirection, used with 3xx status codes
-
Example:
# Permanently redirect to a new domain
response.location = "https://new.example.com"
response.status_code = 301 # 301 Permanent Redirect, 302 Temporary Redirect
19. last_modified
-
Type: String
-
Function: Indicates the last modification time of the resource, used for cache control (the client can request with If-Modified-Since condition)
-
Example:
from datetime import datetime
modify_time = datetime.utcnow() - timedelta(days=1)
response.last_modified = modify_time.strftime("%a, %d %b %Y %H:%M:%S GMT")
20. retry_after
-
Type: Numeric (seconds) or String (date time)
-
Function: Indicates how long the client should wait before retrying the request, commonly used with 503 (Service Unavailable) or 429 (Too Many Requests) status codes
-
Example:
# Inform the client to retry after 10 seconds
response.retry_after = 10
response.status_code = 429
21. set_cookie()
-
Function: Sets or updates the client Cookie
-
Parameters:
- key: Cookie name (required)
- value: Cookie value (default None)
- max_age: Cookie validity period (seconds, None means session-level Cookie, invalid when the browser is closed)
- expires: Cookie expiration time (datetime object, mutually exclusive with max_age, max_age takes precedence)
- path: Cookie path (default “/”, only interfaces under this path can access)
- domain: Cookie scope (e.g., “.example.com” means available to all subdomains)
- secure: Whether to transmit only over HTTPS (default False, recommended to set to True in production)
- httponly: Whether to prohibit JavaScript access (default False, prevents XSS from stealing Cookies)
- samesite: Cross-site request strategy (strict/lax/none, default None, prevents CSRF attacks)
-
Example:
# Set session-level Cookie (invalid when the browser is closed)
response.set_cookie("user_id", "123", httponly=True, secure=True, samesite="strict")
# Set a Cookie valid for 7 days
response.set_cookie("token", "abc123", max_age=60*60*24*7, path="/api")
22. status
-
Type: String
-
Function: HTTP status code and reason phrase (e.g., “200 OK”, “404 Not Found”)
-
Description: Associated with status_code, modifying one will update the other
-
Example:
response.status = "400 Bad Request" # Equivalent to response.status_code = 400
23. status_code
-
Type: Numeric
-
Function: HTTP status code (e.g., 200 success, 404 not found, 500 server error)
-
Description: More concise than status, recommended to use this first
-
Common status codes: 200 (success), 201 (created successfully), 400 (parameter error), 401 (unauthorized), 403 (forbidden), 404 (resource not found), 500 (server error)
-
Example:
response.status_code = 201 # Indicates resource created successfully
24. www_authenticate
-
Type: String
-
Function: Used for 401 Unauthorized responses, indicating the authentication method for the client (e.g., Basic, Bearer)
-
Example:
# Require the client to use Basic authentication
response.www_authenticate = "Basic realm='Please enter username and password'"
response.status_code = 401