Skip to content

Commit

Permalink
Merge pull request #385 from FirstKlaas/state-for-request
Browse files Browse the repository at this point in the history
Added a state property to the request object.
  • Loading branch information
taoufik07 authored Aug 7, 2019
2 parents 784c7e7 + d73243a commit e6d302a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
15 changes: 14 additions & 1 deletion responder/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from requests.structures import CaseInsensitiveDict
from requests.cookies import RequestsCookieJar
from starlette.datastructures import MutableHeaders
from starlette.requests import Request as StarletteRequest
from starlette.requests import Request as StarletteRequest, State
from starlette.responses import (
Response as StarletteResponse,
StreamingResponse as StarletteStreamingResponse,
Expand Down Expand Up @@ -178,6 +178,19 @@ def params(self):
except AttributeError:
return QueryDict({})

@property
def state(self) -> State:
"""
Use the state to store additional information.
This can be a very helpful feature, if you want to hand over
information from a middelware or a route decorator to the
actual route handler.
For example: ``request.state.time_started = time.time()``
"""
return self._starlette.state

@property
async def encoding(self):
"""The encoding of the Request's body. Can be set, manually. Must be awaited."""
Expand Down
18 changes: 18 additions & 0 deletions tests/test_responder.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import string
import io

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient as StarletteTestClient

Expand Down Expand Up @@ -886,3 +887,20 @@ async def home(req, resp):

r = api.requests.post("/")
assert r.text == content

def test_api_request_state(api, url):
class StateMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
request.state.test1 = 42
request.state.test2 = "Foo"

response = await call_next(request)
return response

api.add_middleware(StateMiddleware)

@api.route("/")
def home(req, resp):
resp.text = "{}_{}".format(req.state.test2, req.state.test1)

assert api.requests.get(url("/")).text == "Foo_42"

0 comments on commit e6d302a

Please sign in to comment.