Skip to content

Commit

Permalink
Add query parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
aminalaee committed Feb 4, 2022
1 parent 424351c commit fa3fbf1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 7 additions & 2 deletions starlette/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,15 @@ def state(self) -> State:
self._state = State(self.scope["state"])
return self._state

def url_for(self, name: str, **path_params: typing.Any) -> str:
def url_for(
self, name: str, query_params: dict = None, **path_params: typing.Any
) -> str:
router: Router = self.scope["router"]
url_path = router.url_path_for(name, **path_params)
return url_path.make_absolute_url(base_url=self.base_url)
absolute_url = URL(url_path.make_absolute_url(base_url=self.base_url))
if query_params:
absolute_url = absolute_url.include_query_params(**query_params)
return absolute_url._url


async def empty_receive() -> typing.NoReturn:
Expand Down
19 changes: 19 additions & 0 deletions tests/test_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest

from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, PlainTextResponse, Response
from starlette.routing import Host, Mount, NoMatchFound, Route, Router, WebSocketRoute
from starlette.websockets import WebSocket, WebSocketDisconnect
Expand Down Expand Up @@ -700,3 +701,21 @@ def test_duplicated_param_names():
match="Duplicated param names id, name at path /{id}/{name}/{id}/{name}",
):
Route("/{id}/{name}/{id}/{name}", user)


def test_url_for_with_query_params(test_client_factory):
def echo_queryparams_urls(request: Request):
return JSONResponse(
{
"queryparams": request.url_for("index", query_params={"Foo": "Bar"}),
}
)

routes = [Route("/", echo_queryparams_urls, name="index", methods=["GET"])]
app = Starlette(routes=routes)
client = test_client_factory(app)
response = client.get("/")

assert response.json() == {
"queryparams": "http://testserver/?Foo=Bar",
}

0 comments on commit fa3fbf1

Please sign in to comment.