10

Can I prevent Flask framework from ever sending a Set-Cookie header?

I'm using a variety of blueprints that use the session cookie. I'm wondering if there is a way to tell the framework to simply never try to set cookies. I'd like to not have to prepare each individual response using suggestions like this or using app.after_request.

sholsapp
  • 15,542
  • 10
  • 50
  • 67
  • Follow the link in your post. You can do `resp.set_cookie('session', '', expires=0)` in `app.after_request` handler. – stamaimer Jun 28 '17 at 03:30
  • 1
    @stamaimer I explicitly say I don't want to do this. Additional processing after _every_ request isn't reasonable to me. I'm fishing for configuration that might disable the setting of cookies in general. – sholsapp Jun 28 '17 at 03:57
  • Maybe you can see the 1692 line in the Flask code in app.py. I find flask add `Set-Cookies` in that line. – stamaimer Jun 28 '17 at 04:03

1 Answers1

2

You can create custom session interface and override should_set_cookie method

from flask import Flask
from flask.sessions import SecureCookieSessionInterface, SessionMixin


class CustomSessionInterface(SecureCookieSessionInterface):
    def should_set_cookie(self, app: "Flask", session: SessionMixin) -> bool:
        return False


app = Flask(__name__)
app.session_interface = CustomSessionInterface()
r-m-n
  • 14,192
  • 4
  • 69
  • 68
  • 3
    For anyone who wants to disable `Set-Cookie` on certain paths, this method gets run on every request and you have access to `request.path`. – Garrett Oct 11 '21 at 19:52