### Unittest Example Source: https://github.com/falconry/falcon/blob/master/docs/api/testing.md Demonstrates how to set up a test case using unittest and simulate HTTP GET requests to test a Falcon application. ```python # ----------------------------------------------------------------- # unittest # ----------------------------------------------------------------- from falcon import testing import myapp class MyTestCase(testing.TestCase): def setUp(self): super(MyTestCase, self).setUp() # Assume the hypothetical `myapp` package has a # function called `create()` to initialize and # return a `falcon.App` instance. self.app = myapp.create() class TestMyApp(MyTestCase): def test_get_message(self): doc = {'message': 'Hello world!'} result = self.simulate_get('/messages/42') self.assertEqual(result.json, doc) ``` -------------------------------- ### Run Benchmarks Directly After Local Setup Source: https://github.com/falconry/falcon/blob/master/docs/community/contributing.md Set up a virtual environment, install dependencies, and run the falcon-bench command directly. This is an alternative to using tox for benchmarking. ```bash $ pyenv virtualenv 3.10.6 falcon-sandbox-310 $ pyenv shell falcon-sandbox-310 $ pip install -r requirements/bench $ pip install -e . $ falcon-bench ``` -------------------------------- ### Run Simple ASGI Falcon App with Uvicorn Source: https://github.com/falconry/falcon/blob/master/README.rst Install Falcon and uvicorn, then run the ASGI application example using the uvicorn server. ```bash $ pip install falcon uvicorn $ uvicorn things_asgi:app ``` -------------------------------- ### Basic App Initialization with Type Hinting Source: https://github.com/falconry/falcon/blob/master/docs/api/typing.md This example shows a basic Falcon application setup with type hints for the `falcon.App` instance. It may require explicit type parameters in strict type checking modes. ```python import falcon class HelloResource: def on_get(self, req: falcon.Request, resp: falcon.Response) -> None: resp.media = {'message': 'Hello, typing!'} def create_app() -> falcon.App: app = falcon.App() app.add_route('/', HelloResource()) return app ``` -------------------------------- ### Basic Falcon Application Setup Source: https://github.com/falconry/falcon/blob/master/docs/index.md This snippet demonstrates how to set up a basic Falcon application with a simple GET endpoint. It defines a resource class and adds it to the Falcon application instance. ```python import falcon class QuoteResource: def on_get(self, req: falcon.Request, resp: falcon.Response) -> None: """Handle GET requests.""" resp.media = { 'quote': "I've always been more interested in the future than in the past.", 'author': 'Grace Hopper', } app = falcon.App() app.add_route('/quote', QuoteResource()) ``` -------------------------------- ### ASGI Application Setup Source: https://github.com/falconry/falcon/blob/master/README.rst Sets up an ASGI Falcon application with custom storage, error handling, and a sink adapter for proxying requests. This example uses `httpx` for asynchronous HTTP requests. ```python # examples/things_advanced_asgi.py import json import logging import uuid import falcon import falcon.asgi import httpx class StorageEngine: async def get_things(self, marker, limit): return [{'id': str(uuid.uuid4()), 'color': 'green'}] async def add_thing(self, thing): thing['id'] = str(uuid.uuid4()) return thing class StorageError(Exception): @staticmethod async def handle(ex, req, resp, params): # TODO: Log the error, clean up, etc. before raising raise falcon.HTTPInternalServerError() class SinkAdapter: engines = { 'ddg': 'https://duckduckgo.com', 'y': 'https://search.yahoo.com/search', } async def __call__(self, req, resp, engine): url = self.engines[engine] params = {'q': req.get_param('q', True)} async with httpx.AsyncClient() as client: result = await client.get(url, params=params) resp.status = result.status_code resp.content_type = result.headers['content-type'] resp.text = result.text class AuthMiddleware: async def process_request(self, req, resp): token = req.get_header('Authorization') ``` -------------------------------- ### Install Falcon from Source Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md Clone the repository and install Falcon using pip. This is the standard installation method. ```bash cd falcon pip install . ``` -------------------------------- ### Run Simple WSGI Falcon App Source: https://github.com/falconry/falcon/blob/master/README.rst Install Falcon and run the basic WSGI application example using the Python interpreter. ```bash $ pip install falcon $ python things.py ``` -------------------------------- ### Pytest Example Source: https://github.com/falconry/falcon/blob/master/docs/api/testing.md Shows how to use pytest fixtures to set up a test client and simulate HTTP GET requests for testing a Falcon application. ```python # ----------------------------------------------------------------- # pytest # ----------------------------------------------------------------- from falcon import testing import pytest import myapp # Depending on your testing strategy and how your application # manages state, you may be able to broaden the fixture scope # beyond the default 'function' scope used in this example. @pytest.fixture() def client(): # Assume the hypothetical `myapp` package has a function called # `create()` to initialize and return a `falcon.App` instance. return testing.TestClient(myapp.create()) def test_get_message(client): doc = {'message': 'Hello world!'} result = client.simulate_get('/messages/42') assert result.json == doc ``` -------------------------------- ### Initialize virtual environment and install dependencies Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Set up a Python virtual environment and install Falcon and the Uvicorn ASGI server with standard extras. ```bash mkdir asgilook python3 -m venv asgilook/.venv source asgilook/.venv/bin/activate pip install falcon pip install uvicorn[standard] ``` -------------------------------- ### Basic ASGI App with Resource Source: https://github.com/falconry/falcon/blob/master/docs/api/request_and_response_asgi.md A simple ASGI application setup using Falcon, demonstrating how to add a resource with an async GET responder. ```python import falcon.asgi class Resource: async def on_get(self, req, resp): resp.media = {'message': 'Hello world!'} resp.status = 200 # -- snip -- app = falcon.asgi.App() app.add_route('/', Resource()) ``` -------------------------------- ### Install Falcon and Set Up Virtual Environment Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Commands to create a project directory, set up a virtual environment, activate it, and install the Falcon library. ```bash mkdir look cd look virtualenv .venv source .venv/bin/activate pip install falcon ``` -------------------------------- ### Install Falcon from Source Source: https://github.com/falconry/falcon/blob/master/README.rst Install Falcon after cloning the repository. Use 'pip install .' for a standard installation or 'pip install -e .' for an editable installation. ```bash cd falcon pip install . ``` ```bash pip install -e . ``` -------------------------------- ### Create a Simple ASGI Falcon App Source: https://github.com/falconry/falcon/blob/master/README.rst A basic example of a Falcon ASGI application. It defines a resource with an async GET handler. ```python # examples/things_asgi.py import falcon import falcon.asgi # Falcon follows the REST architectural style, meaning (among # other things) that you think in terms of resources and state # transitions, which map to HTTP verbs. class ThingsResource: async def on_get(self, req, resp): """Handles GET requests""" resp.status = falcon.HTTP_200 # This is the default status resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override resp.text = (' Two things awe me most, the starry sky ' 'above me and the moral law within me. ' ' ' ' ~ Immanuel Kant ') # falcon.asgi.App instances are callable ASGI apps... # in larger applications the app is created in a separate file app = falcon.asgi.App() # Resources are represented by long-lived class instances things = ThingsResource() # things will handle all requests to the '/things' URL path app.add_route('/things', things) ``` -------------------------------- ### Run Falcon App with Gunicorn Source: https://github.com/falconry/falcon/blob/master/docs/user/quickstart.md Install Gunicorn and run the Falcon application. This command starts the application and makes it accessible. ```bash pip install requests gunicorn gunicorn things:app ``` -------------------------------- ### Install Falcon using pip Source: https://github.com/falconry/falcon/blob/master/README.rst Install the latest stable version of Falcon. Use --pre to install beta or release candidates. ```bash pip install falcon ``` ```bash pip install --pre falcon ``` -------------------------------- ### Install Falcon from GitHub Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md Install the latest developmental snapshot of Falcon directly from its GitHub repository. ```bash pip install git+https://github.com/falconry/falcon/ ``` -------------------------------- ### Create Basic Falcon ASGI Application Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-websockets.md A minimal Falcon ASGI application with a '/hello' route that returns JSON. Used to verify the project setup and Falcon installation. ```python import falcon.asgi import uvicorn app = falcon.asgi.App() class HelloWorldResource: async def on_get(self, req, resp): resp.media = {'hello': 'world'} app.add_route('/hello', HelloWorldResource()) if __name__ == '__main__': uvicorn.run(app, host='localhost', port=8000) ``` -------------------------------- ### Run Falcon App with Waitress Source: https://github.com/falconry/falcon/blob/master/docs/user/quickstart.md Install Waitress and run the Falcon application on Windows. This command starts the application and makes it accessible. ```bash pip install requests waitress waitress-serve --port=8000 things:app ``` -------------------------------- ### Install ASGI Server Source: https://github.com/falconry/falcon/blob/master/README.rst Install an ASGI server such as Uvicorn to serve a Falcon ASGI application. ```bash pip install uvicorn ``` -------------------------------- ### Install and Run Waitress (Windows) Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Commands to install Waitress, a WSGI server suitable for Windows, and run the Falcon application. ```bash pip install waitress waitress-serve --port=8000 look.app:app ``` -------------------------------- ### Install WSGI Server Source: https://github.com/falconry/falcon/blob/master/README.rst Install a WSGI server like Gunicorn or uWSGI to serve a Falcon application. ```bash pip install [gunicorn|uwsgi] ``` -------------------------------- ### Install HTTPie Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Command to install HTTPie, a user-friendly command-line HTTP client. ```bash source .venv/bin/activate pip install httpie ``` -------------------------------- ### Install Falcon (Pre-release) Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md Install the latest beta or release candidate version of Falcon from PyPI. Use this if you need to test upcoming features. ```bash pip install --pre falcon ``` -------------------------------- ### Create a Simple WSGI Falcon App Source: https://github.com/falconry/falcon/blob/master/README.rst A basic example of a Falcon WSGI application. It defines a resource with a GET handler and serves it using wsgiref. ```python # examples/things.py # Let's get this party started! from wsgiref.simple_server import make_server import falcon # Falcon follows the REST architectural style, meaning (among # other things) that you think in terms of resources and state # transitions, which map to HTTP verbs. class ThingsResource: def on_get(self, req, resp): """Handles GET requests""" resp.status = falcon.HTTP_200 # This is the default status resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override resp.text = (' Two things awe me most, the starry sky ' 'above me and the moral law within me. ' ' ' ' ~ Immanuel Kant ') # falcon.App instances are callable WSGI apps... # in larger applications the app is created in a separate file app = falcon.App() # Resources are represented by long-lived class instances things = ThingsResource() # things will handle all requests to the '/things' URL path app.add_route('/things', things) if __name__ == '__main__': with make_server('', 8000, app) as httpd: print('Serving on port 8000...') # Serve until process is killed httpd.serve_forever() ``` -------------------------------- ### Run Falcon Benchmarks Directly Source: https://github.com/falconry/falcon/blob/master/CONTRIBUTING.md Alternatively, run falcon-bench directly after setting up a virtual environment and installing Falcon in development mode. This example uses pyenv. ```bash $ pyenv virtualenv 3.10.6 falcon-sandbox-310 $ pyenv shell falcon-sandbox-310 $ pip install -r requirements/bench $ pip install -e . $ falcon-bench ``` -------------------------------- ### Install and Run Gunicorn Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Commands to install Gunicorn, a production-ready WSGI server, and run the Falcon application. ```bash source .venv/bin/activate pip install gunicorn gunicorn --reload look.app ``` -------------------------------- ### Install MessagePack Package Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Install the msgpack-python package to enable MessagePack serialization. ```bash $ pip install msgpack-python ``` -------------------------------- ### Install Testing Dependencies Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Install fakeredis and pytest to set up your testing environment. ```bash $ pip install fakeredis pytest ``` -------------------------------- ### Install aiofiles for Async I/O Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Install the aiofiles library to handle asynchronous file operations, preventing blocking during I/O. ```default pip install aiofiles ``` -------------------------------- ### Install Uvicorn with Standard Dependencies Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md For CPython-based production deployments, install Uvicorn with optimized dependencies like uvloop and httptools for better performance. ```bash pip install uvicorn[standard] ``` -------------------------------- ### GET Image Request Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Example of retrieving an image using its specific URL via an HTTP GET request. ```bash $ http localhost:8000/images/dddff30e-d2a6-4b57-be6a-b985ee67fa87.png ``` -------------------------------- ### Set up Virtual Environment and Install Dependencies Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-websockets.md Initializes a project directory, creates a virtual environment, and installs Falcon and Uvicorn. This is a prerequisite for running the Falcon application. ```bash mkdir ws_tutorial cd ws_tutorial python3 -m venv .venv source .venv/bin/activate pip install falcon uvicorn ``` -------------------------------- ### Start NGINX Service Source: https://github.com/falconry/falcon/blob/master/docs/deploy/nginx-uwsgi.md This command starts or restarts the NGINX web server. Ensure NGINX is installed and configured correctly before running this command. ```sh $ sudo service start nginx ``` -------------------------------- ### GET Request for Thumbnail Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Example of retrieving a generated thumbnail via a GET request. Demonstrates the expected HTTP 200 OK response with image data. ```shell $ http localhost:8000/thumbnails/f2375273-8049-4b10-b17e-8851db9ac7af/115x115.jpeg HTTP/1.1 200 OK content-length: 2985 content-type: image/jpeg date: Tue, 24 Dec 2019 19:00:14 GMT server: uvicorn +----------------------------------------+ | NOTE: binary data not shown in terminal | +----------------------------------------+ ``` -------------------------------- ### Define a Resource with GET Method Source: https://github.com/falconry/falcon/blob/master/docs/user/quickstart.md Create a resource class to handle API endpoints. This example defines a 'ThingsResource' with an asynchronous 'on_get' method to handle GET requests. ```python class ThingsResource: def __init__(self, db): self.db = db self.logger = logging.getLogger('thingsapp.' + __name__) async def on_get(self, req, resp, user_id): marker = req.get_param('marker') or '' limit = req.get_param_as_int('limit') or 50 try: ``` -------------------------------- ### Handling Conditional GET with ETag Source: https://github.com/falconry/falcon/blob/master/docs/api/util.md An example on_get method demonstrating how to use falcon.ETag for conditional GET requests. It checks If-None-Match headers and sets the response ETag. ```default def on_get(self, req, resp): content_etag = self._get_content_etag() for etag in (req.if_none_match or []): if etag == '*' or etag == content_etag: resp.status = falcon.HTTP_304 return # -- snip -- resp.etag = content_etag resp.status = falcon.HTTP_200 ``` -------------------------------- ### Install Requests and Run Gunicorn Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md These commands are used to install the necessary `requests` package for the functional tests and to start the Falcon application using Gunicorn, making it accessible via HTTP. ```bash pip install requests ``` ```bash gunicorn 'look.app:get_app()' ``` -------------------------------- ### Define an Images Resource with GET Handler Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Implement a basic resource class with an `on_get` method to handle GET requests. This example demonstrates how to serialize a Python dictionary to JSON and set the response status. ```python import json import falcon class Resource: def on_get(self, req, resp): doc = { 'images': [ { 'href': '/images/1eaf6ef1-7f2d-4ecc-a8d5-6e8adba7cc0e.png' } ] } # Create a JSON representation of the resource resp.text = json.dumps(doc, ensure_ascii=False) # The following line can be omitted because 200 is the default # status returned by the framework, but it is included here to # illustrate how this may be overridden as needed. resp.status = falcon.HTTP_200 ``` -------------------------------- ### Advanced ASGI App Setup in Falcon Source: https://github.com/falconry/falcon/blob/master/README.rst Demonstrates setting up an ASGI application with middleware and adding routes. Includes custom error handling and proxying to external services. ```python class StorageError(Exception): # ... (implementation details omitted for brevity) @staticmethod def handle(ex, req, resp, params): # Custom error handling logic pass class SinkAdapter: # ... (implementation details omitted for brevity) async def __call__(self, req, resp, **kwargs): # Logic for proxying requests pass # The app instance is an ASGI callable app = falcon.asgi.App(middleware=[ # AuthMiddleware(), RequireJSON(), JSONTranslator(), ]) db = StorageEngine() things = ThingsResource(db) app.add_route('/{user_id}/things', things) # If a responder ever raises an instance of StorageError, pass control to # the given handler. app.add_error_handler(StorageError, StorageError.handle) # Proxy some things to another service; this example shows how you might # send parts of an API off to a legacy system that hasn't been upgraded # yet, or perhaps is a single cluster that all data centers have to share. sink = SinkAdapter() app.add_sink(sink, r'/search/(?Pddg|y)\Z') ``` -------------------------------- ### ExampleMiddleware Source: https://github.com/falconry/falcon/blob/master/docs/api/middleware.md An example class demonstrating the methods available for ASGI middleware in Falcon. ```APIDOC ## ExampleMiddleware ### Description An example class demonstrating the methods available for ASGI middleware in Falcon. ### Methods #### `process_startup(self, scope: dict[str, Any], event: dict[str, Any]) -> None` ##### Description Process the ASGI lifespan startup event. Invoked when the server is ready to start up and receive connections, but before it has started to do so. To halt startup processing and signal to the server that it should terminate, simply raise an exception and the framework will convert it to a "lifespan.startup.failed" event for the server. ##### Arguments - **scope** (dict) - The ASGI scope dictionary for the lifespan protocol. The lifespan scope exists for the duration of the event loop. - **event** (dict) - The ASGI event dictionary for the startup event. #### `process_shutdown(self, scope: dict[str, Any], event: dict[str, Any]) -> None` ##### Description Process the ASGI lifespan shutdown event. Invoked when the server has stopped accepting connections and closed all active connections. To halt shutdown processing and signal to the server that it should immediately terminate, simply raise an exception and the framework will convert it to a "lifespan.shutdown.failed" event for the server. ##### Arguments - **scope** (dict) - The ASGI scope dictionary for the lifespan protocol. The lifespan scope exists for the duration of the event loop. - **event** (dict) - The ASGI event dictionary for the shutdown event. #### `process_request(self, req: Request, resp: Response) -> None` ##### Description Process the request before routing it. Falcon routes each request based on `req.path`, so a request can be effectively re-routed by setting that attribute to a new value from within `process_request()`. ##### Arguments - **req** (Request) - Request object that will eventually be routed to an on_* responder method. - **resp** (Response) - Response object that will be routed to the on_* responder. #### `process_resource(self, req: Request, resp: Response, resource: object, params: dict[str, Any]) -> None` ##### Description Process the request after routing. This method is only called when the request matches a route to a resource. ##### Arguments - **req** (Request) - Request object that will be passed to the routed responder. - **resp** (Response) - Response object that will be passed to the responder. - **resource** (object) - Resource object to which the request was routed. - **params** (dict) - A dict-like object representing any additional params derived from the route's URI template fields, that will be passed to the resource's responder method as keyword arguments. #### `process_response(self, req: Request, resp: Response, resource: object, req_succeeded: bool) -> None` ##### Description Post-processing of the response (after routing). ##### Arguments - **req** (Request) - Request object. - **resp** (Response) - Response object. - **resource** (object) - Resource object to which the request was routed. May be None if no route was found for the request. - **req_succeeded** (bool) - True if no exceptions were raised while the framework processed and routed the request; otherwise False. #### `process_request_ws(self, req: Request, ws: WebSocket) -> None` ##### Description Process a WebSocket handshake request before routing it. Falcon routes each request based on `req.path`, so a request can be effectively re-routed by setting that attribute to a new value from within `process_request()`. ##### Arguments - **req** (Request) - Request object that will eventually be passed into an on_websocket() responder method. - **ws** (WebSocket) - The WebSocket object that will be passed into on_websocket() after routing. #### `process_resource_ws(self, req: Request, ws: WebSocket, resource: object, params: dict[str, Any]) -> None` ##### Description Process a WebSocket handshake request after routing. This method is only called when the request matches a route to a resource. ##### Arguments - **req** (Request) - Request object. - **ws** (WebSocket) - WebSocket object. - **resource** (object) - Resource object to which the request was routed. - **params** (dict) - A dict-like object representing any additional params derived from the route's URI template fields, that will be passed to the resource's responder method as keyword arguments. ``` -------------------------------- ### Build Documentation with Tox Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md Build Falcon's documentation from source using tox. Ensure tox is installed first. ```bash pip install tox && tox -e docs ``` -------------------------------- ### Retrieve Uploaded Image via HTTP GET Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Example of retrieving a specific image using httpie. The response content type is image/jpeg. ```http $ http localhost:8000/images/5cfd9fb6-259a-4c72-b8b0-5f4c35edcd3c.jpeg HTTP/1.1 200 OK content-type: image/jpeg date: Tue, 24 Dec 2019 17:34:53 GMT server: uvicorn transfer-encoding: chunked +-----------------------------------------+ | NOTE: binary data not shown in terminal | +-----------------------------------------+ ``` -------------------------------- ### Initial Image Collection GET Endpoint Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Sets up a static JSON response for listing images. This is a starting point before implementing dynamic filtering. ```python import io import os import re import uuid import mimetypes import falcon import json class Collection: def __init__(self, image_store): self._image_store = image_store def on_get(self, req, resp): # TODO: Modify this to return a list of href's based on # what images are actually available. doc = { 'images': [ { 'href': '/images/1eaf6ef1-7f2d-4ecc-a8d5-6e8adba7cc0e.png' } ] } resp.text = json.dumps(doc, ensure_ascii=False) resp.status = falcon.HTTP_200 def on_post(self, req, resp): name = self._image_store.save(req.stream, req.content_type) resp.status = falcon.HTTP_201 resp.location = '/images/' + name ``` -------------------------------- ### List All Images via HTTP GET Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Example of retrieving a list of all uploaded images using httpie. The response is a JSON array of image metadata. ```http $ http localhost:8000/images HTTP/1.1 200 OK content-length: 175 content-type: application/json date: Tue, 24 Dec 2019 17:36:31 GMT server: uvicorn [ { "id": "5cfd9fb6-259a-4c72-b8b0-5f4c35edcd3c", "image": "/images/5cfd9fb6-259a-4c72-b8b0-5f4c35edcd3c.jpeg", "modified": "Tue, 24 Dec 2019 17:32:19 GMT", "size": [ 462, 462 ] } ] ``` -------------------------------- ### Build Documentation with Tox Source: https://github.com/falconry/falcon/blob/master/CONTRIBUTING.md Run this tox job to build the documentation, including docstrings, before submitting a PR. It also shows commands to open the built HTML documentation on different operating systems. ```bash $ tox -e docs # OS X $ open docs/_build/html/index.html # Gnome $ gnome-open docs/_build/html/index.html # Generic X Windows $ xdg-open docs/_build/html/index.html ``` -------------------------------- ### Basic WSGI Responder Example Source: https://github.com/falconry/falcon/blob/master/docs/api/request_and_response_wsgi.md A simple WSGI responder class demonstrating how to handle a GET request and set a JSON response with a 200 status code. ```python import falcon class Resource: def on_get(self, req, resp): resp.media = {'message': 'Hello world!'} resp.status = falcon.HTTP_200 # -- snip -- app = falcon.App() app.add_route('/', Resource()) ``` -------------------------------- ### Create a basic Falcon ASGI application Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Instantiate a Falcon ASGI application. This is the entry point for your asynchronous web service. ```python import falcon.asgi app = falcon.asgi.App() ``` -------------------------------- ### WSGI Raw URL Path Example Response Source: https://github.com/falconry/falcon/blob/master/docs/user/recipes/raw-url-path.md Demonstrates the JSON response when a GET request with a percent-encoded URL is processed by the WSGI app with the RawPathComponent middleware. ```json { "url": "http://falconframework.org" } ``` -------------------------------- ### WSGI Application Setup and Routing Source: https://github.com/falconry/falcon/blob/master/README.rst Demonstrates how to configure a WSGI Falcon application with middleware, add routes, and set up error handlers. This is useful for setting up the core of a Falcon web service. ```python app = falcon.App( middleware=[ AuthMiddleware(), RequireJSON(), JSONTranslator(), ] ) db = StorageEngine() things = ThingsResource(db) app.add_route('/{user_id}/things', things) # If a responder ever raises an instance of StorageError, pass control to # the given handler. app.add_error_handler(StorageError, StorageError.handle) # Proxy some things to another service; this example shows how you might # send parts of an API off to a legacy system that hasn't been upgraded # yet, or perhaps is a single cluster that all data centers have to share. sink = SinkAdapter() app.add_sink(sink, r'/search/(?Pddg|y)\Z') # Useful for debugging problems in your API; works with pdb.set_trace(). You # can also use Gunicorn to host your app. Gunicorn can be configured to # auto-restart workers when it detects a code change, and it also works # with pdb. if __name__ == '__main__': httpd = simple_server.make_server('127.0.0.1', 8000, app) httpd.serve_forever() ``` -------------------------------- ### Testing Falcon WSGI Application Source: https://github.com/falconry/falcon/blob/master/README.rst Example command to test the Falcon WSGI application using httpie. This sends a GET request to the application with a custom authorization header. ```bash $ http localhost:8000/1/things authorization:custom-token ``` -------------------------------- ### Create Test Directory Structure Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial-asgi.md Create a 'tests' directory and an __init__.py file to make it a Python package. ```bash $ mkdir -p tests $ touch tests/__init__.py ``` -------------------------------- ### Create Falcon App Entry Point Source: https://github.com/falconry/falcon/blob/master/docs/user/tutorial.md Commands to create the application directory structure and the main application file. ```bash mkdir look touch look/__init__.py touch look/app.py ``` -------------------------------- ### uWSGI Operational Mode Output Source: https://github.com/falconry/falcon/blob/master/docs/deploy/nginx-uwsgi.md This is an example of the expected output when uWSGI starts successfully, indicating the operational mode and spawned worker processes. Monitor this output for any errors during startup. ```text *** Operational MODE: preforking+threaded *** ... *** uWSGI is running in multiple interpreter mode *** ... spawned uWSGI master process (pid: 91828) spawned uWSGI worker 1 (pid: 91866, cores: 2) spawned uWSGI worker 2 (pid: 91867, cores: 2) ``` -------------------------------- ### View Built Documentation on Linux Source: https://github.com/falconry/falcon/blob/master/README.rst Open the locally built Falcon documentation index page in your browser on Linux. ```bash $ xdg-open docs/_build/html/index.html ``` -------------------------------- ### ASGI Raw URL Path Example Response Source: https://github.com/falconry/falcon/blob/master/docs/user/recipes/raw-url-path.md Shows the JSON response for a GET request with a percent-encoded URL processed by the ASGI app with the RawPathComponent middleware, correctly handling the encoded path. ```json { "url": "http://falconframework.org/status" } ``` -------------------------------- ### Install ASGI Servers for Falcon Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md Install an ASGI server to run asynchronous Falcon ASGI applications. Uvicorn, Daphne, and Hypercorn are common options. ```bash pip install [uvicorn|daphne|hypercorn] ``` -------------------------------- ### Instantiate WSGI and ASGI Apps Source: https://github.com/falconry/falcon/blob/master/docs/api/app.md Instantiate the respective `App` class to create a callable WSGI or ASGI application. These can be hosted with any standard-compliant server. ```python import falcon import falcon.asgi wsgi_app = falcon.App() asgi_app = falcon.asgi.App() ``` -------------------------------- ### Install and Format Code with Ruff Source: https://github.com/falconry/falcon/blob/master/docs/community/contributing.md Install the ruff formatter and use it to format your code according to project standards. This is a prerequisite for submitting pull requests. ```bash $ pip install -U ruff $ ruff format ``` -------------------------------- ### Run Tests with Editable Install Source: https://github.com/falconry/falcon/blob/master/docs/user/install.md After an editable install, run pytest to manually test changes to the Falcon framework. Ensure test dependencies are installed first. ```bash cd falcon FALCON_DISABLE_CYTHON=Y pip install -e . pip install -r requirements/tests pytest tests ```