### Programmatic API with asyncio Source: https://context7.com/pgjones/hypercorn/llms.txt Serve an ASGI application programmatically using asyncio. This example demonstrates basic server setup and lifecycle management. ```python import asyncio from hypercorn.asyncio import serve from hypercorn.config import Config async def app(scope, receive, send): if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Hello from asyncio!', }) config = Config() config.bind = ["localhost:8080"] # Basic usage asyncio.run(serve(app, config)) ``` -------------------------------- ### Python Configuration File Example Source: https://context7.com/pgjones/hypercorn/llms.txt Configure Hypercorn using a Python file, allowing for dynamic settings based on environment variables. This example demonstrates binding, workers, logging, and conditional SSL configuration. ```python # hypercorn_config.py import os # Bindings bind = [f"0.0.0.0:{os.getenv('PORT', '8000')}"] # Workers workers = int(os.getenv('WORKERS', '4')) worker_class = "uvloop" # Logging accesslog = "-" errorlog = "-" loglevel = os.getenv('LOG_LEVEL', 'INFO') # Timeouts keep_alive_timeout = 5 graceful_timeout = 10 read_timeout = 60 # SSL (conditional) if os.getenv('SSL_ENABLED'): certfile = os.getenv('SSL_CERT', '/etc/ssl/cert.pem') keyfile = os.getenv('SSL_KEY', '/etc/ssl/key.pem') # HTTP/2 h2_max_concurrent_streams = 100 # WebSocket websocket_max_message_size = 16 * 1024 * 1024 websocket_ping_interval = 30 ``` -------------------------------- ### TOML Configuration File Example Source: https://context7.com/pgjones/hypercorn/llms.txt Configure Hypercorn using a TOML file. This example shows common settings for binding, workers, logging, timeouts, SSL, HTTP/2, and WebSockets. ```toml # config.toml bind = ["0.0.0.0:8000"] workers = 4 worker_class = "uvloop" # Logging accesslog = "-" errorlog = "-" loglevel = "INFO" access_log_format = '%(h)s %(l)s %(l)s %(t)s "% (r)s" %(s)s %(b)s "% (f)s" "% (a)s"' # Timeouts keep_alive_timeout = 5 graceful_timeout = 3 read_timeout = 60 # SSL (optional) # certfile = "/path/to/cert.pem" # keyfile = "/path/to/key.pem" # HTTP/2 settings h2_max_concurrent_streams = 100 h2_max_header_list_size = 65536 # WebSocket settings websocket_max_message_size = 16777216 websocket_ping_interval = 30 # Server headers include_server_header = true include_date_header = true # Backlog and limits backlog = 100 max_app_queue_size = 10 # Worker restart settings (for memory leak management) # max_requests = 1000 # max_requests_jitter = 50 # StatsD logging (optional) # statsd_host = "localhost:8125" # statsd_prefix = "hypercorn" ``` -------------------------------- ### Install Hypercorn Source: https://github.com/pgjones/hypercorn/blob/main/README.rst Install Hypercorn using pip. This command installs the base package. ```console pip install hypercorn ``` -------------------------------- ### Integrate with Quart ASGI Framework Source: https://context7.com/pgjones/hypercorn/llms.txt Example of setting up a basic Quart application with routes and a WebSocket endpoint, runnable via Hypercorn either from the command line or programmatically. ```python # app.py from quart import Quart app = Quart(__name__) @app.route('/') async def index(): return 'Hello from Quart!' @app.route('/api/data') async def get_data(): return {'message': 'JSON response', 'status': 'ok'} @app.websocket('/ws') async def websocket_endpoint(): while True: data = await websocket.receive() await websocket.send(f'Echo: {data}') # Run: hypercorn app:app # Or programmatically: if __name__ == '__main__': import asyncio from hypercorn.asyncio import serve from hypercorn.config import Config config = Config() config.bind = ["0.0.0.0:8000"] asyncio.run(serve(app, config)) ``` -------------------------------- ### Programmatic API with uvloop Source: https://context7.com/pgjones/hypercorn/llms.txt Serve an ASGI application programmatically using uvloop for enhanced performance on compatible systems. This example requires uvloop to be installed. ```python import asyncio import uvloop from hypercorn.asyncio import serve from hypercorn.config import Config async def app(scope, receive, send): if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Hello from uvloop!', }) config = Config() config.bind = ["localhost:8080"] # Install uvloop and run uvloop.install() asyncio.run(serve(app, config)) ``` -------------------------------- ### Programmatic Usage of Hypercorn Source: https://github.com/pgjones/hypercorn/blob/main/CHANGELOG.rst Demonstrates how to use Hypercorn programmatically with asyncio and trio. Ensure the appropriate event loop library is installed. ```python async def serve(app: Type[ASGIFramework], config: Config) -> None: asyncio.run(serve(app, config)) trio.run(serve, app, config) ``` -------------------------------- ### Programmatic API with Trio Source: https://context7.com/pgjones/hypercorn/llms.txt Integrate Hypercorn with Trio for structured concurrency. Ensure Trio is installed. ```python import trio from hypercorn.trio import serve from hypercorn.config import Config async def app(scope, receive, send): if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Hello from Trio!', }) config = Config() config.bind = ["localhost:8080"] trio.run(serve, app, config) ``` -------------------------------- ### Run Tests with Tox Source: https://github.com/pgjones/hypercorn/blob/main/README.rst Execute Hypercorn's tests and code style checks using Tox. Ensure Tox is installed in your environment first. ```console pipenv install tox tox ``` -------------------------------- ### Binding to Multiple Sockets with Hypercorn CLI Source: https://github.com/pgjones/hypercorn/blob/main/CHANGELOG.rst Example of how to bind Hypercorn to multiple IP addresses and ports using the command-line interface. This allows serving on both IPv4 and IPv6. ```bash hypercorn --bind '0.0.0.0:5000' --bind '[::]:5000' ... ``` -------------------------------- ### Configure Hypercorn for HTTP/3 (QUIC) Support Source: https://context7.com/pgjones/hypercorn/llms.txt Configure Hypercorn to support HTTP/3 using the QUIC protocol. This requires SSL certificates and specific bindings for both standard HTTPS and QUIC. Ensure 'hypercorn[h3]' is installed. ```python from hypercorn.config import Config config = Config() # Standard HTTPS binding config.bind = ["0.0.0.0:443"] # Add QUIC binding for HTTP/3 (same port, UDP) config.quic_bind = ["0.0.0.0:443"] # SSL is required for HTTP/3 config.certfile = "cert.pem" config.keyfile = "key.pem" # Optional: Configure Alt-Svc headers manually # (Hypercorn generates these automatically for QUIC bindings) # config.alt_svc_headers = ['h3=":443"; ma=3600'] # Run: pip install hypercorn[h3] # Then: hypercorn --certfile cert.pem --keyfile key.pem \ # --bind 0.0.0.0:443 --quic-bind 0.0.0.0:443 \ # module:app ``` -------------------------------- ### Use Legacy ProxyFixMiddleware Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/proxy_fix.md Wrap your application with ProxyFixMiddleware in 'legacy' mode when serving behind a single legacy proxy. Ensure 'trusted_hops' matches your proxy setup to prevent security risks. ```python from hypercorn.middleware import ProxyFixMiddleware fixed_app = ProxyFixMiddleware(app, mode="legacy", trusted_hops=1) ``` -------------------------------- ### Graceful Shutdown with shutdown_trigger Source: https://context7.com/pgjones/hypercorn/llms.txt Control server shutdown programmatically using the shutdown_trigger parameter. This example uses asyncio and handles SIGTERM signals for graceful shutdown. ```python import asyncio import signal from typing import Any from hypercorn.asyncio import serve from hypercorn.config import Config async def app(scope, receive, send): if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Hello!', }) config = Config() config.bind = ["localhost:8080"] config.graceful_timeout = 5.0 # Wait up to 5 seconds for requests to complete # Shutdown on SIGTERM signal shutdown_event = asyncio.Event() def _signal_handler(*_: Any) -> None: shutdown_event.set() loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGTERM, _signal_handler) loop.run_until_complete( serve(app, config, shutdown_trigger=shutdown_event.wait) ) # Disable signal handling entirely (server runs forever) # loop.run_until_complete( # serve(app, config, shutdown_trigger=lambda: asyncio.Future()) # ) ``` -------------------------------- ### Invoke Hypercorn Command Source: https://github.com/pgjones/hypercorn/blob/main/docs/tutorials/usage.md Use this command to invoke Hypercorn, specifying the ASGI or WSGI application module. Refer to the configuration guide for a full list of command-line arguments. ```shell $ hypercorn [OPTIONS] MODULE_APP ``` -------------------------------- ### Serve ASGI App from Command Line Source: https://github.com/pgjones/hypercorn/blob/main/README.rst Serve an ASGI application using Hypercorn from the command line. Replace 'module:app' with your application's module and app variable. ```console hypercorn module:app ``` -------------------------------- ### Create a Simple ASGI App Source: https://github.com/pgjones/hypercorn/blob/main/docs/tutorials/quickstart.md This Python code defines a basic ASGI application that responds with 'hello' to HTTP requests. Ensure the file is saved as hello_world.py. ```python async def app(scope, receive, send): if scope["type"] != "http": raise Exception("Only the HTTP protocol is supported") await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'content-type', b'text/plain'), (b'content-length', b'5'), ], }) await send({ 'type': 'http.response.body', 'body': b'hello', }) ``` -------------------------------- ### Load Config from Python File Source: https://context7.com/pgjones/hypercorn/llms.txt Load server configuration settings from a Python file. ```bash hypercorn --config file:config.py module:app ``` -------------------------------- ### Basic ASGI Application Source: https://context7.com/pgjones/hypercorn/llms.txt A minimal ASGI application that handles HTTP requests and responds with 'hello'. Requires Hypercorn to be run with 'hypercorn hello_world:app'. ```python # hello_world.py async def app(scope, receive, send): """Simple ASGI application that returns 'hello'.""" if scope["type"] != "http": raise Exception("Only the HTTP protocol is supported") await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'content-type', b'text/plain'), (b'content-length', b'5'), ], }) await send({ 'type': 'http.response.body', 'body': b'hello', }) # Run: hypercorn hello_world:app # Test: curl localhost:8000 ``` -------------------------------- ### Enable SSL/TLS Source: https://context7.com/pgjones/hypercorn/llms.txt Configure the server to use SSL/TLS for secure connections by specifying certificate and key files. ```bash hypercorn --certfile cert.pem --keyfile key.pem --bind localhost:443 module:app ``` -------------------------------- ### Load Config from TOML Source: https://context7.com/pgjones/hypercorn/llms.txt Load server configuration settings from a TOML file. ```bash hypercorn --config config.toml module:app ``` -------------------------------- ### Load Python File Configuration via Command Line Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/configuring.md Use the -c or --config option with the 'file:' prefix followed by the path to your Python configuration file. ```bash hypercorn --config file:file_path/file_name.py ``` -------------------------------- ### Load TOML Configuration via Command Line Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/configuring.md Use the -c or --config option with the path to your TOML configuration file. ```bash hypercorn --config file_path/file_name.toml ``` -------------------------------- ### Serve ASGI App with Asyncio Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Use the asyncio serve function to run an ASGI application with the configured Hypercorn settings. ```python import asyncio from hypercorn.asyncio import serve asyncio.run(serve(app, config)) ``` -------------------------------- ### Serve ASGI App with Uvloop and Asyncio Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Run an ASGI application using uvloop for enhanced performance with Hypercorn's asyncio serve function. ```python import asyncio import uvloop from hypercorn.asyncio import serve uvloop.install() asyncio.run(serve(app, config)) ``` -------------------------------- ### Load Config from Python Module Source: https://context7.com/pgjones/hypercorn/llms.txt Load server configuration settings from a Python module. ```bash hypercorn --config python:myconfig module:app ``` -------------------------------- ### Create Hypercorn Config Instance Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Instantiate a Hypercorn Config object and set basic configuration options like bind addresses. ```python from hypercorn.config import Config config = Config() config.bind = ["localhost:8080"] # As an example configuration setting ``` -------------------------------- ### Serve HTTPS and HTTP with Hypercorn Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/http_https_redirect.md Use the `--bind` option for HTTPS and `--insecure-bind` for HTTP. Ensure redirection middleware is outermost. ```shell $ hypercorn --certfile cert.pem --keyfile key.pem --bind localhost:443 --insecure-bind localhost:80 module:app ``` -------------------------------- ### Specify Host and Port Source: https://context7.com/pgjones/hypercorn/llms.txt Bind the server to a specific IP address and port for incoming connections. ```bash hypercorn --bind 0.0.0.0:8000 module:app ``` -------------------------------- ### Load TOML Configuration Programmatically Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/configuring.md Instantiate a Config object by loading settings from a TOML file using Config.from_toml(). ```python config = Config.from_toml("file_path/file_name.toml") ``` -------------------------------- ### Enable HTTP/3 (QUIC) Source: https://context7.com/pgjones/hypercorn/llms.txt Configure Hypercorn to support the HTTP/3 protocol (QUIC) by specifying certificate and key files for the QUIC bind address. ```bash hypercorn --certfile cert.pem --keyfile key.pem --quic-bind localhost:443 module:app ``` -------------------------------- ### Serve Redirected App with Hypercorn Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/http_https_redirect.md Serve the application wrapped with redirection middleware using both secure and insecure binds. ```shell $ hypercorn --certfile cert.pem --keyfile key.pem --bind localhost:443 --insecure-bind localhost:80 module:redirected_app ``` -------------------------------- ### Configure Logging Source: https://context7.com/pgjones/hypercorn/llms.txt Set up access and error logging to standard output ('-') and specify the log level for detailed debugging. ```bash hypercorn --access-logfile - --error-logfile - --log-level DEBUG module:app ``` -------------------------------- ### Load Python File Configuration Programmatically Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/configuring.md Configure Hypercorn by loading attributes from a Python file using Config.from_pyfile(). ```python config = Config.from_pyfile("file_path/file_name.py") ``` -------------------------------- ### Integrate with FastAPI/Starlette ASGI Framework Source: https://context7.com/pgjones/hypercorn/llms.txt Demonstrates a FastAPI application with standard HTTP routes, path parameters, query parameters, and a WebSocket endpoint, ready to be served by Hypercorn. ```python # main.py from fastapi import FastAPI, WebSocket app = FastAPI() @app.get("/") async def root(): return {"message": "Hello from FastAPI"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await websocket.accept() while True: data = await websocket.receive_text() await websocket.send_text(f"Message received: {data}") # Run: hypercorn main:app # Or with configuration: # hypercorn --bind 0.0.0.0:8000 --workers 4 --worker-class uvloop main:app ``` -------------------------------- ### Serve ASGI App with Trio Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Use the trio serve function to run an ASGI application with the configured Hypercorn settings. ```python import trio from hypercorn.trio import serve trio.run(serve, app, config) ``` -------------------------------- ### Serve Dispatcher App with Hypercorn Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/dispatch_apps.md Serve the configured DispatcherMiddleware application using the hypercorn command-line interface. Specify the module and application name. ```shell $ hypercorn module:dispatcher_app ``` -------------------------------- ### Run ASGI App with Hypercorn Source: https://github.com/pgjones/hypercorn/blob/main/docs/tutorials/quickstart.md Use the hypercorn command-line tool to run your ASGI application. Specify the application object by its module and variable name. ```console hypercorn hello_world:app ``` -------------------------------- ### Mount Multiple ASGI Apps with DispatcherMiddleware Source: https://context7.com/pgjones/hypercorn/llms.txt Use DispatcherMiddleware to mount multiple ASGI applications under different root paths. The order of paths in the dictionary matters, with more specific paths needing to be defined first. ```python from hypercorn.middleware import DispatcherMiddleware async def api_app(scope, receive, send): """API application mounted at /api""" if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'application/json')], }) await send({ 'type': 'http.response.body', 'body': b'{"message": "API response"}', }) async def static_app(scope, receive, send): """Static file application mounted at root /""" if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/html')], }) await send({ 'type': 'http.response.body', 'body': b'Static content', }) async def admin_app(scope, receive, send): """Admin application mounted at /admin""" if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Admin panel', }) # Order matters! More specific paths must come first app = DispatcherMiddleware({ "/api": api_app, "/admin": admin_app, "/": static_app, # Catch-all last }) # Run: hypercorn module:app ``` -------------------------------- ### Load Python Module Configuration via Command Line Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/configuring.md Specify a Python module or an instance within a module using the -c or --config option with the 'python:' prefix. ```bash hypercorn --config python:module_name ``` -------------------------------- ### Multiple Bind Addresses Source: https://context7.com/pgjones/hypercorn/llms.txt Configure the server to listen on multiple IP addresses and ports simultaneously, supporting both IPv4 and IPv6. ```bash hypercorn --bind '0.0.0.0:5000' --bind '[::]:5000' module:app ``` -------------------------------- ### SSL with Insecure Bind for Redirects Source: https://context7.com/pgjones/hypercorn/llms.txt Enable SSL/TLS and configure an additional insecure bind address, typically for handling HTTP-to-HTTPS redirects. ```bash hypercorn --certfile cert.pem --keyfile key.pem --bind localhost:443 --insecure-bind localhost:80 module:app ``` -------------------------------- ### Run Hypercorn Programmatically with Asyncio Source: https://context7.com/pgjones/hypercorn/llms.txt This snippet shows how to configure and run the Hypercorn server programmatically using Python's asyncio. Ensure 'app' is defined elsewhere in your application. ```python if __name__ == '__main__': import asyncio from hypercorn.asyncio import serve from hypercorn.config import Config config = Config() config.bind = ["0.0.0.0:8000"] config.workers = 4 asyncio.run(serve(app, config)) ``` -------------------------------- ### Programmatic ASGI Server Usage Source: https://github.com/pgjones/hypercorn/blob/main/README.rst Programmatically run an ASGI application using Hypercorn with asyncio. Ensure the 'app' object is correctly imported and configured. ```python import asyncio from hypercorn.config import Config from hypercorn.asyncio import serve from module import app asyncio.run(serve(app, Config())) ``` -------------------------------- ### Config Class Loading Methods Source: https://context7.com/pgjones/hypercorn/llms.txt Load Hypercorn configuration from various sources including mappings, TOML files, Python files, and objects. ```python from hypercorn.config import Config # Create config from mapping/dictionary config = Config.from_mapping({ 'bind': ['localhost:8080'], 'workers': 2, 'accesslog': '-', }) # Or with keyword arguments config = Config.from_mapping(bind=['localhost:8080'], workers=2) # Load from TOML file config = Config.from_toml("config.toml") # Load from Python file config = Config.from_pyfile("hypercorn_config.py") # Load from Python module or object config = Config.from_object("myconfig") config = Config.from_object("myconfig.settings") ``` -------------------------------- ### Configure StatsD Metrics Logging Source: https://context7.com/pgjones/hypercorn/llms.txt Enable exporting server metrics to StatsD or DogStatsD by configuring the host, port, and an optional prefix. DogStatsD supports additional tags for finer-grained monitoring. ```python from hypercorn.config import Config config = Config() config.bind = ["localhost:8000"] # Enable StatsD logging config.statsd_host = "localhost:8125" config.statsd_prefix = "myapp.hypercorn" # For DogStatsD, add tags config.dogstatsd_tags = "env:production,service:myapp" # Metrics exported: # - hypercorn.requests: rate of requests # - hypercorn.request.duration: request duration in milliseconds # - hypercorn.request.status.[code]: rate of responses by status code # - hypercorn.log.critical: rate of critical log messages # - hypercorn.log.error: rate of error log messages # - hypercorn.log.warning: rate of warning log messages # - hypercorn.log.exception: rate of exceptional log messages ``` -------------------------------- ### Serve WSGI Application Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/wsgi_apps.md Command to serve a WSGI application using Hypercorn. ```shell $ hypercorn module:wsgi_app ``` -------------------------------- ### Run WSGI Application Source: https://context7.com/pgjones/hypercorn/llms.txt Serve a WSGI application directly from the command line. Hypercorn automatically detects the application type. ```bash hypercorn module:wsgi_app ``` -------------------------------- ### Configure DispatcherMiddleware for Multiple ASGI Apps Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/dispatch_apps.md Use DispatcherMiddleware to map different ASGI applications to specific root paths. Ensure that more specific paths are listed before general ones in the configuration dictionary. ```python from hypercorn.middleware import DispatcherMiddleware dispatcher_app = DispatcherMiddleware({ "/graphql": graphql_app, "/": static_app, }) ``` -------------------------------- ### Integrate WSGI Apps with AsyncioWSGIMiddleware and TrioWSGIMiddleware Source: https://context7.com/pgjones/hypercorn/llms.txt Serve WSGI applications using AsyncioWSGIMiddleware or TrioWSGIMiddleware, or combine them with other ASGI middleware. You can configure the maximum request body size and mix WSGI and ASGI applications. ```python from hypercorn.middleware import AsyncioWSGIMiddleware, TrioWSGIMiddleware def wsgi_app(environ, start_response): """Standard WSGI application""" status = '200 OK' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) return [b'Hello from WSGI!'] # For asyncio/uvloop workers asyncio_app = AsyncioWSGIMiddleware(wsgi_app) # For trio workers trio_app = TrioWSGIMiddleware(wsgi_app) # Configure maximum request body size (default 64KB) asyncio_app = AsyncioWSGIMiddleware(wsgi_app, max_body_size=1024 * 1024) # 1MB # Combine with other ASGI middleware from hypercorn.middleware import DispatcherMiddleware async def api_app(scope, receive, send): """ASGI API app""" await send({'type': 'http.response.start', 'status': 200, 'headers': []}) await send({'type': 'http.response.body', 'body': b'ASGI API'}) # Mix ASGI and WSGI apps combined_app = DispatcherMiddleware({ "/api": api_app, "/legacy": AsyncioWSGIMiddleware(wsgi_app), }) # Run: hypercorn module:asyncio_app ``` -------------------------------- ### Multiple Binds for Dual Stack Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/binds.md Configure Hypercorn to bind to multiple addresses simultaneously, such as both IPv4 and IPv6, to serve on all specified interfaces. This can be done via command-line arguments or a configuration file. ```shell $ hypercorn --bind '0.0.0.0:5000' --bind '[::]:5000' ... ``` ```python bind = ["0.0.0.0:5000", "[::]:5000"] ``` -------------------------------- ### Implement HTTP to HTTPS Redirect Middleware Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/http_https_redirect.md Wrap your ASGI application with `HTTPToHTTPSRedirectMiddleware` to handle redirects. Specify the target host for redirects. ```python redirected_app = HTTPToHTTPSRedirectMiddleware(app, host="example.com") ``` -------------------------------- ### Wrap WSGI App with ASGI Middleware Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/wsgi_apps.md Wrap a WSGI application with AsyncioWSGIMiddleware or TrioWSGIMiddleware for use with Hypercorn workers. ```python from hypercorn.middleware import AsyncioWSGIMiddleware, TrioWSGIMiddleware asyncio_app = AsyncioWSGIMiddleware(wsgi_app) trio_app = TrioWSGIMiddleware(wsgi_app) ``` -------------------------------- ### Configure Access Logging Source: https://context7.com/pgjones/hypercorn/llms.txt Set up detailed access logging to stdout and define custom log formats using available atoms. Error logging can also be directed to stderr with a specified log level. ```python from hypercorn.config import Config config = Config() config.bind = ["localhost:8000"] # Enable access logging to stdout config.accesslog = "-" # Custom access log format using atoms # Available atoms: # h - remote address # t - date of request # r - status line (e.g., GET / HTTP/1.1) # R - status line with query string # m - request method # U - URL path without query string # Uq - URL path with query string # q - query string # H - protocol # s - status code # st - status phrase (OK, Not Found, etc.) # S - scheme (http, https, ws, wss) # B - response length # b - response length or '-' (CLF format) # f - referer # a - user agent # T - request time in seconds # D - request time in microseconds # L - request time in decimal seconds # p - process ID # {Header}i - request header # {Header}o - response header # {Variable}e - environment variable config.access_log_format = '%(h)s %(l)s %(l)s %(t)s "%(r)s" %(s)s %(b)s "%(f)s" "%(a)s"' # Alternative detailed format config.access_log_format = '%(h)s - %(t)s "%(m)s %(U)s %(H)s" %(s)s %(B)s %(D)sms' # Error logging config.errorlog = "-" # stderr config.loglevel = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL # Use external logging configuration file config.logconfig = "logging.ini" # ini format config.logconfig = "json:logging.json" # JSON format config.logconfig = "toml:logging.toml" # TOML format ``` -------------------------------- ### Load Python Module Configuration Programmatically Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/configuring.md Load configuration from a Python module or an instance within a module using Config.from_object(). ```python config = Config.from_object("module_name.instance") ``` -------------------------------- ### Config Class Manual Configuration Source: https://context7.com/pgjones/hypercorn/llms.txt Configure Hypercorn using the Config class by manually setting attributes. Supports SSL, HTTP/2, and WebSocket settings. ```python from hypercorn.config import Config # Create config manually config = Config() config.bind = ["0.0.0.0:8000"] config.workers = 4 config.worker_class = "asyncio" # or "uvloop", "trio" config.accesslog = "-" # Log to stdout config.errorlog = "-" # Log to stderr config.loglevel = "INFO" config.keep_alive_timeout = 5.0 config.graceful_timeout = 3.0 config.debug = False # SSL configuration config.certfile = "/path/to/cert.pem" config.keyfile = "/path/to/key.pem" config.keyfile_password = "optional_password" config.ca_certs = "/path/to/ca.pem" # HTTP/2 settings config.h2_max_concurrent_streams = 100 config.h2_max_header_list_size = 65536 config.h2_max_inbound_frame_size = 16384 # WebSocket settings config.websocket_max_message_size = 16 * 1024 * 1024 # 16MB config.websocket_ping_interval = 30.0 # Keep-alive pings ``` -------------------------------- ### Force ASGI Mode Source: https://context7.com/pgjones/hypercorn/llms.txt Explicitly specify that an application should be served in ASGI mode. ```bash hypercorn asgi:module:app ``` -------------------------------- ### Force ASGI Mode Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Explicitly set the application mode to ASGI using the 'mode' argument in the serve function. ```python serve(app, config, mode="asgi") ``` -------------------------------- ### File Descriptor Binding Source: https://context7.com/pgjones/hypercorn/llms.txt Bind the server to a pre-existing file descriptor, useful in environments where the file descriptor is managed externally. ```bash hypercorn --bind fd://2 module:app ``` -------------------------------- ### Handle Proxy Headers with ProxyFixMiddleware Source: https://context7.com/pgjones/hypercorn/llms.txt Use ProxyFixMiddleware to correct client address, scheme, and host headers when Hypercorn is behind a reverse proxy. Configure 'trusted_hops' based on the number of proxies in front of Hypercorn. ```python from hypercorn.middleware import ProxyFixMiddleware async def app(scope, receive, send): """Application that uses client info from proxy headers""" if scope["type"] == "http": client_ip = scope.get("client", ("unknown", 0))[0] scheme = scope.get("scheme", "http") body = f"Client IP: {client_ip}, Scheme: {scheme}".encode() await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ (b'content-type', b'text/plain'), (b'content-length', str(len(body)).encode()), ], }) await send({ 'type': 'http.response.body', 'body': body, }) # Legacy mode for X-Forwarded-* headers (most common) # trusted_hops = number of proxies in front of Hypercorn fixed_app = ProxyFixMiddleware(app, mode="legacy", trusted_hops=1) # Modern mode for RFC 7239 Forwarded header # fixed_app = ProxyFixMiddleware(app, mode="modern", trusted_hops=1) # Run: hypercorn module:fixed_app ``` -------------------------------- ### Configure Max Body Size for WSGI Middleware Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/wsgi_apps.md Configure the maximum request body size for AsyncioWSGIMiddleware. The default max size can be overridden. ```python app = AsyncioWSGIMiddleware(wsgi_app, max_body_size=20) # Bytes ``` -------------------------------- ### Bind to Unix Domain Socket Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/binds.md Use the `unix:` prefix to specify a Unix domain socket for Hypercorn to bind to. This is useful for inter-process communication on Unix-like systems. ```shell $ hypercorn --bind unix:/tmp/socket.sock ``` -------------------------------- ### Bind to File Descriptor Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/binds.md Use the `fd://` prefix followed by the descriptor number to bind Hypercorn to an existing file descriptor. This is typically used in environments where the socket is pre-configured. ```shell $ hypercorn --bind fd://2 ``` -------------------------------- ### Test ASGI App with curl Source: https://github.com/pgjones/hypercorn/blob/main/docs/tutorials/quickstart.md Verify that your ASGI application is running correctly by sending an HTTP request to the default address and port using curl. ```sh curl localhost:8000 ``` -------------------------------- ### Test HTTP/2 Upgrade with Curl Source: https://github.com/pgjones/hypercorn/blob/main/docs/discussion/http2.md Use this command to test the h2c HTTP/1.1 to HTTP/2 upgrade process. Ensure Hypercorn is running and accessible at the specified URL and port. ```shell $ curl --http2 http://url:port/path ``` -------------------------------- ### Use uvloop Worker Source: https://context7.com/pgjones/hypercorn/llms.txt Specify 'uvloop' as the worker class for potentially faster performance, primarily on Linux and macOS systems. ```bash hypercorn --worker-class uvloop module:app ``` -------------------------------- ### Force WSGI Mode Source: https://context7.com/pgjones/hypercorn/llms.txt Explicitly specify that an application should be served in WSGI mode. ```bash hypercorn wsgi:module:wsgi_app ``` -------------------------------- ### Force WSGI Mode Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Explicitly set the application mode to WSGI using the 'mode' argument in the serve function. ```python serve(app, config, mode="wsgi") ``` -------------------------------- ### Graceful Shutdown with Signal Handler Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Implement graceful shutdown by adding a SIGTERM signal handler that sets an asyncio event. ```python import asyncio import signal shutdown_event = asyncio.Event() def _signal_handler(*_: Any) -> None: shutdown_event.set() loop = asyncio.get_event_loop() loop.add_signal_handler(signal.SIGTERM, _signal_handler) loop.run_until_complete( serve(app, config, shutdown_trigger=shutdown_event.wait) ) ``` -------------------------------- ### Use trio Worker Source: https://context7.com/pgjones/hypercorn/llms.txt Specify 'trio' as the worker class, enabling compatibility with applications built using the Trio asynchronous framework. ```bash hypercorn --worker-class trio module:app ``` -------------------------------- ### Handle SSL Errors Programmatically Source: https://context7.com/pgjones/hypercorn/llms.txt Configure a custom exception handler to ignore SSL handshake failures when using the programmatic API. Ensure cert.pem and key.pem are available. ```python import asyncio import ssl from hypercorn.asyncio import serve from hypercorn.config import Config async def app(scope, receive, send): if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Secure connection established!', }) def _exception_handler(loop: asyncio.AbstractEventLoop, context: dict) -> None: """Custom exception handler to ignore SSL handshake failures.""" exception = context.get("exception") if isinstance(exception, ssl.SSLError): pass # Silently ignore SSL handshake failures else: loop.default_exception_handler(context) config = Config() config.bind = ["localhost:8443"] config.certfile = "cert.pem" config.keyfile = "key.pem" loop = asyncio.get_event_loop() loop.set_exception_handler(_exception_handler) loop.run_until_complete(serve(app, config)) ``` -------------------------------- ### Configure Event Loop Exception Handler for SSL Errors Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Set a custom exception handler for the event loop to manage or ignore SSLErrors during the handshake. ```python def _exception_handler(loop, context): exception = context.get("exception") if isinstance(exception, ssl.SSLError): pass # Handshake failure else: loop.default_exception_handler(context) loop.set_exception_handler(_exception_handler) ``` -------------------------------- ### Redirect HTTP to HTTPS with HTTPToHTTPSRedirectMiddleware Source: https://context7.com/pgjones/hypercorn/llms.txt Automatically redirect HTTP requests to HTTPS using HTTPToHTTPSRedirectMiddleware. The 'host' parameter specifies the domain to redirect to. ```python from hypercorn.middleware import HTTPToHTTPSRedirectMiddleware async def secure_app(scope, receive, send): """Your main ASGI application""" if scope["type"] == "http": await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Secure content over HTTPS', }) # Wrap your app with redirect middleware # The host parameter specifies where to redirect users app = HTTPToHTTPSRedirectMiddleware(secure_app, host="example.com") # Run with both secure and insecure binds: # hypercorn --certfile cert.pem --keyfile key.pem \ # --bind localhost:443 --insecure-bind localhost:80 \ # module:app ``` -------------------------------- ### Enable Auto-Reload Source: https://context7.com/pgjones/hypercorn/llms.txt Activate the auto-reload feature, which restarts the server automatically when code changes are detected during development. ```bash hypercorn --reload module:app ``` -------------------------------- ### Unix Socket Binding Source: https://context7.com/pgjones/hypercorn/llms.txt Bind the server to a Unix domain socket, commonly used for inter-process communication on Unix-like systems. ```bash hypercorn --bind unix:/tmp/socket.sock module:app ``` -------------------------------- ### Multiple Workers Source: https://context7.com/pgjones/hypercorn/llms.txt Run multiple worker processes to handle requests concurrently, improving throughput and fault tolerance. ```bash hypercorn --workers 4 module:app ``` -------------------------------- ### Disable Signal Handling with Future Source: https://github.com/pgjones/hypercorn/blob/main/docs/how_to_guides/api_usage.md Prevent signal handling by providing a shutdown_trigger that returns an uncompletable future. ```python loop.run_until_complete( serve(app, config, shutdown_trigger=lambda: asyncio.Future()) ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.