MCPcopy Create free account
hub / github.com/encode/starlette / __call__

Method __call__

starlette/middleware/sessions.py:42–91  ·  view source on GitHub ↗
(self, scope: Scope, receive: Receive, send: Send)

Source from the content-addressed store, hash-verified

40 self.security_flags += "; partitioned"
41
42 async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
43 if scope["type"] not in ("http", "websocket"): # pragma: no cover
44 await self.app(scope, receive, send)
45 return
46
47 connection = HTTPConnection(scope)
48 initial_session_was_empty = True
49
50 if self.session_cookie in connection.cookies:
51 data = connection.cookies[self.session_cookie].encode("utf-8")
52 try:
53 data = self.signer.unsign(data, max_age=self.max_age)
54 scope["session"] = Session(json.loads(b64decode(data)))
55 initial_session_was_empty = False
56 except BadSignature:
57 scope["session"] = Session()
58 else:
59 scope["session"] = Session()
60
61 async def send_wrapper(message: Message) -> None:
62 if message["type"] == "http.response.start":
63 session: Session = scope["session"]
64 headers = MutableHeaders(scope=message)
65 if session.accessed:
66 headers.add_vary_header("Cookie")
67 if session.modified and session:
68 # We have session data to persist.
69 data = b64encode(json.dumps(session).encode("utf-8"))
70 data = self.signer.sign(data)
71 header_value = "{session_cookie}={data}; path={path}; {max_age}{security_flags}".format(
72 session_cookie=self.session_cookie,
73 data=data.decode("utf-8"),
74 path=self.path,
75 max_age=f"Max-Age={self.max_age}; " if self.max_age else "",
76 security_flags=self.security_flags,
77 )
78 headers.append("Set-Cookie", header_value)
79 elif session.modified and not initial_session_was_empty:
80 # The session has been cleared.
81 header_value = "{session_cookie}={data}; path={path}; {expires}{security_flags}".format(
82 session_cookie=self.session_cookie,
83 data="null",
84 path=self.path,
85 expires="expires=Thu, 01 Jan 1970 00:00:00 GMT; ",
86 security_flags=self.security_flags,
87 )
88 headers.append("Set-Cookie", header_value)
89 await send(message)
90
91 await self.app(scope, receive, send_wrapper)
92
93
94class Session(dict[str, typing.Any]):

Callers

nothing calls this directly

Calls 3

HTTPConnectionClass · 0.90
SessionClass · 0.85
appMethod · 0.45

Tested by

no test coverage detected