MCPcopy
hub / github.com/pallets/flask / session_transaction

Method session_transaction

src/flask/testing.py:136–183  ·  view source on GitHub ↗

When used in combination with a ``with`` statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the ``with`` block is left the session is stored back. :: with client.session_transaction() as s

(
        self, *args: t.Any, **kwargs: t.Any
    )

Source from the content-addressed store, hash-verified

134
135 @contextmanager
136 def session_transaction(
137 self, *args: t.Any, **kwargs: t.Any
138 ) -> t.Iterator[SessionMixin]:
139 """When used in combination with a ``with`` statement this opens a
140 session transaction. This can be used to modify the session that
141 the test client uses. Once the ``with`` block is left the session is
142 stored back.
143
144 ::
145
146 with client.session_transaction() as session:
147 session['value'] = 42
148
149 Internally this is implemented by going through a temporary test
150 request context and since session handling could depend on
151 request variables this function accepts the same arguments as
152 :meth:`~flask.Flask.test_request_context` which are directly
153 passed through.
154 """
155 if self._cookies is None:
156 raise TypeError(
157 "Cookies are disabled. Create a client with 'use_cookies=True'."
158 )
159
160 app = self.application
161 ctx = app.test_request_context(*args, **kwargs)
162 self._add_cookies_to_wsgi(ctx.request.environ)
163
164 with ctx:
165 sess = app.session_interface.open_session(app, ctx.request)
166
167 if sess is None:
168 raise RuntimeError("Session backend did not open a session.")
169
170 yield sess
171 resp = app.response_class()
172
173 if app.session_interface.is_null_session(sess):
174 return
175
176 with ctx:
177 app.session_interface.save_session(app, sess, resp)
178
179 self._update_cookies_from_response(
180 ctx.request.host.partition(":")[0],
181 ctx.request.path,
182 resp.headers.getlist("Set-Cookie"),
183 )
184
185 def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:
186 out = {**self.environ_base, **other}

Calls 4

test_request_contextMethod · 0.80
is_null_sessionMethod · 0.80
open_sessionMethod · 0.45
save_sessionMethod · 0.45

Tested by

no test coverage detected