MCPcopy
hub / github.com/encode/starlette / __call__

Method __call__

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

Source from the content-addressed store, hash-verified

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