English 中文(简体)
Python Falcon - ASGI
  • 时间:2024-09-17

Python Falcon - ASGI


Previous Page Next Page  

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

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

    Uvicorn

    Daphne

    Hypercorn

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

Hello World - ASGI

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


import falcon
import 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

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)

To run the apppcation, start the Uvicorn server from the command pne as follows −


uvicorn hellofalcon:app –reload

Output

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

ASGI Advertisements