用于WSGI应用的灵活调度器
gargant.dispatch的Python项目详细描述
适用于WSGI的灵活调度程序。
基本用法
编写dispathing tree,并将wsgi应用程序注册到case
from wsgiref.simple_server import make_server from gargant.dispatch import Node, path_matching, make_wsgi_app from path.to.yours import wsgi_app tree = Node((path_matching(['']),), case=wsgi_app, name='first') app = make_wsgi_app(tree) httpd = make_server('', 8000, app) httpb.serve_forever()
当路径为“/”时,将调用已注册的应用程序(wsgi_app)。
节点
dispatch不仅仅用于创建wsgi应用程序。 它可以处理environ并根据需要返回一个值。
您可以对案例应用任何内容
节点类可以采用如下参数“children”: 没有匹配的子级,将匹配父级:>>> tree = Node((path_matching(['']),),
... case='dolls')
>>>
>>> node = tree({'PATH_INFO': '/'})
>>> node.case # 'dolls'
层次结构
>>> tree = Node((path_matching(['']),),
... case='dolls',
... children=(
... Node((path_matching['fifth']),
... case='shinku'),
... ))
>>>
>>> node = tree({'PATH_INFO': '/fifth'})
>>> node.case # 'shinku'
>>> node = tree({'PATH_INFO': '/'})
>>> node.case # 'dolls'
匹配
路径匹配只是匹配模式之一, 您也可以使用方法匹配:
>>> tree = Node((path_matching(['']), method_matching('get')), ... case='dolls', ... ) >>> >>> node = tree({'PATH_INFO': '/', ... 'REQUEST_METHOD': 'GET'}) >>> node.case # 'dolls'
方法模式返回接受environ并返回 一些价值观。 匹配返回的所有值都可以作为true处理。 节点将是“匹配”的句柄。
匹配返回的值将存储在 node.matched作为这些的列表。
url参数
使用此行为,路径匹配可以从url获取参数:
>>> tree = Node((path_matching(['']),), ... case='doll_list', ... children=( ... Node((path_matching(['{doll}']),), ... case='doll_detail', ... ), ... )) >>> >>> node = tree({'PATH_INFO': '/first'}) >>> node.case # 'doll_detail' >>> node.matched[0]['doll'] # 'first'
适配器
节点可以使用名为adapter\u factory的关键字arg。 它接受node.matched并返回一些您喜欢的可调用项:
>>> tree = Node((path_matching(['']),), ... case='dolls', ... children=( ... Node((path_matching(['fifth']),), ... case='shinku', ... adapter_factory=lambda matched: lambda x: x + ' kawaii' ... ), ... ), ... adapter_factory=lambda matched: lambda x: x + ' is' ... ) >>> >>> node = tree({'PATH_INFO': '/fifth'}) >>> node.case # 'shinku' >>> doll = 'shinku' >>> root_to_leaf = reversed(list(node)) # [dolls node, shinku node] >>> for node in root_to_leaf: ... doll = node.adapter(doll) ... >>> doll # 'shinku is kawaii'
在这种情况下,这些适配器工厂将返回简单的函数, 但是gargant.dispatch假设您返回适配器类。