Python Falcon 简明教程
Python Falcon - App Class
此类是基于 Falcon 的 WSGI 应用程序的主要入口点。此类的实例提供了一个可调用的 WSGI 接口和一个路由引擎。
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()
此类的 init() 构造函数采用以下关键字参数 −
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.
-
request_type − Default value of this argument is falcon.Request class.
-
response_type − Default value of this argument is falcon.Response class.
为了使 App 对象可调用,其类有一个 call() 方法。
In order to make the App object callable, its class has a call() method.
__call__(self, env, start_response)
这是一个 WSGI 应用程序方法。WSGI 开发服务器或其他生产服务器(Waitress/Uvicorn)使用此对象启动服务器实例并侦听来自客户端的请求。
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.
App 类还定义了 add_route() 方法。
The App class also defines the add_route() method.
add_route(self, uri_template, resource)
此方法有助于将 URI 路径与其资源类中的对象相关联。传入请求按一组 URI 模板路由到资源。如果路径与给定路由的模板匹配,则该请求被传递到相关资源以进行处理。根据请求方法,将调用各自的应答器方法。
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
让我们向 on_post() 类中添加 HelloResource 应答器方法,并测试 GET 和 POST 请求的端点。
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
使用 Waitress 服务器运行应用程序,并使用 Curl 检查响应。对于 GET 请求的响应,使用以下命令 −
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
我们通过 POST 方法将一些数据发送到 /hello URL,如下所示 −
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
要将路由添加到静态文件目录,Falcon 具有 add_static_route() 方法。
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)
prefix 参数是要匹配此路由的路径前缀。directory 参数是要从中提供文件的文件目录。downloadable 参数设置为 True,如果您希望在响应中包含 ContentDisposition 头。 fallback_filename 默认情况下为无,但在请求的文件未找到时可以指定。
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.
add_error_handler() 方法用于为一个或多个异常类型注册处理程序。
The add_error_handler() method is used to register a handler for one or more exception types.
add_error_handler(self, exception, handler=None)
可异步调用 App 类具有相同的方法。它在 falcon.asgi 模块中定义。
The ASGI callable App class possesses the same methods. It is defined in falcon.asgi module.
import falcon.asgi
app=falcon.asgi.App()
请注意,ASGI 应用程序中资源类的响应器必须是 coroutines (使用 async 关键字定义),而不是正常方法。
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'
)