Apply middlewares only when there's request handler

This commit is contained in:
Hyunjun Kim 2017-01-11 17:23:12 +09:00
parent 2aa7579884
commit f7fab4c7be
2 changed files with 27 additions and 9 deletions

View File

@ -179,6 +179,13 @@ class Sanic:
try:
request_started.send(request)
# Fetch handler from router
handler, args, kwargs = self.router.get(request)
if handler is None:
raise ServerError(
("'None' was returned while requesting a "
"handler from the router"))
# -------------------------------------------- #
# Request Middleware
# -------------------------------------------- #
@ -196,17 +203,9 @@ class Sanic:
# No middleware results
if not response:
# -------------------------------------------- #
# Execute Handler
# Execute Response Handler
# -------------------------------------------- #
# Fetch handler from router
handler, args, kwargs = self.router.get(request)
if handler is None:
raise ServerError(
("'None' was returned while requesting a "
"handler from the router"))
# Run response handler
response = handler(request, *args, **kwargs)
if isawaitable(response):
response = await response

View File

@ -71,6 +71,25 @@ def test_middleware_override_request():
assert response.text == 'OK'
def test_middleware_override_scope():
app = Sanic('test_middleware_override_scope')
@app.middleware
async def validate_request(request):
if not request.headers.get('X-REQUIRED-HEADER'):
return text('X-REQUIRED-HEADER is missing.', status=412)
@app.route('/')
async def handler(request):
return text('OK')
response = sanic_endpoint_test(app, uri='/', gather_request=False)
assert response.status == 412
response = sanic_endpoint_test(app, uri='/nothing/', gather_request=False)
assert response.status == 404
def test_middleware_override_response():
app = Sanic('test_middleware_override_response')