### Create Hello World Quart Application Source: https://github.com/pallets/quart/blob/main/docs/tutorials/quickstart.md A minimal Quart application that creates an async web server with a single route returning 'hello'. Requires Quart to be installed. The app listens on localhost:5000 by default. ```python from quart import Quart app = Quart(__name__) @app.route('/') async def hello(): return 'hello' app.run() ``` -------------------------------- ### Run Quart Application via Command Line Source: https://github.com/pallets/quart/blob/main/docs/tutorials/quickstart.md Two methods to run a Quart application: directly executing the Python file, or using the Quart CLI after setting the QUART_APP environment variable. Both methods start the development server. ```console python hello-world.py ``` ```console export QUART_APP=hello-world:app quart run ``` -------------------------------- ### Define Poetry Script for Starting App Source: https://github.com/pallets/quart/blob/main/docs/tutorials/video_tutorial.md Configures a 'start' script in 'pyproject.toml' to run the Quart application. This allows starting the server with a simple command. ```toml [tool.poetry.scripts] start = "video:run" ``` -------------------------------- ### Test Quart Application with cURL Source: https://github.com/pallets/quart/blob/main/docs/tutorials/quickstart.md A shell command to test the running Quart application by making an HTTP GET request to the root endpoint. Returns the 'hello' response from the server running on localhost:5000. ```sh curl localhost:5000 ``` -------------------------------- ### Configure Poetry script for application startup Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Define a Poetry script entry point in pyproject.toml to easily start the application. This allows running the app with 'poetry run start' command. ```toml [tool.poetry.scripts] start = "blog:run" ``` -------------------------------- ### Configure Poetry Script to Start App Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Adds a script named 'start' to the pyproject.toml file, allowing the Quart application to be easily started using 'poetry run start'. ```toml [tool.poetry.scripts] start = "api:run" ``` -------------------------------- ### Start Quart App with Poetry Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Executes the 'start' script defined in pyproject.toml, launching the Quart web server. Assumes the app is configured to run on localhost:5000 by default. ```console poetry run start ``` -------------------------------- ### Install Poetry Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Installs Poetry, a dependency management tool for Python projects, using pip. ```console pip install poetry ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Installs all project dependencies, including Quart, as defined in the pyproject.toml file. This ensures the project environment is correctly set up. ```console poetry install ``` -------------------------------- ### Serve Documentation - Python Source: https://github.com/pallets/quart/blob/main/CONTRIBUTING.md Starts a local HTTP server to serve the built documentation from the docs/_build/html directory. ```python python -m http.server -b 127.0.0.1 -d docs/_build/html ``` -------------------------------- ### Install Dependencies and Hooks - All Platforms Source: https://github.com/pallets/quart/blob/main/CONTRIBUTING.md Installs development dependencies from a requirements file, installs the project in editable mode, and sets up pre-commit hooks for automated checks. ```bash pip install -r requirements/dev.txt && pip install -e . pre-commit install --install-hooks ``` -------------------------------- ### Configure Poetry script for application startup Source: https://github.com/pallets/quart/blob/main/docs/tutorials/chat_tutorial.md Adds a custom Poetry script command to simplify starting the Quart application. This configuration in pyproject.toml allows running the app with 'poetry run start' instead of calling Python directly. ```toml [tool.poetry.scripts] start = "chat:run" ``` -------------------------------- ### Testing Streaming Requests and Responses in Python Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/testing.md Provides an example of how to test routes that handle streaming requests and responses using the test client's request method. It demonstrates sending data and receiving response chunks. ```python async def test_stream() -> None: test_client = app.test_client() async with test_client.request(...) as connection: await connection.send(b"data") await connection.send_complete() ... # receive a chunk of the response data = await connection.receive() ... # assemble the rest of the response without the first bit response = await connection.as_response() ``` -------------------------------- ### Basic App Test with Test Client in Python Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/testing.md Demonstrates how to use Quart's test client to make a GET request to the root path and assert the response status code. This is a fundamental pattern for testing Quart routes. ```python async def test_app(app): client = app.test_client() response = await client.get('/') assert response.status_code == 200 ``` -------------------------------- ### Run Application Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.app.md The `run` function starts the Quart development server, listening on a specified host and port. ```APIDOC ## run(host=None, port=None, debug=None, use_reloader=True, loop=None, ca_certs=None, certfile=None, keyfile=None, **kwargs) ### Description Run this application. This is best used for development only, see Hypercorn for production servers. ### Method (Implicitly called, not a direct HTTP method) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Function Arguments - **host** (str | None) - Optional - Hostname to listen on. By default this is loopback only, use 0.0.0.0 to have the server listen externally. - **port** (int | None) - Optional - Port number to listen on. - **debug** (bool | None) - Optional - If set enable (or disable) debug mode and debug output. - **use_reloader** (bool) - Optional - Automatically reload on code changes. Defaults to True. - **loop** (AbstractEventLoop | None) - Optional - Asyncio loop to create the server in, if None, take default one. If specified it is the caller’s responsibility to close and cleanup the loop. - **ca_certs** (str | None) - Optional - Path to the SSL CA certificate file. - **certfile** (str | None) - Optional - Path to the SSL certificate file. - **keyfile** (str | None) - Optional - Path to the SSL key file. - **kwargs** (Any) - Optional - Additional keyword arguments. ### Request Example ```python if __name__ == "__main__": app.run(host="127.0.0.1", port=5000) ``` ### Response #### Success Response (200) - **return value** (None) - This function does not return a value upon successful execution; it starts the server. #### Response Example (No direct response, the server starts and listens for requests.) ``` -------------------------------- ### Quart App Test Setup and Assertions Source: https://context7.com/pallets/quart/llms.txt Sets up a Quart application fixture for testing, defines routes for index, user creation, and websocket communication. It includes tests for GET requests, POST requests with JSON data, and WebSocket interactions, along with testing for WebSocket rejection and request context. ```python import pytest from quart import Quart, websocket from quart.testing import WebsocketResponseError import asyncio from quart import request @pytest.fixture def app(): app = Quart(__name__) @app.route('/') async def index(): return 'Hello' @app.post('/api/users') async def create_user(): data = await request.get_json() return {'id': 1, 'name': data['name']}, 201 @app.websocket('/ws') async def ws(): while True: data = await websocket.receive() await websocket.send(f"Echo: {data}") return app async def test_get_request(app): """Test GET request""" client = app.test_client() response = await client.get('/') assert response.status_code == 200 assert await response.get_data() == b'Hello' async def test_post_json(app): """Test POST with JSON""" client = app.test_client() response = await client.post( '/api/users', json={'name': 'Alice'} ) assert response.status_code == 201 data = await response.get_json() assert data['name'] == 'Alice' async def test_websocket(app): """Test WebSocket communication""" client = app.test_client() async with client.websocket('/ws') as ws: await ws.send('Hello') result = await ws.receive() assert result == 'Echo: Hello' async def test_websocket_rejection(app): """Test WebSocket rejection""" client = app.test_client() try: async with client.websocket('/ws/protected'): await ws.send('test') except WebsocketResponseError as error: assert error.response.status_code == 403 async def test_with_context(app): """Test with request context""" async with app.test_request_context('/', method='GET'): await app.preprocess_request() assert request.method == 'GET' async def test_background_tasks(app): """Test background task completion""" task_completed = False async def background_task(): nonlocal task_completed await asyncio.sleep(0.1) task_completed = True async with app.test_app(): app.add_background_task(background_task) assert task_completed ``` -------------------------------- ### Basic App Setup Source: https://github.com/pallets/quart/blob/main/docs/reference/cheatsheet.md Demonstrates the fundamental structure of a Quart application and a simple route. ```APIDOC ## Basic App Setup ### Description This section shows how to initialize a Quart application and define a basic route that returns a string. ### Method GET ### Endpoint / ### Request Example ```python from quart import Quart app = Quart(__name__) @app.route("/hello") async def hello(): return "Hello, World!" if __name__ == "__main__": app.run(debug=True) ``` ### Response #### Success Response (200) - **body** (string) - "Hello, World!" #### Response Example ``` Hello, World! ``` ``` -------------------------------- ### Setup Repository - Bash/Shell Source: https://github.com/pallets/quart/blob/main/CONTRIBUTING.md Steps to fork and clone the project repository, switch to the appropriate branch (stable or main), pull updates from upstream, and create a new work branch for your changes. ```bash gh repo fork --clone pallets/flask cd flask git switch stable git pull upstream git switch -c short-descriptive-name ``` -------------------------------- ### GET / Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.testing.md Simulates an HTTP GET request to the application. ```APIDOC ## GET / ### Description Make a GET request. ### Method GET ### Endpoint / ### Parameters See [`open()`](#quart.testing.QuartClient.open) for argument details. ### Return type Response ``` -------------------------------- ### Install pytest-asyncio for Quart API Testing (Shell) Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md This command installs the pytest-asyncio package as a development dependency using Poetry. This is necessary for running asynchronous tests with pytest in the Quart application. ```bash poetry add --dev pytest-asyncio ``` -------------------------------- ### GET/POST /create/ Source: https://context7.com/pallets/quart/llms.txt Handles both GET requests to display the post creation form and POST requests to create new blog posts in the database. Returns the create form on GET and redirects to the posts list after successful creation. ```APIDOC ## GET/POST /create/ ### Description Create a new blog post. GET returns the creation form, POST processes form submission and creates the post. ### Method GET, POST ### Endpoint /create/ ### Parameters #### Request Body (POST only) - **title** (string) - Required - Post title - **text** (string) - Required - Post content ### Request Example { "title": "My New Post", "text": "This is the content of my post" } ### Response #### Success Response (GET - 200) HTML form for creating a new post #### Success Response (POST - 302) Redirect to / (posts list) #### Response Headers - **Location** - Redirect URL to posts page ``` -------------------------------- ### Add Quart-Schema Dependency Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Installs the Quart-Schema extension using Poetry, which is used for request/response validation and automatic OpenAPI documentation generation. ```console poetry add quart-schema ``` -------------------------------- ### quart.testing.make_test_headers_path_and_query_string Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.testing.md Generates default headers, path, and query string components for testing purposes, simplifying test setup. ```APIDOC ## quart.testing.make_test_headers_path_and_query_string ### Description Make the headers and path with defaults for testing. ### Parameters #### Path Parameters - **app** (Quart) – The application to test against. - **path** (str) – The path to request. If the query_string argument is not defined this argument will be partitioned on a ‘?’ with the following part being considered the query_string. #### Query Parameters - **headers** (dict | Headers | None) – Initial headers to send. - **query_string** (dict | None) – To send as a dictionary, alternatively the query_string can be determined from the path. - **auth** (Authorization | tuple[str, str] | None) - **subdomain** (str | None) ### Return type tuple[Headers, str, bytes] ``` -------------------------------- ### Basic Quart App Setup Source: https://github.com/pallets/quart/blob/main/docs/reference/cheatsheet.md Sets up a basic Quart application with a single route '/hello' that returns 'Hello, World!'. It requires the 'quart' library. The app is run with debug mode enabled when the script is executed directly. ```python from quart import Quart app = Quart(__name__) @app.route("/hello") async def hello(): return "Hello, World!" if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Quart Application Startup and Shutdown Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.app.md These are asynchronous functions representing the application's startup and shutdown events. They do not take any parameters and return None. These are typically used for initializing resources before the application starts serving requests and for releasing resources when the application is shutting down. ```python async def startup(): """ * **Return type:** None """ pass ``` ```python async def shutdown(): """ * **Return type:** None """ pass ``` -------------------------------- ### GET /store/products Source: https://context7.com/pallets/quart/llms.txt Retrieves a list of available products from the store module. Returns JSON formatted product data. Demonstrates blueprint route organization. ```APIDOC ## GET /store/products ### Description Retrieve list of products from the store. ### Method GET ### Endpoint /store/products ### Response #### Success Response (200) - **products** (array) - List of product names - **item** (string) - Product name #### Response Example { "products": [ "Product 1", "Product 2" ] } ``` -------------------------------- ### Define Simple View with Dispatch Request (Python) Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.views.md This example demonstrates how to create a simple view by subclassing quart.views.View and implementing the dispatch_request method. It shows how to associate this view with a URL rule in a Quart application. ```python from quart import Quart app = Quart(__name__) class SimpleView: methods = ['GET'] async def dispatch_request(id): return f"ID is {id}" app.add_url_rule('/', view_func=SimpleView.as_view('simple')) # To run this example: # if __name__ == '__main__': # app.run() ``` -------------------------------- ### Python: Organize Quart App with Blueprints Source: https://context7.com/pallets/quart/llms.txt Demonstrates how to use Quart Blueprints to organize a larger application into modular components. Provides examples for a 'store' blueprint with request preprocessing and an 'api' blueprint. ```python # blueprints/store/__init__.py from quart import Blueprint, render_template, request store_bp = Blueprint('store', __name__, url_prefix='/store') @store_bp.route('/') async def index(): return await render_template('store/index.html') @store_bp.route('/products') async def products(): return {"products": ["Product 1", "Product 2"]} @store_bp.before_request async def before_request(): """Runs before each request to this blueprint""" print(f"Store request: {request.path}") # blueprints/api/__init__.py from quart import Blueprint api_bp = Blueprint('api', __name__, url_prefix='/api') @api_bp.route('/health') async def health(): return {"status": "healthy"} ``` -------------------------------- ### Create new Poetry project for blog Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Initialize a new Poetry project with source layout using the 'poetry new' command. This creates the project directory structure and necessary configuration files. ```console poetry new --src blog ``` -------------------------------- ### Configure database connection and initialization in Quart Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Set up SQLite database configuration, connection pooling, and database initialization function in src/blog/__init__.py. Includes database path configuration and connection factory with row factory for dict-like access. ```python from pathlib import Path from sqlite3 import dbapi2 as sqlite3 app.config.update({ "DATABASE": Path(app.root_path) / "blog.db", }) def _connect_db(): engine = sqlite3.connect(app.config["DATABASE"]) engine.row_factory = sqlite3.Row return engine def init_db(): db = _connect_db() with open(Path(app.root_path) / "schema.sql", mode="r") as file_: db.cursor().executescript(file_.read()) db.commit() ``` -------------------------------- ### Define HTTP Method-Specific View with MethodView (Python) Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.views.md This example shows how to use quart.views.MethodView to create a view that handles different HTTP methods (GET, POST) by defining separate asynchronous methods. It illustrates associating this MethodView with a URL rule. ```python from quart import Quart, MethodView app = Quart(__name__) class SimpleView(MethodView): async def get(id): return f"Get {id}" async def post(id): return f"Post {id}" app.add_url_rule('/', view_func=SimpleView.as_view('simple')) # To run this example: # if __name__ == '__main__': # app.run() ``` -------------------------------- ### Initialize SQLite database via Poetry Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Run the database initialization function using Poetry script. This creates the SQLite database and applies the schema from schema.sql file. ```console poetry run init_db ``` -------------------------------- ### GET - Make GET Request Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.testing.client.md Asynchronous convenience method to make a GET request. Accepts all parameters supported by the open() method. ```APIDOC ## GET /path ### Description Makes an asynchronous GET request to the specified path. This is a convenience method that calls open() with method='GET'. See open() for all supported parameters. ### Method GET ### Endpoint {path} ### Parameters See open() method for all available parameters. ### Response #### Success Response - Returns Response object ### Return Type Response ``` -------------------------------- ### Configure Poetry scripts for database initialization Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Update Poetry scripts in pyproject.toml to include database initialization command. Allows running 'poetry run init_db' to create and update the database. ```toml [tool.poetry.scripts] init_db = "blog:init_db" start = "blog:run" ``` -------------------------------- ### Create New Quart Project with Poetry Source: https://github.com/pallets/quart/blob/main/docs/tutorials/video_tutorial.md Creates a new Python project named 'video' using Poetry, with source code located in a 'src' directory. This sets up the basic project structure. ```console poetry new --src video ``` -------------------------------- ### Create new Poetry project for chat application Source: https://github.com/pallets/quart/blob/main/docs/tutorials/chat_tutorial.md Initializes a new Poetry project with source code layout. Creates a project directory structure with proper configuration for Python package development. ```console poetry new --src chat ``` -------------------------------- ### Find Package - Python Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.helpers.md Locates the installation prefix and containing folder for a given Python package name. This function is useful for determining where installed packages reside on the filesystem, which can be helpful for configuration or resource loading. It returns a tuple containing the path to the package's installation directory (or None if not found) and the path to its containing folder. ```python from quart import Quart, find_package from pathlib import Path app = Quart(__name__) @app.route('/find_quart') def find_quart_package(): prefix, folder = find_package('quart') if prefix and folder: return f'Quart package found:
Prefix: {prefix}
Folder: {folder}' else: return 'Quart package not found.' @app.route('/find_nonexistent') def find_nonexistent_package(): prefix, folder = find_package('nonexistent_package_xyz') if prefix and folder: return f'Found nonexistent package: Prefix: {prefix}, Folder: {folder}' else: return 'Nonexistent package correctly not found.' ``` -------------------------------- ### Quart Request Method Handling Source: https://github.com/pallets/quart/blob/main/docs/reference/cheatsheet.md Shows how to specify allowed HTTP methods for a given route in Quart. By default, routes accept GET requests. You can explicitly define methods like GET, POST, or DELETE. ```python @app.route("/get") # GET Only by default @app.route("/get", methods=["GET", "POST"]) # GET and POST @app.route("/get", methods=["DELETE"]) # Just DELETE ``` -------------------------------- ### Pytest Fixture for Database Setup Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md This Python code sets up a temporary SQLite database for testing using pytest. The `configure_db` fixture runs automatically before tests, configuring the app to use a database file in a temporary directory and initializing the database schema. It requires pytest and the application's `init_db` function. ```python import pytest from blog import app, init_db @pytest.fixture(autouse=True) def configure_db(tmpdir): app.config['DATABASE'] = str(tmpdir.join('blog.db')) init_db() ``` -------------------------------- ### JavaScript WebSocket Client Example Source: https://context7.com/pallets/quart/llms.txt A client-side JavaScript example demonstrating how to connect to a WebSocket server, send messages, and handle incoming messages and errors. This code is intended to be run in a web browser. ```javascript // JavaScript WebSocket client example const ws = new WebSocket('ws://localhost:5000/ws'); ws.onopen = () => { ws.send('Hello Server'); }; ws.onmessage = (event) => { console.log('Received:', event.data); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ``` -------------------------------- ### Basic Quart Application Setup Source: https://context7.com/pallets/quart/llms.txt Demonstrates the creation of a simple Quart web application with asynchronous route handlers for basic HTTP requests. It includes instructions on how to run the application using Python or the Quart CLI and test it with curl. ```python from quart import Quart app = Quart(__name__) @app.route('/') async def hello(): return 'hello' @app.route('/hello/') async def hello_name(name): return f"Hello, {name}!" if __name__ == "__main__": app.run(debug=True) ``` ```bash # Run the application python app.py # Or using the CLI export QUART_APP=app:app quart run # Test with curl curl http://localhost:5000/ curl http://localhost:5000/hello/World ``` -------------------------------- ### Quart GET Route for Streaming Server Sent Events Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/server_sent_events.md An asynchronous GET route in Quart designed to stream Server Sent Events. It checks for the 'text/event-stream' Accept header, defines a generator function to yield encoded events, and configures the response with appropriate headers and disabled timeout. ```python from quart import abort, make_response, request @app.get("/sse") async def sse(): if "text/event-stream" not in request.accept_mimetypes: abort(400) async def send_events(): while True: data = ... # Up to you where the events are from event = ServerSentEvent(data) # Assuming ServerSentEvent class is defined elsewhere yield event.encode() response = await make_response( send_events(), { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Transfer-Encoding': 'chunked', }, ) response.timeout = None return response ``` -------------------------------- ### Create New API Project with Poetry Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Creates a new API project structure using Poetry. Subsequent commands should be run from within the created 'api' directory. ```console poetry new --src api ``` -------------------------------- ### Run Asynchronous Code in a Quart CLI Command Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/command_line.md This example shows how to execute asynchronous code within a Quart CLI command. It involves creating an event loop and using `run_until_complete` to execute an async function. The `_fetch` function is an example of an asynchronous operation that might interact with a database. ```python import asyncio @app.cli.command() def fetch_db_data(): result = asyncio.get_event_loop().run_until_complete(_fetch()) async def _fetch(): return await db.execute(...) ``` -------------------------------- ### GET requested_subprotocols Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.wrappers.websocket.md Property that returns the list of subprotocols requested by the WebSocket client during the handshake. ```APIDOC ## GET requested_subprotocols ### Description Retrieve the list of WebSocket subprotocols that were requested by the client. ### Method GET (Property) ### Response #### Success Response - **return** (list[str]) - List of subprotocol strings requested by the client ### Usage Example ```python subprotocols = websocket.requested_subprotocols print(subprotocols) # Output: ['protocol1', 'protocol2'] ``` ``` -------------------------------- ### Initialize Quart App and Run Function Source: https://github.com/pallets/quart/blob/main/docs/tutorials/api_tutorial.md Creates a basic Quart application instance and defines a run function. This code is typically placed in the main application file (e.g., src/api/__init__.py). ```python from quart import Quart app = Quart(__name__) def run() -> None: app.run() ``` -------------------------------- ### Query database and render posts with Quart route Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Implement GET route in src/blog/__init__.py that queries the SQLite database for blog posts and renders them using the Jinja2 template. Uses Quart's g object for request-scoped database connections. ```python from quart import render_template, g def _get_db(): if not hasattr(g, "sqlite_db"): g.sqlite_db = _connect_db() return g.sqlite_db @app.get("/") async def posts(): db = _get_db() cur = db.execute( """SELECT title, text FROM post ORDER BY id DESC""", ) posts = cur.fetchall() return await render_template("posts.html", posts=posts) ``` -------------------------------- ### quart.helpers.find_package() Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.helpers.md Locates the installation prefix and containing folder of a Python package. ```APIDOC ## quart.helpers.find_package(name) ### Description Finds packages install prefix (or None) and it’s containing Folder. ### Method GET (conceptual - finding package info) ### Endpoint N/A (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **name** (str) - The name of the package to find. ### Request Example ```python prefix, folder = find_package('quart') ``` ### Response #### Success Response (tuple) - **tuple[Path | None, Path]** - A tuple containing the package's install prefix (or None if not found) and its containing folder path. #### Response Example ```json [ "/path/to/venv/lib/python3.9/site-packages", "/path/to/venv/lib/python3.9/site-packages/quart" ] ``` ``` -------------------------------- ### Run Core Tests - Shell Source: https://github.com/pallets/quart/blob/main/CONTRIBUTING.md Basic commands to execute unit tests, run the main type checker (mypy), and build the documentation using tox. ```bash pytest mypy tox run -e docs ``` -------------------------------- ### Create Basic Quart Application Source: https://github.com/pallets/quart/blob/main/docs/tutorials/deployment.md Initializes a simple Quart ASGI application with a basic route handler. The application creates an async route that returns a plain text response. This serves as the foundation for deploying with external ASGI servers. ```python from quart import Quart app = Quart(__name__) @app.route('/') async def hello(): return 'Hello World' ``` -------------------------------- ### GET / Source: https://context7.com/pallets/quart/llms.txt A basic route that returns a simple string response. ```APIDOC ## GET / ### Description This endpoint serves a simple "hello" message. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example { "message": "hello" } ``` -------------------------------- ### Request Object Usage Source: https://github.com/pallets/quart/blob/main/docs/reference/cheatsheet.md Provides examples of accessing various parts of the incoming request. ```APIDOC ## Request Object Usage ### Description This endpoint demonstrates how to access different components of the incoming HTTP request, such as headers, query parameters, form data, JSON body, and cookies. ### Method GET, POST ### Endpoint /hello ### Parameters #### Query Parameters - **a** (string) - Optional - A query parameter example. #### Request Body - **name** (string) - Optional - Form data field. - **key** (any) - Optional - JSON body field. ### Request Example ```python from quart import request @app.route("/hello") async def hello(): request.method request.url request.headers["X-Bob"] request.args.get("a") # Query string e.g. example.com/hello?a=2 await request.get_data() # Full raw body (await request.form)["name"] (await request.get_json())["key"] request.cookies.get("name") ``` ### Response #### Success Response (200) - **body** (any) - The response content depends on how the request data is processed. #### Response Example ``` (Response varies based on request data) ``` ``` -------------------------------- ### Run Quart with Hypercorn ASGI Server Source: https://github.com/pallets/quart/blob/main/docs/tutorials/deployment.md Executes a Quart application using Hypercorn, the recommended ASGI server for production deployments. Hypercorn is pre-installed with Quart and provides better performance than the development server. ```bash hypercorn example:app ``` -------------------------------- ### Quart Route Handler for Post Creation Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md This Python code defines a Quart route handler for creating blog posts. It accepts GET requests to display the creation form and POST requests to process form data, insert it into the database, and redirect the user. It depends on Quart's request and redirect functionalities. ```python from quart import redirect, request, url_for @app.route("/create/", methods=["GET", "POST"]) async def create(): if request.method == "POST": db = _get_db() form = await request.form db.execute( "INSERT INTO post (title, text) VALUES (?, ?)", [form["title"], form["text"]], ) db.commit() return redirect(url_for("posts")) else: return await render_template("create.html") ``` -------------------------------- ### Build WebSocket chat UI with HTML and JavaScript Source: https://github.com/pallets/quart/blob/main/docs/tutorials/chat_tutorial.md Creates an interactive chat interface with WebSocket client functionality. The HTML includes JavaScript that establishes a WebSocket connection, handles incoming messages by appending them to a list, and sends user input to the server via the WebSocket connection. ```html
    ``` -------------------------------- ### GET /data Source: https://context7.com/pallets/quart/llms.txt Retrieves a static JSON object containing status and a list of data. ```APIDOC ## GET /data ### Description This endpoint returns a predefined JSON response with a status and a list of data. ### Method GET ### Endpoint /data ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The status of the request (e.g., "success"). - **data** (array) - A list of numbers. #### Response Example ```json { "status": "success", "data": [1, 2, 3] } ``` ``` -------------------------------- ### Startup and Shutdown Hooks Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.app.md Provides asynchronous methods for application startup and shutdown. ```APIDOC ## Startup and Shutdown Hooks ### Description Provides asynchronous methods for application startup and shutdown. ### Method ASYNC ### Endpoint Startup: `/startup`, Shutdown: `/shutdown` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python await app.startup() await app.shutdown() ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Serve Index Template in Quart Source: https://github.com/pallets/quart/blob/main/docs/tutorials/video_tutorial.md A Quart route that renders the 'index.html' template for the root path ('/'). This serves the video player UI to users. ```python from quart import render_template @app.get("/") async def index(): return await render_template("index.html") ``` -------------------------------- ### HTML Template for Video Player Source: https://github.com/pallets/quart/blob/main/docs/tutorials/video_tutorial.md An HTML template that creates a video player element. It includes a source tag pointing to '/video.mp4', which will be served by the Quart application. ```html ``` -------------------------------- ### GET /info Source: https://context7.com/pallets/quart/llms.txt Retrieves information about the current request, including query parameters, headers, and cookies. ```APIDOC ## GET /info ### Description This endpoint provides details about the incoming GET request, such as query parameters, headers, and cookies. ### Method GET ### Endpoint /info ### Parameters #### Path Parameters None #### Query Parameters - **page** (integer) - Optional - The page number for pagination (defaults to 1). - **limit** (integer) - Optional - The number of items per page (defaults to 10). ### Request Example `GET /info?page=2&limit=20` ### Response #### Success Response (200) - **method** (string) - The HTTP method of the request. - **url** (string) - The full URL of the request. - **page** (integer) - The requested page number. - **limit** (integer) - The requested limit per page. - **user_agent** (string | null) - The User-Agent header value, if present. - **has_auth** (boolean) - Indicates if an Authorization header was present. #### Response Example ```json { "method": "GET", "url": "http://localhost:5000/info?page=1&limit=10", "page": 1, "limit": 10, "user_agent": "curl/7.68.0", "has_auth": false } ``` ``` -------------------------------- ### Run Quart App with `quart run` Command Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/developing.md This console snippet demonstrates how to run a Quart application using the `quart run` command. The `QUART_APP` environment variable points to the application instance. This command is recommended for development as it enables features like the reloader. Options for host, port, and SSL certificates can be provided. ```console $ QUART_APP=run:app quart run ``` -------------------------------- ### GET /hello/ Source: https://context7.com/pallets/quart/llms.txt A route that takes a name as a path parameter and returns a personalized greeting. ```APIDOC ## GET /hello/ ### Description This endpoint greets a user by name, where the name is provided in the URL path. ### Method GET ### Endpoint /hello/ ### Parameters #### Path Parameters - **name** (string) - Required - The name to greet. #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **message** (string) - The personalized greeting. #### Response Example { "message": "Hello, World!" } ``` -------------------------------- ### Pytest Test for Blog Post Creation and Display Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md This Python code defines an asynchronous test function using pytest to verify blog post creation and display. It utilizes the Quart test client to simulate POST and GET requests, asserting that the post is created and then visible on the main page. This test requires pytest-asyncio. ```python from blog import app async def test_create_post(): test_client = app.test_client() response = await test_client.post("/create/", form={"title": "Post", "text": "Text"}) assert response.status_code == 302 response = await test_client.get("/") text = await response.get_data() assert b"

    Post

    " in text assert b"

    Text

    " in text ``` -------------------------------- ### Get Test App Instance Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.app.md Returns a test app protocol instance for testing purposes. This provides a testing interface compatible with the Quart application for running tests. ```APIDOC ## test_app() ### Description Return a test app protocol instance for testing the Quart application. ### Method Factory method ### Return Type TestAppProtocol ``` -------------------------------- ### Initialize Quart App for `quart run` Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/developing.md This Python snippet shows the basic initialization of a Quart application instance. It is intended to be used with the `quart run` command, where the app instance is specified via the QUART_APP environment variable. This is a common pattern for setting up a Quart application for development. ```python from quart import Quart app = Quart(__name__) ... ``` -------------------------------- ### Get Test App Protocol in Quart Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.app.md Returns a TestAppProtocol instance for testing the Quart application. This provides utilities and interfaces for simulating application behavior in test environments. ```python test_app = app.test_app() ``` -------------------------------- ### Concurrent URL Fetching with asyncio Source: https://github.com/pallets/quart/blob/main/docs/tutorials/asyncio.md Demonstrates concurrent programming using asyncio by simulating multiple URL fetches with varying delays. Uses asyncio.gather() to run multiple coroutines concurrently, showing how the event loop switches between tasks during IO waits. The example runs in approximately 2 seconds instead of 3 seconds with synchronous code, illustrating performance benefits. ```python import asyncio async def simulated_fetch(url, delay): await asyncio.sleep(delay) print(f"Fetched {url} after {delay}") return f"{url}" def main(): loop = asyncio.get_event_loop() results = loop.run_until_complete(asyncio.gather( simulated_fetch('http://google.com', 2), simulated_fetch('http://bbc.co.uk', 1), )) print(results) ``` -------------------------------- ### GET /error Source: https://context7.com/pallets/quart/llms.txt Demonstrates error handling by aborting with a 409 Conflict status code. Shows how to provide descriptive error messages in responses. ```APIDOC ## GET /error ### Description Abort with HTTP 409 Conflict error. ### Method GET ### Endpoint /error ### Response #### Error Response (409) - **error** (string) - Error type - **message** (string) - Error description #### Response Example { "error": "Conflict", "message": "Resource conflict" } ``` -------------------------------- ### Run Quart Application for Development Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.app.md Runs the Quart application, primarily intended for development use. It allows configuration of host, port, debug mode, and SSL certificates. For production, Hypercorn is recommended. Dependencies include Quart and potentially Hypercorn. ```python app.run(host=None, port=None, debug=None, use_reloader=True, loop=None, ca_certs=None, certfile=None, keyfile=None, **kwargs) ``` -------------------------------- ### Websocket Class Source: https://github.com/pallets/quart/blob/main/docs/reference/source/quart.wrappers.md Represents a WebSocket connection in Quart. This class handles bidirectional communication between client and server, managing the WebSocket lifecycle including connection setup, message exchange, and closure. ```APIDOC ## Websocket Class ### Description Represents an active WebSocket connection. This class manages the full lifecycle of a WebSocket connection including connection negotiation, message sending/receiving, and graceful closure. ### Constructor Parameters - **path** (str) - Required - The request path - **query_string** (bytes) - Required - Raw query string bytes - **scheme** (str) - Required - Connection scheme (ws or wss) - **headers** (Headers) - Required - HTTP headers - **root_path** (str) - Required - Root path for the application - **http_version** (str) - Required - HTTP version used - **subprotocols** (list[str]) - Required - List of supported WebSocket subprotocols - **receive** (Callable) - Required - Async callable to receive messages - **send** (Callable) - Required - Async callable to send messages - **accept** (Callable) - Required - Async callable to accept the connection - **close** (Callable) - Required - Async callable to close the connection - **scope** (WebsocketScope) - Required - ASGI scope dictionary ### Base Class BaseRequestWebsocket ### Usage Example ```python from quart import websocket @app.websocket('/echo') async def echo(): data = await websocket.receive() await websocket.send(data) ``` ``` -------------------------------- ### Create Jinja2 template for rendering blog posts Source: https://github.com/pallets/quart/blob/main/docs/tutorials/blog_tutorial.md Define HTML template in src/blog/templates/posts.html using Jinja2 syntax. Renders blog posts as articles with title and text, displaying a message if no posts exist. ```html
    {% for post in posts %}

    {{ post.title }}

    {{ post.text|safe }}

    {% else %}

    No posts available

    {% endfor %}
    ``` -------------------------------- ### Testing within App Context in Python Source: https://github.com/pallets/quart/blob/main/docs/how_to_guides/testing.md Shows how to execute code within the application context using `app.app_context()`. This is necessary for accessing application-level resources during testing. ```python async def test_app_context(app): async with app.app_context(): current_app.[use] ``` -------------------------------- ### Test Video Serving in Quart Source: https://github.com/pallets/quart/blob/main/docs/tutorials/video_tutorial.md Tests the video serving route ('/video.mp4') using Quart's test client. It verifies that the full video is returned for a standard request and the correct byte range for a conditional request. ```python from video import app async def test_auto_video() -> None: test_client = app.test_client() response = await test_client.get("/video.mp4") data = await response.get_data() assert len(data) == 255_849 response = await test_client.get("/video.mp4", headers={"Range": "bytes=200-1000"}) data = await response.get_data() assert len(data) == 801 ``` -------------------------------- ### GET /stream Source: https://context7.com/pallets/quart/llms.txt Returns a streaming response that sends data incrementally to the client. Useful for large datasets, server-sent events, or real-time data feeds. ```APIDOC ## GET /stream ### Description Stream response data line by line to the client. ### Method GET ### Endpoint /stream ### Response #### Success Response (200) - **Content-Type** - text/plain - **Transfer-Encoding** - chunked - **body** (stream) - Newline-separated lines sent incrementally #### Response Example Line 0 Line 1 Line 2 ... Line 9 ``` -------------------------------- ### GET /download/ Source: https://context7.com/pallets/quart/llms.txt Downloads a file from the uploads directory. The file is served as an attachment, which triggers a download dialog in the browser instead of displaying inline. ```APIDOC ## GET /download/ ### Description Download a file from the uploads directory as an attachment. ### Method GET ### Endpoint /download/ ### Parameters #### Path Parameters - **filename** (string) - Required - Name of file to download ### Request Example curl -O http://localhost:5000/download/document.pdf ### Response #### Success Response (200) - **Content-Disposition** - attachment; filename="{filename}" - **Content-Type** - Detected MIME type of file - **Content-Length** - File size in bytes #### Error Response (404) File not found ```