Python Falcon - App Class



This class is the main entry point into a Falcon-based WSGI app. An instance of this class provides a callable WSGI interface and a routing engine.

import falcon
app = falcon.App()

The __init__() constructor of this class takes the following keyword arguments −

  • media_type − media type to use when initializing RequestOptions and ResponseOptions. Falcon allows for easy and customizable internet media type handling. By default, Falcon only enables handlers for JSON and HTML (URL-encoded and multipart) forms.

  • Other media types supported by Falcon are represented by the following constants −

    • falcon.MEDIA_JSON

    • falcon.MEDIA_MSGPACK

    • falcon.MEDIA_MULTIPART

    • falcon.MEDIA_URLENCODED

    • falcon.MEDIA_YAML

    • falcon.MEDIA_XML

    • falcon.MEDIA_HTML

    • falcon.MEDIA_JS

    • falcon.MEDIA_TEXT

    • falcon.MEDIA_JPEG

    • falcon.MEDIA_PNG

    • falcon.MEDIA_GIF

  • request_type − Default value of this argument is falcon.Request class.

  • response_type − Default value of this argument is falcon.Response class.

In order to make the App object callable, its class has a __call__() method.

__call__(self, env, start_response)

This is a WSGI app method. The WSGI development server or other production servers (Waitress/Uvicorn) use this object to launch the server instance and listen to the requests from the client.

The App class also defines the add_route() method.

add_route(self, uri_template, resource)

This method helps in associating a URI path with an object of resource class. Incoming requests are routed to resources based on a set of URI templates. If the path matches the template for a given route, the request is then passed on to the associated resource for processing. Depending on the request method, the respective responder methods are called.

Example

Let us add on_post() responder method to HelloResource class and test the endpoints for GET as well as POST requests.

from waitress import serve
import falcon
import json
class HelloResource:
   def on_get(self, req, resp):
      resp.status = falcon.HTTP_200
      resp.content_type = falcon.MEDIA_TEXT
      resp.text = (
         'Hello World'
      )
   def on_post(self, req, resp):
      data=req.media
      nm=data['name']
      resp.status = falcon.HTTP_200
      resp.content_type = falcon.MEDIA_TEXT 
      resp.text = (
         'Hello '+nm
      )
app = falcon.App()
hello = HelloResource()
app.add_route('/hello', hello)
if __name__ == '__main__':
   serve(app, host='0.0.0.0', port=8000)

Output

Run the application using Waitress server and check the responses using Curl. For response to GET request, using following command −

C:\Users\User>curl localhost:8000/hello
Hello World

We send some data to the /hello URL by POST method as follows −

C:\Users\User>curl -i -H "Content-Type:application/json" -X
POST -d "{"""name""":"""John"""}" http://localhost:8000/hello
HTTP/1.1 200 OK
Content-Length: 10
Content-Type: text/plain; charset=utf-8
Date: Sun, 17 Apr 2022 07:06:20 GMT
Server: waitress
Hello John

To add a route to a directory of static files, Falcon has add_static_route() method.

add_static_route(self, prefix, directory, downloadable=False,
fallback_filename=None)

The prefix argument is the path prefix to match for this route. The directory argument is the source directory from which to serve files. The downloadable argument is set to True if you want to include a ContentDisposition header in the response. The fallback_filename is by default None but can be specified when the requested file is not found.

The add_error_handler() method is used to register a handler for one or more exception types.

add_error_handler(self, exception, handler=None)

The ASGI callable App class possesses the same methods. It is defined in falcon.asgi module.

import falcon.asgi
app=falcon.asgi.App()

Note that the responders of the resource class in an ASGI application must be coroutines (defined with async keyword) instead of normal methods.

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'
      )
Advertisements