English 中文(简体)
Python Falcon - Resource Class
  • 时间:2024-11-05

Python Falcon - Resource Class


Previous Page Next Page  

Falcon s design borrows several key concepts from the REST architectural style. REST stands for Relational State Transfer. REST defines how the architecture of web apppcations should behave.

REST is a resource-based architecture. Here, everything that the REST server hosts, be it a file, an image or row in a table of a database, is treated as a resource, which may have many representations. The REST API provides a controlled access to these resources so that the cpent can retrieve and modify them.

A resource with the server should have only one uniform resource identifier (URI). It only identifies the resource; it does not specify what action to take on that resource. Instead, users choose from a set of standard methods. HTTP verb or method to be used for the operation on the resources. The POST, GET, PUT and DELETE methods perform CREATE, READ, UPDATE and DELETE operations respectively.

Falcon uses normal Python classes to represent resources. Such a class acts as a controller in your apppcation. It converts an incoming request into one or more internal actions, and then compose a response back to the cpent based on the results of those actions.

Python Falcon Resource

Each resource class defines various "responder" methods, one for each HTTP method the resource allows. Responder names start with "on_" and are named according to which HTTP method they handle, as in on_get(), on_post(), on_put(), etc.

In the hellofalcon.py example code used above, HelloResource (the resource class) has an on_get() responder method. Responders must always define at least two arguments to receive Request and Response objects.


import falcon
class HelloResource:
   def on_get(self, req, resp):
      """Handles GET requests"""
      resp.status = falcon.HTTP_200
      resp.content_type = falcon.MEDIA_TEXT
      resp.text = (
          Hello World 
      )

For ASGI apps, the responder must be a coroutine function, i.e. must be defined with async keyword.


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 
      )

The Request object represents the incoming HTTP request. Request headers, query string parameters, and other metadata associated with the request can be accessed through this object.

The Response object represents the apppcation s HTTP response to the request. Properties and methods of this object set status, header and body data. It also exposes a dict-pke context property for passing arbitrary data to hooks and other middleware methods.

Note that HelloResource in the above example is just a normal Python class. It can have any name; however, the convention is to name it as xxxResource.

Advertisements