Merge pull request #476 from seemethere/inject_app_into_request

Inject app into request object
This commit is contained in:
Eli Uriegas 2017-02-23 09:12:41 -06:00 committed by GitHub
commit d015d6b103
3 changed files with 25 additions and 2 deletions

View File

@ -360,6 +360,8 @@ class Sanic:
# Request Middleware
# -------------------------------------------- #
request.app = self
response = False
# The if improves speed. I don't know why
if self.request_middleware:

View File

@ -36,7 +36,7 @@ class RequestParameters(dict):
class Request(dict):
"""Properties of an HTTP request such as URL, headers, etc."""
__slots__ = (
'url', 'headers', 'version', 'method', '_cookies', 'transport',
'app', 'url', 'headers', 'version', 'method', '_cookies', 'transport',
'query_string', 'body',
'parsed_json', 'parsed_args', 'parsed_form', 'parsed_files',
'_ip',
@ -45,6 +45,7 @@ class Request(dict):
def __init__(self, url_bytes, headers, version, method, transport):
# TODO: Content-Encoding detection
url_parsed = parse_url(url_bytes)
self.app = None
self.url = url_parsed.path.decode('utf-8')
self.headers = headers
self.version = version

View File

@ -1,3 +1,5 @@
import random
from sanic import Sanic
from sanic.response import json
from ujson import loads
@ -21,3 +23,21 @@ def test_storage():
response_json = loads(response.text)
assert response_json['user'] == 'sanic'
assert response_json.get('sidekick') is None
def test_app_injection():
app = Sanic('test_app_injection')
expected = random.choice(range(0, 100))
@app.listener('after_server_start')
async def inject_data(app, loop):
app.injected = expected
@app.get('/')
async def handler(request):
return json({'injected': request.app.injected})
request, response = app.test_client.get('/')
response_json = loads(response.text)
assert response_json['injected'] == expected