pallets/flask · error · RuntimeError

Session backend did not open a session.

Error message

Session backend did not open a session.

What it means

In session_transaction, Flask calls app.session_interface.open_session(app, ctx.request). If that returns None (the interface could not/ would not open a session - e.g. SecureCookieSessionInterface with no secret key, or a custom interface whose open_session returns None), the method raises RuntimeError. This is the session-backend equivalent of the NullSession secret-key failure, surfaced at test time.

Solutions

  1. Set app.secret_key before session_transaction (most common cause).
  2. If using a custom SessionInterface, ensure open_session always returns a session object (never None) for valid requests, or raise a clearer error inside it.
  3. In tests, build the app with a known secret_key and a stable session interface.

Example fix

// before
app = Flask(__name__)
with app.test_client(use_cookies=True) as c:
    with c.session_transaction() as sess:  # raises
        sess['k'] = 1

// after
app = Flask(__name__)
app.secret_key = 'test'
with app.test_client(use_cookies=True) as c:
    with c.session_transaction() as sess:
        sess['k'] = 1
Defensive patterns

Strategy: validation

Validate before calling

def session_can_open(app, request):
    sess = app.session_interface.open_session(app, request)
    if sess is None:
        if not app.secret_key:
            raise RuntimeError('set app.secret_key so the session backend can open a session')
        raise RuntimeError('session_interface.open_session returned None')
    return sess

Try / catch

try:
    with client.session_transaction() as s:
        s['k'] = 1
except RuntimeError as e:
    if 'did not open a session' in str(e):
        app.secret_key = 'test'  # fix and retry in tests
        raise

Prevention

When it happens

Trigger: Running session_transaction without app.secret_key set (SecureCookieSessionInterface.open_session returns None when secret_key is falsy); a custom SessionInterface whose open_session returns None on a malformed cookie or unsupported request.

Common situations: Test app factory forgot to set secret_key; switched to a custom session backend whose open_session has a None path; cookie sent in the test is unsigned/expired.

Related errors


AI-assisted analysis of pallets/flask@3596b1ab61 (2026-08-11). Data as JSON: /api/errors/6d1f2a720132954d. Report an issue: GitHub.

Appendix: source

Thrown at src/flask/testing.py:168

        request context and since session handling could depend on
        request variables this function accepts the same arguments as
        :meth:`~flask.Flask.test_request_context` which are directly
        passed through.
        """
        if self._cookies is None:
            raise TypeError(
                "Cookies are disabled. Create a client with 'use_cookies=True'."
            )

        app = self.application
        ctx = app.test_request_context(*args, **kwargs)
        self._add_cookies_to_wsgi(ctx.request.environ)

        with ctx:
            sess = app.session_interface.open_session(app, ctx.request)

        if sess is None:
            raise RuntimeError("Session backend did not open a session.")

        yield sess
        resp = app.response_class()

        if app.session_interface.is_null_session(sess):
            return

        with ctx:
            app.session_interface.save_session(app, sess, resp)

        self._update_cookies_from_response(
            urlsplit(ctx.request.host_url).hostname or "localhost",
            ctx.request.path,
            resp.headers.getlist("Set-Cookie"),
        )

    def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment:
        out = {**self.environ_base, **other}

View on GitHub (pinned to 3596b1ab61)