Quart Documentation

repository·main·Indexed 25 days ago

https://github.com/pallets/quart

Quart is an asyncio-based Python ASGI web framework designed as an asynchronous reimplementation of Flask. It provides a compatible API for building high-performance web applications with native support for WebSockets, streaming, and JSON APIs. Version 0.21.0 requires Python 3.11.0 or greater.

Tokens
34.1K
Snippets
138
Records
229
Agent score
86%

What's inside Quart

  1. Overview of Quart capabilities

    main

    Quart is an asynchronous (asyncio) Python web microframework designed for high-performance web applications. It is an asyncio reimplementation of the Flask API, meaning developers familiar with Flask can easily transition to Quart.

    Key capabilities include:

    • Writing JSON APIs (RESTful).
    • Rendering and serving HTML.
    • Serving WebSockets (e.g., for chat servers).
    • Streaming responses (e.g., for video).
    • Supporting both asynchronous (asyncio) and synchronous libraries/code.
  2. Available Quart Extensions

    main

    Quart has a variety of community-maintained extensions for common tasks such as authentication, database management, API documentation, and more. Notable extensions include:

    • Authentication & Security: Quart-Auth (cookie sessions), Quart-Login (Flask-Login port), Quart-Keycloak (OIDC), Quart-WTF (WTForms & CSRF), Quart-Enciphers (encrypted cookies), and Quart-Rate-Limiter.
    • Databases & Caching: Quart-DB (PostgreSQL), Quart-Mongo / Quart-Motor (MongoDB), Quart-SqlAlchemy (SQLAlchemy wrapper), and Quart-Redis.
    • API & Validation: Quart-OpenApi, Quart-Rapidoc (OpenAPI docs), Quart-Schema (validation), and Webargs-Quart (parsing).
    • Utilities: Quart-Babel (i18n), Quart-compress / Quart-compress2 (gzip), Quart-CORS (CORS support), Quart-minify (HTML/JS/CSS minification), and Quart-Uploads (file uploads).
  3. Understand Quart Contexts

    main

    Quart uses two primary contexts to resolve global proxies like current_app and request: the Application Context and the Request Context.

    • Application Context: Provides access to information not specific to a single request, such as the application instance itself, the g global object, and an app-bound url_adapter. It is implicitly created and destroyed by the request context.
    • Request Context: Provides access to request-specific information, including the request object, a request-bound url_adapter, and the session. It is created and destroyed per request by Quart.handle_request.

    Best Practice: Because these contexts are accessed via global proxies, it is recommended to use them only within routes to isolate their scope and avoid issues with global variable arguments.

  4. Understand the relationship between Quart and Flask

    main
    Quart is designed as an evolution of Flask, specifically built to support asyncio, WebSockets, and HTTP/2. It follows Flask's design patterns, such as using context locals and globals for request/websocket data rather than passing them as arguments to route handlers. This makes Quart highly compatible with the mental model used for Flask development.
  5. Understand background task behavior and error handling

    main

    Quart's background task API follows the pattern used by Sanic and Starlette, where you provide a callable and its arguments.

    Key behaviors include:

    • Graceful Shutdown: Quart ensures that background tasks are completed during the application shutdown process (provided the server does not time out and cancel them first).
    • Error Isolation: Errors raised within a background task are logged but do not crash the application. The task is treated similarly to request or websocket handling errors, allowing the rest of the app to continue running.
  6. Quickstart with Quart

    main

    Quart is an async Python web application framework. You can use it to render HTML templates, write RESTful JSON APIs, serve WebSockets, and stream request/response data.

    To run a Quart application, use the quart run command.

    from quart import Quart, render_template, websocket
    
    app = Quart(__name__)
    
    @app.route("/")
    async def hello():
        return await render_template("index.html")
    
    @app.route("/api")
    async def json():
        return {"hello": "world"}
    
    @app.websocket("/ws")
    async def ws():
        while True:
            await websocket.send("hello")
            await websocket.send_json({"hello": "world"})

    To run the application:

    $ quart run
  7. Create a basic Quart application

    main

    Initialize a Quart app in your package's __init__.py. You can define a run() function to start the server.

    To make the app easily runnable via Poetry, add a script entry to your pyproject.toml:

    [tool.poetry.scripts]
    start = "video:run"

    Then start the application using: poetry run start.

    from quart import Quart
    
    app = Quart(__name__)
    
    def run() -> None:
        app.run()
  8. Configure Permanent Sessions

    main

    By default, Quart session cookies are not permanent and are deleted when the browser session ends. To make cookies permanent, you must set session.permanent = True when the session is modified.

    To make all sessions permanent by default for your application, use a @app.before_request handler.

    @app.before_request
    def make_session_permanent():
        session.permanent = True
  9. Test within App and Request contexts

    main

    You can manually enter application or request contexts to test code that relies on Quart globals.

    • App Context: Use async with app.app_context():.
    • Request Context: Use async with app.test_request_context(path, method='...'):. Note that you must provide at least a path and a method.

    Important: before_request and after_request functions are not automatically called when using test_request_context. To trigger them, you must explicitly call await app.preprocess_request() inside the context.

    # Testing App Context
    async def test_app_context(app):
        async with app.app_context():
            current_app.[use]
    
    # Testing Request Context
    async def test_request_context(app):
        async with app.test_request_context("/", method="GET"):
            request.[use]
    
    # Testing Request Context with before_request functions
    async def test_request_context_with_preprocess(app):
        async with app.test_request_context("/", method="GET"):
            await app.preprocess_request()
            # The before_request functions have now been called
            request.[use]
  10. Disable timeouts for streaming responses

    main

    Quart applies default timeouts to protect against DoS attacks, which can prematurely close long-running or indefinite streams. To allow a specific stream to run indefinitely, use make_response to create the response object and set its timeout attribute to None.

    from quart import make_response
    
    @app.route('/sse')
    async def stream_time():
        ...
        response = await make_response(async_generator())
        response.timeout = None  # No timeout for this route
        return response
  11. Update Flask imports to Quart

    main

    Replace imports from the flask package with imports from the quart package. Most imported objects retain their original names.

    Flask Example:

    from flask import Flask, g, request
    from flask.helpers import make_response

    Quart Equivalent:

    from quart import Quart, g, request
    from quart.helpers import make_response