tornado.routing — Basic routing implementation

Flexible routing implementation.

Tornado使用Router类实现将HTTP请求路由到适当的处理程序. tornado.web.Application类是Router实现,可以直接使用,或者可以使用此模块中的类来提高灵活性. RuleRouter类可以比Application匹配更多的条件,或者可以将Router接口子类化以实现最大程度的自定义.

Router接口扩展了HTTPServerConnectionDelegate以提供其他路由功能. 这也意味着任何Router实现都可以直接用作HTTPServer构造函数的request_callback .

Router子类必须实现find_handler方法,以提供合适的HTTPMessageDelegate实例来处理请求:

class CustomRouter(Router):
    def find_handler(self, request, **kwargs):
        # some routing logic providing a suitable HTTPMessageDelegate instance
        return MessageDelegate(request.connection)

class MessageDelegate(HTTPMessageDelegate):
    def __init__(self, connection):
        self.connection = connection

    def finish(self):
        self.connection.write_headers(
            ResponseStartLine("HTTP/1.1", 200, "OK"),
            HTTPHeaders({"Content-Length": "2"}),
            b"OK")
        self.connection.finish()

router = CustomRouter()
server = HTTPServer(router)

Router实现的主要职责是提供从请求到将处理此请求的HTTPMessageDelegate实例的映射. 在上面的示例中,我们可以看到即使不实例化Application也可以进行路由.

为了路由到RequestHandler实现,我们需要一个Application实例. get_handler_delegate提供了一种为给定请求和RequestHandler创建HTTPMessageDelegate的便捷方法.

这是一个简单的示例,说明如何通过HTTP方法路由到RequestHandler子类:

resources = {}

class GetResource(RequestHandler):
    def get(self, path):
        if path not in resources:
            raise HTTPError(404)

        self.finish(resources[path])

class PostResource(RequestHandler):
    def post(self, path):
        resources[path] = self.request.body

class HTTPMethodRouter(Router):
    def __init__(self, app):
        self.app = app

    def find_handler(self, request, **kwargs):
        handler = GetResource if request.method == "GET" else PostResource
        return self.app.get_handler_delegate(request, handler, path_args=[request.path])

router = HTTPMethodRouter(Application())
server = HTTPServer(router)

ReversibleRouter接口增加了区分路由并使用路由名称和其他参数将它们反向转换为原始url的功能. Application本身就是ReversibleRouter类的实现.

RuleRouterReversibleRuleRouterRouterReversibleRouter接口的实现,可用于创建基于规则的路由配置.

规则是Rule类的实例. 它们包含Matcher ,该Matcher提供用于确定规则是否与特定请求和目标匹配的逻辑,可以是以下目标之一.

  1. HTTPServerConnectionDelegate的实例:

router = RuleRouter([
    Rule(PathMatches("/handler"), ConnectionDelegate()),
    # ... more rules
])

class ConnectionDelegate(HTTPServerConnectionDelegate):
    def start_request(self, server_conn, request_conn):
        return MessageDelegate(request_conn)
  1. 接受HTTPServerRequest类型的单个参数的可调用对象:

router = RuleRouter([
    Rule(PathMatches("/callable"), request_callable)
])

def request_callable(request):
    request.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
    request.finish()
  1. Another Router instance:

router = RuleRouter([
    Rule(PathMatches("/router.*"), CustomRouter())
])

当然可以使用嵌套的RuleRouterApplication

router = RuleRouter([
    Rule(HostMatches("example.com"), RuleRouter([
        Rule(PathMatches("/app1/.*"), Application([(r"/app1/handler", Handler)]))),
    ]))
])

server = HTTPServer(router)

In the example below RuleRouter is used to route between applications:

app1 = Application([
    (r"/app1/handler", Handler1),
    # other handlers ...
])

app2 = Application([
    (r"/app2/handler", Handler2),
    # other handlers ...
])

router = RuleRouter([
    Rule(PathMatches("/app1.*"), app1),
    Rule(PathMatches("/app2.*"), app2)
])

server = HTTPServer(router)

有关应用程序级路由的更多信息,请参阅Application文档.

4.5版的新功能.

class tornado.routing.Router[source]

抽象路由器接口.

find_handler(request: tornado.httputil.HTTPServerRequest, **kwargs) → Optional[tornado.httputil.HTTPMessageDelegate][source]

必须实现以返回可以为请求提供服务的HTTPMessageDelegate的适当实例. 路由实现可能会传递额外的kwarg,以扩展路由逻辑.

Parameters
Returns

an instance of HTTPMessageDelegate that will be used to process the request.

class tornado.routing.ReversibleRouter[source]

路由器的抽象路由器接口,可以处理命名的路由并支持将其反向转换为原始URL.

reverse_url(name: str, *args) → Optional[str][source]

返回给定路由名称和参数的url字符串;如果找不到匹配项,则返回None .

Parameters
  • namestr )–路由名称.

  • args –网​​址参数.

Returns

给定路由名称的参数化url字符串(或None ).

class tornado.routing.RuleRouter(rules: List[Union[Rule, List[Any], Tuple[Union[str, Matcher], Any], Tuple[Union[str, Matcher], Any, Dict[str, Any]], Tuple[Union[str, Matcher], Any, Dict[str, Any], str]]] = None)[source]

基于规则的路由器实现.

从规则的有序列表构造路由器:

RuleRouter([
    Rule(PathMatches("/handler"), Target),
    # ... more rules
])

您还可以省略显式的Rule构造函数,并使用参数元组:

RuleRouter([
    (PathMatches("/handler"), Target),
])

PathMatches是默认的匹配器,因此可以简化以上示例:

RuleRouter([
    ("/handler", Target),
])

在上面的示例中, Target可以是嵌套的Router实例, HTTPServerConnectionDelegate的实例或接受请求参数的旧式可调用对象.

Parameters

rulesRule实例或Rule构造函数参数元组的列表.

add_rules(rules: List[Union[Rule, List[Any], Tuple[Union[str, Matcher], Any], Tuple[Union[str, Matcher], Any, Dict[str, Any]], Tuple[Union[str, Matcher], Any, Dict[str, Any], str]]]) → None[source]

将新规则附加到路由器.

Parameters

rules – Rule实例(或传递给Rule构造函数的参数元组)的列表.

process_rule(rule: tornado.routing.Rule) → tornado.routing.Rule[source]

重写此方法可对每个规则进行额外的预处理.

Parameters

规则Rule )–要处理的规则.

Returns

相同或已修改的Rule实例.

get_target_delegate(target: Any, request: tornado.httputil.HTTPServerRequest, **target_params) → Optional[tornado.httputil.HTTPMessageDelegate][source]

返回规则目标的HTTPMessageDelegate实例. 此方法由find_handler ,可以扩展为提供其他目标类型.

Parameters
class tornado.routing.ReversibleRuleRouter(rules: List[Union[Rule, List[Any], Tuple[Union[str, Matcher], Any], Tuple[Union[str, Matcher], Any, Dict[str, Any]], Tuple[Union[str, Matcher], Any, Dict[str, Any], str]]] = None)[source]

一个基于规则的路由器,可实现reverse_url方法.

添加到此路由器的每个规则可能具有可用于重构原始uri的name属性. 实际的重建在规则的匹配器中进行(请参阅Matcher.reverse ).

class tornado.routing.Rule(matcher: tornado.routing.Matcher, target: Any, target_kwargs: Dict[str, Any] = None, name: str = None)[source]

路由规则.

构造一个Rule实例.

Parameters
class tornado.routing.Matcher[source]

表示请求功能的匹配器.

match(request: tornado.httputil.HTTPServerRequest) → Optional[Dict[str, Any]][source]

将当前实例与请求进行匹配.

Parameters

requesthttputil.HTTPServerRequest )–当前的HTTP请求

Returns

传递给目标处理程序的参数的命令(例如,可以传递handler_kwargspath_argspath_kwargs以进行正确的RequestHandler实例化). 空dict是有效(且通用)的返回值,用于在不使用传递参数功能时指示匹配. None必须返回,表明没有匹配.

reverse(*args) → Optional[str][source]

从匹配器实例和其他参数重构完整的url.

class tornado.routing.AnyMatches[source]

匹配任何请求.

class tornado.routing.HostMatches(host_pattern: Union[str, Pattern])[source]

匹配来自host_pattern正则表达式指定的主机的请求.

class tornado.routing.DefaultHostMatches(application: Any, host_pattern: Pattern)[source]

匹配来自主机的等于应用程序default_host的请求. 如果存在X-Real-Ip标头,则始终不返回匹配项.

class tornado.routing.PathMatches(path_pattern: Union[str, Pattern])[source]

将请求与path_pattern正则表达式指定的路径匹配.

class tornado.routing.URLSpec(pattern: Union[str, Pattern], handler: Any, kwargs: Dict[str, Any] = None, name: str = None)[source]

指定URL和处理程序之间的映射.

Parameters:

  • pattern :要匹配的正则表达式. 正则表达式中的任何捕获组都将作为参数传递到处理程序的get / post / etc方法中(如果命名,则通过关键字;如果未命名,则通过位置.已命名和未命名的捕获组不能在同一规则中混合使用).

  • handler :要调用的RequestHandler子类.

  • kwargs (optional): A dictionary of additional arguments to be passed to the handler’s constructor.

  • name (可选):此处理程序的名称. 由reverse_url .