Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add handler name to request as endpoint #1445

Merged
merged 4 commits into from
Jan 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions docs/sanic/request_data.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,40 @@ 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)
```

Or, with a blueprint it will be include both, separated by a period. For example,
the below route would return foo.bar:

```python
from sanic import Sanic
from sanic import Blueprint
from sanic.response import text


app = Sanic(__name__)
blueprint = Blueprint('foo')

@blueprint.get('/')
async def bar(request):
return text(request.endpoint)

app.blueprint(blueprint)

app.run(host="0.0.0.0", port=8000, debug=True)
```
21 changes: 21 additions & 0 deletions sanic/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,13 @@ def websocket(
def response(handler):
async def websocket_handler(request, *args, **kwargs):
request.app = self
if not getattr(handler, "__blueprintname__", False):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe these two if/else chunks can be refactored into a method?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually like the if/else for clarity of reading. I think it's a simple enough logic branch that it doesn't necessarily require moving it to its own method... with that being said, perhaps it's worth revisiting if we do end up adding more complexity here.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sjsadowski Looking back at the comment, I see how my message was a bit confusing. I suggested the refactoring because we can re-use what we do in and around line#457 and carry it over to line#898

request.endpoint = handler.__name__
else:
request.endpoint = (
getattr(handler, "__blueprintname__", "")
+ handler.__name__
)
try:
protocol = request.transport.get_protocol()
except AttributeError:
Expand Down Expand Up @@ -888,6 +895,16 @@ async def handle_request(self, request, write_callback, stream_callback):
"handler from the router"
)
)
else:
if not getattr(handler, "__blueprintname__", False):
request.endpoint = self._build_endpoint_name(
handler.__name__
)
else:
request.endpoint = self._build_endpoint_name(
getattr(handler, "__blueprintname__", ""),
handler.__name__,
)

# Run response handler
response = handler(request, *args, **kwargs)
Expand Down Expand Up @@ -1276,3 +1293,7 @@ def _helper(
logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port))

return server_settings

def _build_endpoint_name(self, *parts):
parts = [self.name, *parts]
return ".".join(parts)
30 changes: 16 additions & 14 deletions sanic/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,26 +69,27 @@ class Request(dict):
"""Properties of an HTTP request such as URL, headers, etc."""

__slots__ = (
"app",
"headers",
"version",
"method",
"__weakref__",
"_cookies",
"transport",
"body",
"parsed_json",
"parsed_args",
"parsed_form",
"parsed_files",
"_ip",
"_parsed_url",
"uri_template",
"stream",
"_port",
"_remote_addr",
"_socket",
"_port",
"__weakref__",
"app",
"body",
ahopkins marked this conversation as resolved.
Show resolved Hide resolved
"endpoint",
"headers",
"method",
"parsed_args",
"parsed_files",
"parsed_form",
"parsed_json",
"raw_url",
"stream",
"transport",
"uri_template",
"version",
)

def __init__(self, url_bytes, headers, version, method, transport):
Expand All @@ -111,6 +112,7 @@ def __init__(self, url_bytes, headers, version, method, transport):
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:
Expand Down
1 change: 1 addition & 0 deletions tests/test_logo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

try:
import uvloop # noqa

ROW = 0
except BaseException:
ROW = 1
Expand Down
41 changes: 41 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

import pytest

from sanic import Sanic
from sanic import Blueprint
from sanic.exceptions import ServerError
from sanic.request import DEFAULT_HTTP_CONTENT_TYPE
from sanic.response import json, text
Expand Down Expand Up @@ -698,3 +700,42 @@ async def post(request):
request, response = app.test_client.post("/", json={"test": "OK"})

assert request.form == {}


def test_endpoint_basic():
app = Sanic()

@app.route("/")
def my_unique_handler(request):
return text("Hello")

request, response = app.test_client.get("/")

assert request.endpoint == "test_requests.my_unique_handler"


def test_endpoint_named_app():
app = Sanic("named")

@app.route("/")
def my_unique_handler(request):
return text("Hello")

request, response = app.test_client.get("/")

assert request.endpoint == "named.my_unique_handler"


def test_endpoint_blueprint():
bp = Blueprint("my_blueprint", url_prefix="/bp")

@bp.route("/")
async def bp_root(request):
return text("Hello")

app = Sanic("named")
app.blueprint(bp)

request, response = app.test_client.get("/bp")

assert request.endpoint == "named.my_blueprint.bp_root"