Merge pull request #732 from jrocketfingers/feature/explicit-register-middleware
Extract register_middleware into a method.
This commit is contained in:
commit
49631542ce
17
sanic/app.py
17
sanic/app.py
|
@ -277,24 +277,25 @@ class Sanic:
|
||||||
|
|
||||||
return response
|
return response
|
||||||
|
|
||||||
|
def register_middleware(self, middleware, attach_to='request'):
|
||||||
|
if attach_to == 'request':
|
||||||
|
self.request_middleware.append(middleware)
|
||||||
|
if attach_to == 'response':
|
||||||
|
self.response_middleware.appendleft(middleware)
|
||||||
|
return middleware
|
||||||
|
|
||||||
# Decorator
|
# Decorator
|
||||||
def middleware(self, middleware_or_request):
|
def middleware(self, middleware_or_request):
|
||||||
"""Decorate and register middleware to be called before a request.
|
"""Decorate and register middleware to be called before a request.
|
||||||
Can either be called as @app.middleware or @app.middleware('request')
|
Can either be called as @app.middleware or @app.middleware('request')
|
||||||
"""
|
"""
|
||||||
def register_middleware(middleware, attach_to='request'):
|
|
||||||
if attach_to == 'request':
|
|
||||||
self.request_middleware.append(middleware)
|
|
||||||
if attach_to == 'response':
|
|
||||||
self.response_middleware.appendleft(middleware)
|
|
||||||
return middleware
|
|
||||||
|
|
||||||
# Detect which way this was called, @middleware or @middleware('AT')
|
# Detect which way this was called, @middleware or @middleware('AT')
|
||||||
if callable(middleware_or_request):
|
if callable(middleware_or_request):
|
||||||
return register_middleware(middleware_or_request)
|
return self.register_middleware(middleware_or_request)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return partial(register_middleware,
|
return partial(self.register_middleware,
|
||||||
attach_to=middleware_or_request)
|
attach_to=middleware_or_request)
|
||||||
|
|
||||||
# Static Files
|
# Static Files
|
||||||
|
|
|
@ -65,10 +65,11 @@ class Blueprint:
|
||||||
# Middleware
|
# Middleware
|
||||||
for future in self.middlewares:
|
for future in self.middlewares:
|
||||||
if future.args or future.kwargs:
|
if future.args or future.kwargs:
|
||||||
app.middleware(*future.args,
|
app.register_middleware(future.middleware,
|
||||||
**future.kwargs)(future.middleware)
|
*future.args,
|
||||||
|
**future.kwargs)
|
||||||
else:
|
else:
|
||||||
app.middleware(future.middleware)
|
app.register_middleware(future.middleware)
|
||||||
|
|
||||||
# Exceptions
|
# Exceptions
|
||||||
for future in self.exceptions:
|
for future in self.exceptions:
|
||||||
|
|
Loading…
Reference in New Issue
Block a user