add handler name to request as endpoint
This commit is contained in:
parent
c5cdcf0f95
commit
75f2180cb1
|
@ -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)
|
||||
```
|
||||
|
|
|
@ -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(
|
||||
|
|
|
@ -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:
|
||||
|
|
|
@ -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'
|
||||
|
|
Loading…
Reference in New Issue
Block a user