Python Falcon - Uvicorn



Uvicorn uses uvloop and httptools libraries. It also provides support for HTTP/2 and WebSockets, which cannot be handled by WSGI. uvloop is similar to the built-in asyncio event loop. httptools library handles the http protocols.

Falcon's ASGI compliant application is launched on Uvicorn server with following command −

Uvicorn hellofalcon:app – reload

The --reload option enables the debug mode, so that any changes in app.py will be automatically reflected and the display on the client browser will be automatically refreshed. In addition, the following command-line options may be used −

--host TEXT Bind socket to this host. [default 127.0.0.1]
--port INTEGER Bind socket to this port. [default 8000]
--uds TEXT Bind to a UNIX domain socket.
--fd INTEGER Bind to socket from this file descriptor.
--reload Enable auto-reload.
--reload-dir PATH Set reload directories explicitly, default current working directory.
--reload-include TEXT Include files while watching. Includes '*.py' by default
--reload-exclude TEXT Exclude while watching for files.
--reload-delay FLOAT Delay between previous and next check default 0.25
--loop [auto|asyncio|uvloop] Event loop implementation. [default auto]
--http [auto|h11|httptools] HTTP protocol implementation. [default auto]
--interface auto|asgi|wsgi Select application interface. [default auto]
--env-file PATH Environment configuration file.
--log-config PATH Logging configuration file. Supported formats .ini, .json, .yaml.
--version Display the Uvicorn version and exit.
--app-dir TEXT Look for APP in the specified directory default current directory
--help Show this message and exit.

The Uvicorn server can also be launched from within the program instead of the above command line. To do that, import uvicorn module and call uvicorn.run() method as shown below −

import uvicorn
if __name__ == "__main__":
   uvicorn.run("hellofalcon:app", host="0.0.0.0", port=8000, reload=True)

Change the hellofalcon.py code accordingly, and execute the same from command prompt. The result can be verified by the curl command or in the browser as explained earlier.

Advertisements