Python Falcon 简明教程

Python Falcon - Uvicorn

Uvicorn 使用 uvloophttptools 库。它还提供对 HTTP/2 和 Websocket 的支持,而 WSGI 无法处理它们。 uvloop 类似于内置 asyncio 事件循环。 httptools 库处理 http 协议。

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 的 ASGI 兼容应用程序在 Uvicorn 服务器上使用以下命令启动:

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

Uvicorn hellofalcon:app – reload

--reload 选项启用调试模式,以便 app.py 中的任何更改都将自动反映,并且客户端浏览器上的显示将自动刷新。此外,可以使用以下命令行选项:

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.

Uvicorn 服务器也可以在程序内部启动,而不是通过上述命令行。要执行该操作,请导入 uvicorn 模块并调用 uvicorn.run() 方法,如下所示 −

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)

相应地更改 hellofalcon.py 代码,并从命令提示符执行相同操作。可以使用 curl 命令或在浏览器中验证结果,如前所述。

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.