Python Falcon 简明教程

Python Falcon - ASGI

ASGI 代表 Asynchronous Server Gateway Interface (根据其官方文档,它是 WSGI 的精神继承者),它为 Python Web 服务器、应用程序和框架增加了异步功能。

ASGI stands for Asynchronous Server Gateway Interface (as per its official documentation, it is a spiritual successor to WSGI), it adds the async capabilities to Python web servers, applications and frameworks.

要运行异步 web 应用程序,我们需要一个 ASGI 应用程序服务器。常用的选择包括 −

For running an async web application, we’ll need an ASGI application server. Popular choices include −

  1. Uvicorn

  2. Daphne

  3. Hypercorn

在本教程中,我们将在 async 示例中使用 Uvicorn 服务器。

We shall use Uvicorn server for async examples in this tutorial.

Hello World - ASGI

Falcon 的 ASGI 相关功能在 falcon.asgi 模块中可用。因此,我们需要在开头将其导入。

The ASGI related functionality of Falcon is available in the falcon.asgi module. Hence, we need to import it in the beginning.

import falcon
import falcon.asgi

虽然资源类与上一个示例中相同,但必须使用 async 关键字声明 on_get() 方法。我们必须获取 Falcon 的 ASGI 应用程序的实例。

While the resource class remains the same as in the previous example, the on_get() method must be declared with async keyword. we have to obtain the instance of Falson’s ASGI app.

app = falcon.asgi.App()

Example

因此,针对 ASGI 的 hellofalcon.py 如下所示:

Hence, the hellofalcon.py for ASGI will be as follows −

import falcon
import falcon.asgi
class HelloResource:
   async def on_get(self, req, resp):
      """Handles GET requests"""
      resp.status = falcon.HTTP_200
      resp.content_type = falcon.MEDIA_TEXT
      resp.text = (
         'Hello World'
      )
app = falcon.asgi.App()
hello = HelloResource()
app.add_route('/hello', hello)

要运行该应用程序,请从命令行启动 Uvicorn 服务器,如下所示:

To run the application, start the Uvicorn server from the command line as follows −

uvicorn hellofalcon:app –reload

Output

打开浏览器并访问 http://localhost:/8000/hello 。您将在浏览器窗口中看到响应。

Open the browser and visit http://localhost:/8000/hello. You will see the response in the browser window.

asgi