add handler name to request as endpoint

This commit is contained in:
Raphael Deem 2017-10-16 22:40:21 -07:00
parent c5cdcf0f95
commit 75f2180cb1
4 changed files with 32 additions and 1 deletions

View File

@ -120,3 +120,19 @@ args.get('titles') # => 'Post 1'
args.getlist('titles') # => ['Post 1', 'Post 2'] 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)
```

View File

@ -247,6 +247,7 @@ class Sanic:
def response(handler): def response(handler):
async def websocket_handler(request, *args, **kwargs): async def websocket_handler(request, *args, **kwargs):
request.app = self request.app = self
request.endpoint = handler.__name__
try: try:
protocol = request.transport.get_protocol() protocol = request.transport.get_protocol()
except AttributeError: except AttributeError:
@ -540,6 +541,7 @@ class Sanic:
# Fetch handler from router # Fetch handler from router
handler, args, kwargs, uri = self.router.get(request) handler, args, kwargs, uri = self.router.get(request)
request.endpoint = handler.__name__
request.uri_template = uri request.uri_template = uri
if handler is None: if handler is None:
raise ServerError( raise ServerError(

View File

@ -46,7 +46,8 @@ class Request(dict):
__slots__ = ( __slots__ = (
'app', 'headers', 'version', 'method', '_cookies', 'transport', 'app', 'headers', 'version', 'method', '_cookies', 'transport',
'body', 'parsed_json', 'parsed_args', 'parsed_form', 'parsed_files', '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): def __init__(self, url_bytes, headers, version, method, transport):
@ -68,6 +69,7 @@ class Request(dict):
self.uri_template = None self.uri_template = None
self._cookies = None self._cookies = None
self.stream = None self.stream = None
self.endpoint = None
def __repr__(self): def __repr__(self):
if self.method is None or not self.path: if self.method is None or not self.path:

View File

@ -369,3 +369,14 @@ def test_url_attributes_with_ssl(path, query, expected_url):
assert parsed.path == request.path assert parsed.path == request.path
assert parsed.query == request.query_string assert parsed.query == request.query_string
assert parsed.netloc == request.host 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'