Yaroslav
Yaroslav

Reputation: 73

Conditional activation of Flask(Werkzeug) Debugger?

I am about to deploy a Flask application and due to built-in debugger is so good, I was wondering if I could use it in production environment.

Therefore I was looking for a conditional way to activate that debugger say only only for requests from specific IP, or only for request that have special passcode in cookies (or both coditions met).

I guess there is no built-in way to do that, thus I would love to have an advice of where I should dig to hack this in. Maybe it will be possible to monkey-patch Flask to do it? Also if it is a bad idea - let me know why.

Upvotes: 3

Views: 447

Answers (2)

sberry
sberry

Reputation: 132098

As @Miguel points out, this is not a good idea for production environment, but for the sake of hacking, this is how you can do it.

class CustomDebuggedApplication(DebuggedApplication):
    def __call__(self, environ, start_response):
        # Note, this line can check whatever you want.  A cookie, a query string param, a header.  But don't read the post form body.  If you do, it is gone and can't be used later.
        if not request.args.get('secret', False) == 'Foo' and not request.args.get('__debugger__', False):
            return self.app(environ, start_response)
        return super(CustomerDebuggedApplication).__call__(environ, start_response)

Upvotes: 0

Miguel Grinberg
Miguel Grinberg

Reputation: 67492

It's very likely possible to enable or disable the debugger by hacking Werkzeug's DebuggedApplication class (see source code here).

But it's a terrible idea. This is a production system, at the same time you go and debug your problem there will be real users interacting with the application through different threads or processes. Some of the things that can happen:

  • Werkzeug's debugger is likely tested inside the development server. It may or may not work when used under a multi-process or multi-threaded server.
  • While you debug your problem there will be real users interacting with the application on different processes or threads, possibly changing the state of the application from underneath you, which could affect your debugging.
  • While you debug your problem you may unintentionally change the state of the application in a way that affects other users currently working with the system.

Upvotes: 2

Related Questions