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

Expose scope parameter in request object #2432

Merged
merged 15 commits into from Apr 26, 2022
Merged
10 changes: 10 additions & 0 deletions sanic/request.py
Expand Up @@ -14,6 +14,7 @@

from sanic_routing.route import Route # type: ignore

from sanic.models.asgi import ASGIScope
from sanic.models.http_types import Credentials


Expand Down Expand Up @@ -819,6 +820,15 @@ def url_for(self, view_name: str, **kwargs) -> str:
view_name, _external=True, _scheme=scheme, _server=netloc, **kwargs
)

@property
def scope(self) -> Optional[ASGIScope]:
"""
:return: the URL
prryplatypus marked this conversation as resolved.
Show resolved Hide resolved
:rtype: str
prryplatypus marked this conversation as resolved.
Show resolved Hide resolved
"""

return self.transport.scope if self.app.asgi else None


class File(NamedTuple):
"""
Expand Down
23 changes: 23 additions & 0 deletions tests/test_request.py
Expand Up @@ -191,3 +191,26 @@ def test_bad_url_parse():
Mock(),
Mock(),
)


def test_request_scope_is_none_when_no_asgi():
app = Sanic("no_asgi")

@app.get("/")
async def get(request):
return response.empty()

request, _ = app.test_client.get("/")
assert request.scope == None
prryplatypus marked this conversation as resolved.
Show resolved Hide resolved


@pytest.mark.asyncio
async def test_request_scope_is_not_none_when_runnin_in_asgi(app):
@app.get("/")
async def get(request):
return response.empty()

request, _ = await app.asgi_client.get("/")
assert request.scope != None
prryplatypus marked this conversation as resolved.
Show resolved Hide resolved
assert request.scope["method"].lower() == "get"
assert request.scope["path"].lower() == "/"