Quart-CORS

0.8.0 · active · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Quart application and apply CORS globally using `cors(app, allow_origin='*')`. It also shows how to use the `route_cors` decorator to apply more specific CORS rules to an individual API endpoint, allowing GET and POST requests from a specific origin with custom headers. Remember to replace `allow_origin='*'` with specific origins in production for security.

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()

view raw JSON →