From 75f2180cb176c7095b67f1a78f49866eb21577ed Mon Sep 17 00:00:00 2001 From: Raphael Deem Date: Mon, 16 Oct 2017 22:40:21 -0700 Subject: [PATCH] add handler name to request as endpoint --- docs/sanic/request_data.md | 16 ++++++++++++++++ sanic/app.py | 2 ++ sanic/request.py | 4 +++- tests/test_requests.py | 11 +++++++++++ 4 files changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/sanic/request_data.md b/docs/sanic/request_data.md index e778faf6..5423aa13 100644 --- a/docs/sanic/request_data.md +++ b/docs/sanic/request_data.md @@ -120,3 +120,19 @@ args.get('titles') # => 'Post 1' args.getlist('titles') # => ['Post 1', 'Post 2'] ``` + +## Accessing the handler name with the request.endpoint attribute + +The `request.endpoint` attribute holds the handler's name. For instance, the below +route will return "hello". + +```python +from sanic.response import text +from sanic import Sanic + +app = Sanic() + +@app.get("/") +def hello(request): + return text(request.endpoint) +``` diff --git a/sanic/app.py b/sanic/app.py index 8f70b6e7..8f621599 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -247,6 +247,7 @@ class Sanic: def response(handler): async def websocket_handler(request, *args, **kwargs): request.app = self + request.endpoint = handler.__name__ try: protocol = request.transport.get_protocol() except AttributeError: @@ -540,6 +541,7 @@ class Sanic: # Fetch handler from router handler, args, kwargs, uri = self.router.get(request) + request.endpoint = handler.__name__ request.uri_template = uri if handler is None: raise ServerError( diff --git a/sanic/request.py b/sanic/request.py index 26f19baf..2893a5b7 100644 --- a/sanic/request.py +++ b/sanic/request.py @@ -46,7 +46,8 @@ class Request(dict): __slots__ = ( 'app', 'headers', 'version', 'method', '_cookies', 'transport', 'body', 'parsed_json', 'parsed_args', 'parsed_form', 'parsed_files', - '_ip', '_parsed_url', 'uri_template', 'stream', '_remote_addr' + '_ip', '_parsed_url', 'uri_template', 'stream', '_remote_addr', + 'endpoint', ) def __init__(self, url_bytes, headers, version, method, transport): @@ -68,6 +69,7 @@ class Request(dict): self.uri_template = None self._cookies = None self.stream = None + self.endpoint = None def __repr__(self): if self.method is None or not self.path: diff --git a/tests/test_requests.py b/tests/test_requests.py index f0696c7f..1f98673d 100644 --- a/tests/test_requests.py +++ b/tests/test_requests.py @@ -369,3 +369,14 @@ def test_url_attributes_with_ssl(path, query, expected_url): assert parsed.path == request.path assert parsed.query == request.query_string assert parsed.netloc == request.host + +def test_endpoint_name(): + app = Sanic('test_text') + + @app.route('/') + def my_unique_handler(request): + return text('Hello') + + request, response = app.test_client.get('/') + + assert request.endpoint == 'my_unique_handler'