Quart-CORS
Quart-CORS is an extension for Quart, an async Python web application framework, designed to provide Cross-Origin Resource Sharing (CORS) access control support. It simplifies the process of adding necessary CORS headers to your Quart application or specific routes and WebSockets. The library is actively maintained, with its current version being 0.8.0, and receives regular updates to keep pace with Quart and web standards.
Warnings
- breaking When `allow_credentials=True`, the `allow_origin` parameter MUST NOT be a wildcard (`*`). Instead, it must be a specific origin or a list of specific origins, as required by the CORS specification for security reasons.
- gotcha Aggressive browser caching (especially in Chrome) can lead to CORS errors persisting even after server-side fixes are deployed. Browsers might cache preflight `OPTIONS` responses, leading to outdated CORS headers being used.
- breaking As of Quart 0.11.1, the CORS specification dictates that only a single origin (or a wildcard) can be returned in the `Access-Control-Allow-Origin` header. If multiple specific origins are allowed by `quart-cors`, the library will dynamically set the header to the requesting origin if it's in the allowed list.
- breaking Attempting to use `Flask-CORS` with a Quart application will not work, as `Flask-CORS` relies on synchronous `app.make_response` calls which are incompatible with Quart's async nature.
- gotcha While `quart-cors` is generally backward compatible with `Quart`, ensure that `quart` and `quart-cors` versions are reasonably aligned. Significant version jumps of `Quart` might introduce subtle incompatibilities.
Install
-
pip install quart-cors
Imports
- cors
from quart_cors import cors
- route_cors
from quart_cors import route_cors
- websocket_cors
from quart_cors import websocket_cors
- cors_exempt
from quart_cors import cors_exempt
Quickstart
from quart import Quart, request
from quart_cors import cors, route_cors
app = Quart(__name__)
# Apply CORS to the entire application, allowing all origins
# For production, specify allowed origins instead of '*'
app = cors(app, allow_origin='*')
@app.route('/')
async def hello():
return 'Hello, Quart-CORS!'
@app.route('/api/data', methods=['GET', 'POST'])
@route_cors(allow_origin='https://example.com', allow_methods=['GET', 'POST'], allow_headers=['Content-Type'])
async def api_data():
if request.method == 'GET':
return {'message': 'This is your data!'}
elif request.method == 'POST':
data = await request.get_json()
return {'received': data, 'message': 'Data posted successfully!'}
if __name__ == '__main__':
app.run()