>>> urls = url_map.bind_to_environ(env)
>>> urls.match()
('index', {})
>>> env = werkzeug.create_environ(path='/Galahad?favorite+color')
>>> urls = url_map.bind_to_environ(env)
>>> urls.match()
('ask', {'person': 'Galahad'})
>>> env = werkzeug.create_environ(path='/Lancelot')
>>> urls = url_map.bind_to_environ(env)
>>> urls.match()
('other', {'other': 'Lancelot'})
>>> env = werkzeug.test.create_environ(path='/shouldnt/match')
>>> urls = url_map.bind_to_environ(env)
>>> urls.match()
Traceback (most recent call last):
File "
File "[…path…]/werkzeug/werkzeug/routing.py", line 1569, in match
raise NotFound()
werkzeug.exceptions.NotFound: 404: Not Found
Вы соотнесли маршрут запроса с соответствующей конечной точкой. В следующем фрагменте кода продолжим рассматривать суть предыдущего примера:
@werkzeug.Request.application
def send_to_endpoint(request):
····urls = url_map.bind_to_environ(request)
····try:
········endpoint, kwargs = urls.match()
········if endpoint == 'index':
············response = werkzeug.Response("You got the index.")
········elif endpoint == 'ask':
············questions = dict(
················Galahad='What is your favorite color?',
················Robin='What is the capital of Assyria?',
················Arthur='What is the air-speed velocity
························of an unladen swallow?')
············response = werkzeug.Response(questions[kwargs['person']])
········else:
············response = werkzeug.Response("Other: {other}".format(**kwargs))
····except (KeyboardInterrupt, SystemExit):
········raise
····except:
········response = werkzeug.Response(
········'You may not have gone where you intended to go,\n'
········'but I think you have ended up where you needed to be.',
········status=404
········)
····return response
Для того чтобы протестировать этот фрагмент, снова используйте класс werkzeug.Client:
>>> client = werkzeug.Client(send_to_endpoint, response_wrapper=werkzeug.Response)
>>> print(client.get("/"). data.decode())
You got the index.
>>>
>>> print(client.get("Arthur"). data.decode())
What is the air-speed velocity of an unladen swallow?
>>>
>>> print(client.get("42"). data.decode())
Other: 42
>>>
>>> print(client.get("time/lunchtime"). data.decode()) # no match
You may not have gone where you intended to go,
but I think you have ended up where you needed to be.