From 8220515e72fd6c6a7ad65438b4e9fba5d29a2891 Mon Sep 17 00:00:00 2001 From: Sean Parsons Date: Sun, 25 Dec 2016 18:01:26 -0500 Subject: [PATCH] Added token property to Request object & added test to confirm new functionality. --- sanic/request.py | 14 +++++++++++++- tests/test_requests.py | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/sanic/request.py b/sanic/request.py index 62d89781..fd52ba90 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -8,8 +8,9 @@ from sanic.exceptions import InvalidUsage from .log import log - DEFAULT_HTTP_CONTENT_TYPE = "application/octet-stream" + + # HTTP/1.1: https://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7.2.1 # > If the media type remains unknown, the recipient SHOULD treat it # > as type "application/octet-stream" @@ -72,6 +73,17 @@ class Request(dict): return self.parsed_json + @property + def token(self): + """ + Attempts to return the auth header token. + :return: token related to request + """ + auth_header = self.headers.get('Authorization', None) + if auth_header is not None: + return auth_header.split()[1] + return auth_header + @property def form(self): if self.parsed_form is None: diff --git a/tests/test_requests.py b/tests/test_requests.py index 5895e3d5..4e1fd1a5 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -112,6 +112,29 @@ def test_post_json(): assert response.text == 'OK' +def test_post_token(): + app = Sanic('test_post_token') + + @app.route('/') + async def handler(request): + return text('OK') + + payload = {'test': 'OK'} + + # uuid4 generated token. + token = 'a1d895e0-553a-421a-8e22-5ff8ecb48cbf' + + headers = { + 'content-type': 'application/json', + 'Authorization': 'Token {}'.format(token) + } + + request, response = sanic_endpoint_test(app, data=json_dumps(payload), headers=headers) + + assert request.token == token + assert response.text == 'OK' + + def test_post_form_urlencoded(): app = Sanic('test_post_form_urlencoded')