Skip to main content

Build Status pypi python license

Quart-CORS is an extension for Quart to enable and control Cross Origin Resource Sharing, CORS (also known as access control).

CORS is required to share resources in browsers due to the Same Origin Policy which prevents resources being used from a different origin. An origin in this case is defined as the scheme, host and port combined and a resource corresponds to a path.

In practice the Same Origin Policy means that a browser visiting http://quart.com will prevent the response of GET http://api.com being read. It will also prevent requests such as POST http://api.com. Note that CORS applies to browser initiated requests, non-browser clients such as requests are not subject to CORS restrictions.

CORS allows a server to indicate to a browser that certain resources can be used, contrary to the Same Origin Policy. It does so via access-control headers that inform the browser how the resource can be used. For GET requests these headers are sent in the response. For non-GET requests the browser must ask the server for the access-control headers before sending the actual request, it does so via a preflight OPTIONS request.

The Same Origin Policy does not apply to WebSockets, and hence there is no need for CORS. Instead the server alone is responsible for deciding if the WebSocket is allowed and it should do so by inspecting the WebSocket-request origin header.

Simple (GET) requests should return CORS headers specifying the origins that are allowed to use the resource (response). This can be any origin, * (wildcard), or a list of specific origins. The response should also include a CORS header specifying whether response-credentials e.g. cookies can be used. Note that if credential sharing is allowed the allowed origins must be specific and not a wildcard.

Preflight requests should return CORS headers specifying the origins allowed to use the resource, the methods and headers allowed to be sent in a request to the resource, whether response credentials can be used, and finally which response headers can be used.

Note that certain actions are allowed in the Same Origin Policy such as embedding e.g. <img src="http://api.com/img.gif"> and simple POSTs. For the purposes of this readme though these complications are ignored.

The CORS access control response headers are,

Header name

Meaning

Access-Control-Allow-Origin

Origins that are allowed to use the resource.

Access-Control-Allow-Credentials

Can credentials be shared.

Access-Control-Allow-Methods

Methods that may be used in requests to the resource.

Access-Control-Allow-Headers

Headers that may be sent in requests to the resource.

Access-Control-Expose-Headers

Headers that may be read in the response from the resource.

Access-Control-Max-Age

Maximum age to cache the CORS headers for the resource.

Quart-CORS uses the same naming (without the Access-Control prefix) for it’s arguments and settings when they relate to the same meaning.

Installation

Quart-CORS can be installed using pip or your favorite python package manager:

pip install quart-cors

Usage

To add CORS access control headers to all of the routes in the application, simply apply the cors function to the application, or to a specific blueprint,

from quart_cors import cors

app = Quart(__name__)
app = cors(app, **settings)

blueprint = Blueprint(__name__)
blueprint = cors(blueprint, **settings)

alternatively if you wish to add CORS selectively by resource, apply the route_cors function to a route, or the websocket_cors function to a WebSocket,

from quart_cors import route_cors

@app.route('/')
@route_cors(**settings)
async def handler():
    ...

@app.websocket('/')
@websocket_cors(allow_origin=...)
async def handler():
    ...

The settings are these arguments,

Argument

type

allow_origin

Union[Set[Union[Pattern, str]], Union[Pattern, str]]

allow_credentials

bool

allow_methods

Union[Set[str], str]

allow_headers

Union[Set[str], str]

expose_headers

Union[Set[str], str]

max_age

Union[int, flot, timedelta]

send_origin_wildcard

bool

which correspond to the CORS headers noted above (bar send_origin_wildcard). The send_origin_wildcard argument specifies whether to send a wildcard or echo the request origin in the allow origin header. Note that all settings are optional and defaults can be specified in the application configuration,

Configuration key

type

QUART_CORS_ALLOW_ORIGIN

Set[Union[Pattern, str]]

QUART_CORS_ALLOW_CREDENTIALS

bool

QUART_CORS_ALLOW_METHODS

Set[str]

QUART_CORS_ALLOW_HEADERS

Set[str]

QUART_CORS_EXPOSE_HEADERS

Set[str]

QUART_CORS_MAX_AGE

float

QUART_CORS_SEND_ORIGIN_WILDCARD

bool

The websocket_cors decorator only takes allow_origin and send_origin_wildcard arguments which defines the origins that are allowed to use the WebSocket and whether a wildcard should be sent in the allow origin header. A WebSocket request from a disallowed origin will be responded to with a 400 response.

The allow_origin origins should be the origin only (no path, query strings or fragments) i.e. https://quart.com not https://quart.com/.

The cors_exempt decorator can be used in conjunction with cors to exempt a websocket handler or view function from cors. You can find a usage example in “Simple examples” section down below.

Simple examples

To allow an app to be used from any origin (not recommended as it is too permissive),

app = Quart(__name__)
app = cors(app, allow_origin="*")

To allow a route or WebSocket to be used from another specific domain, https://quart.com,

@app.route('/')
@route_cors(allow_origin="https://quart.com")
async def handler():
    ...

@app.websocket('/')
@websocket_cors(allow_origin="https://quart.com")
async def handler():
    ...

To allow a route or WebSocket to be used from any subdomain (but not the domain itself) of quart.com,

@app.route('/')
@route_cors(allow_origin=re.compile(r"https:\/\/.*\.quart\.com"))
async def handler():
    ...

@app.websocket('/')
@websocket_cors(allow_origin=re.compile(r"https:\/\/.*\.quart\.com"))
async def handler():
    ...

To exempt a WebSocket handler from CORS,

@app.websocket('/')
@cors_exempt
async def handler():
    ...

To allow a JSON POST request to an API route, from https://quart.com,

@app.route('/', methods=["POST"])
@route_cors(
    allow_headers=["content-type"],
    allow_methods=["POST"],
    allow_origin=["https://quart.com"],
)
async def handler():
    data = await request.get_json()
    ...

Contributing

Quart-CORS is developed on GitHub. You are very welcome to open issues or propose merge requests.

Testing

The best way to test Quart-CORS is with Tox,

$ pip install tox
$ tox

this will check the code style and run the tests.

Help

This README is the best place to start, after that try opening an issue.

Release files for quart-cors 0.8.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for quart-cors 0.8.0
File Size Uploaded
quart_cors-0.8.0.tar.gz 12.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for quart-cors 0.8.0
File Interpreter ABI Platform
quart_cors-0.8.0-py3-none-any.whl Python 3 none any Details

Total release size: 21.2 kB

Release files / quart_cors-0.8.0.tar.gz

Download URL quart_cors-0.8.0.tar.gz
Size 12.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ac32c4931da6fba944e9e2d3f856f2db4fd82e3fb905a09646086780c221a118
BLAKE2b-256 checksum
How to use checksums
14b12a65be601f3c92c913f3321ee186d10c2da4325447b4b0fca83e0c493c60
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.0.1 CPython/3.12.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 27, 2024.

Transparency log

Release files / quart_cors-0.8.0-py3-none-any.whl

Download URL quart_cors-0.8.0-py3-none-any.whl
Size 8.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
62dc811768e2e1704d2b99d5880e3eb26fc776832305a19ea53db66f63837767
BLAKE2b-256 checksum
How to use checksums
ea31da390a5a10674481dea2909178973de81fa3a246c0eedcc0e1e4114f52f8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.0.1 CPython/3.12.8

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 27, 2024.

Transparency log

Release history Release notifications | RSS feed

This release

0.8.0 This release

2 release files

0.7.0

2 release files

0.6.0

2 release files

0.5.0

2 release files

0.4.0

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page