Python Falcon 简明教程
Python Falcon - Routing
Falcon 采用 RESTful 架构样式。因此,它使用基于资源的路由。资源类负责通过响应器处理 HTTP 方法,响应器本质上是类方法,名称以 on_ 开头,以小写 HTTP 方法名称结尾(例如, on_get(), on_patch(), on_delete(), 等)。Falcon 应用程序对象的 add_route() 方法将其路由器与其资源类的实例相关联。
Falcon adopts RESTful architectural style. Hence it uses resource based routing. A resource class is responsible for handling the HTTP methods by the responders, which are essentially class methods with a name that starts with on_ and ends in the lowercased HTTP method name (e.g., on_get(), on_patch(), on_delete(), etc.). The add_route() method of the Falcon Application object associates its router with an instance of resource class.
在上面使用的 Hellofalcon.py 示例中, on_get() 和 on_post() 响应器在客户端通过 GET 和 POST 方法请求 /hello 路由时被调用。
In the Hellofalcon.py example used above, the on_get() and on_post() responders are invoked when the /hello route is requested by the client by GET and POST method respectively.
如果没有路由与请求相匹配,则会引发 HTTPRouteNotFound 的实例。另一方面,如果匹配到路由,但资源并未实现对所请求 HTTP 方法的响应器,则默认响应器将引发 HTTPMethodNotAllowed 的实例。
If no route matches the request, an instance of HTTPRouteNotFound is raised. On the other hand, if a route is matched but the resource does not implement a responder for the requested HTTP method, a default responder raises an instance of HTTPMethodNotAllowed.
Field Converters
Falcon 的路由机制允许 URL 向响应器传递参数。URL 包含三个部分:协议(例如 http:// 或 https:// ),后跟 IP 地址或主机名。URL 的其余部分在主机名之后的第一个 / 之后称为路径或端点。要传递的参数在端点之后。
Falcon’s routing mechanism allows URLs to pass parameters to the responders. The URL comprises of three parts: The protocol (such as http:// or https://) followed by the IP address or hostname. The remaining part of the URL after first / after the hostname is called as the path or endpoint. Parameters to be passed are after the endpoint.

它充当资源标识符,例如唯一 ID 或主键。参数名用大括号括起来。路径参数的值除了请求和响应之外,还会进入在响应器方法中定义的参数。
This acts as a resource identifier such as a unique ID or primary key. The parameter names are enclosed in curly brackets. Value of a path parameter goes to the argument defined in the responder method in addition to request and response.
在以下示例中,路由器将资源类对象与其由端点之后的参数组成的 URL 相关联。
In the following example, the router associates the resource class object with a URL consisting of a parameter after the endpoint.
from waitress import serve
import falcon
import json
class HelloResource:
def on_get(self, req, resp, nm):
"""Handles GET requests"""
resp.status = falcon.HTTP_200
resp.content_type = falcon.MEDIA_TEXT
resp.text = (
'Hello '+nm
)
app = falcon.App()
hello = HelloResource()
app.add_route('/hello/{nm}', hello)
if __name__ == '__main__':
serve(app, host='0.0.0.0', port=8000)
我们可以看到, on_get() 响应器方法有一个额外的参数 nm 用于接受从 URL 路由中解析的数据。让我们使用 HTTPie 工具测试 http://localhost:8000/hello/Priya 。
We can see that the on_get() responder method has an additional parameter nm to accept the data parsed from the URL route. Let us test http://localhost:8000/hello/Priya with HTTPie tool.
>http GET localhost:8000/hello/Priya
HTTP/1.1 200 OK
Content-Length: 11
Content-Type: text/plain; charset=utf-8
Date: Mon, 18 Apr 2022 12:27:35 GMT
Server: waitress
Hello Priya
路径参数被解析为的默认数据类型是 str (即字符串)。然而,Falcon 的路由引擎有以下 built-in field converters ,可以使用它们将它们读取到其他数据类型中。
The default data type to which the path parameters are parsed to is str (i.e. string). However, Falcon’s router engine has the following built-in field converters using which they can be read into other data types as well.
-
IntConverter − This class is defined in falcon.routing module. The constructor uses the following arguments −
IntConverter(num_digits=None, min=None, max=None)
app.add_route('/student/{rollno:int(1,1,100}', StudentResource())
-
UUIDConverter − This class in the falcon.routing module gives converts a string of 32 hexadecimal digits into a UUID (Universal Unique Identifier).
-
DateTimeConverter − Converts the parameter string to a datetime variable. The parameter must be a string in any format recognized by strptime() function, the default being '%Y-%m-%dT%H:%M:%SZ'.
格式字符串使用以下格式代码 −
Format string uses the following format codes −
%a |
Abbreviated weekday name |
Sun, Mon |
%A |
Full weekday name |
Sunday, Monday |
%d |
Day of the month as a zero-padded decimal |
01, 02 |
%-d |
day of the month as decimal number |
1, 2.. |
%b |
Abbreviated month name |
Jan, Feb |
%m |
month as a zero padded decimal number |
01, 02 |
%B |
Full month name |
January, February |
%-y |
year without century as a decimal number |
0, 99 |
%Y |
year with century as a decimal number |
2000, 1999 |
%H |
hour(24 hour clock) as a zero padded decimal number |
01, 23 |
%p |
locale’s AM or PM |
AM, PM |
%-M |
Minute as a decimal number |
1, 59 |
%-S |
Second as a decimal number |
1, 59 |
在以下示例中, add_route() 函数将一个 URL 与带有两个参数的 Resource 对象关联在一起。默认情况下,第一个参数 nm 为字符串。第二个参数 age 使用 IntConverter 。
In the following example, the add_route() function associates a URL with two parameters with the Resource object. First parameter nm is a string by default. The second parameter age uses IntConverter.
from waitress import serve
import falcon
import json
class HelloResource:
def on_get(self, req, resp, nm,age):
"""Handles GET requests"""
retvalue={"name":nm, "age":age}
resp.body=json.dumps(retvalue)
resp.status = falcon.HTTP_200
resp.content_type = falcon.MEDIA_JSON
app = falcon.App()
hello = HelloResource()
app.add_route('/hello/{nm}/{age:int}', hello)
if __name__ == '__main__':
serve(app, host='0.0.0.0', port=8000)
请注意, on_get() 响应程序使用路径参数形成 dict 对象 - retvalue 。然后,将它的 JSON 表示分配给响应正文的值,并返回给客户端。如前所述,JSON 是 Falcon 响应对象的默认内容类型。
Note that the on_get() responder uses the path parameters to form a dict object – retvalue. Its JSON representation is then assigned as the value of response body and returned to the client. As mentioned earlier, JSON is the default content type of Falcon’s response object.
启动 Waitress 服务器,并使用 HTTPie 帮助检查 URL http://localhost:8000/hello/Priya/21 的响应。
Start the Waitress server and check the response for the URL http://localhost:8000/hello/Priya/21 with the help of HTTPie.
http GET localhost:8000/hello/Priya/21
HTTP/1.1 200 OK
Content-Length: 28
Content-Type: application/json
Date: Fri, 22 Apr 2022 14:22:47 GMT
Server: waitress {
"age": 21,
"name": "Priya"
}
你还可以使用浏览器中查看响应,如下所示 −
You can also check the response in a browser as follows −
