Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugging Flask in PyCharm

I'm trying to figure out how to easily switch between debugging my Flask application with the Flask (Werkzeug) debugger and using PyCharm's debugger. I've gotten as far as having two PyCharm run configurations

  1. one that I invoke with "Run" and --debug flag supplied to the application script; and
  2. one that I invoke with "Debug" and a --pydebug flag supplied to the application script

with the flags supported in my application script with"

if __name__ == "__main__":

    import argparse
    parser = argparse.ArgumentParser(description='Runs Web application with options for debugging')
    parser.add_argument('-d', '--debug', action='store_true', 
                        dest='debug_mode', default=False,
                        help='run in Werkzeug debug mode')
    parser.add_argument('-p', '--pydebug', action='store_true') 
                        dest='debug_pycharm', default=False,
                        help='for use with PyCharm debugger')

    cmd_args = parser.parse_args()
    app_options = dict()

    app_options["debug"] = cmd_args.debug_mode or cmd_args.debug_pycharm
    if cmd_args.debug_pycharm:
        app_options["use_debugger"] = False
        app_options["use_reloader"] = False

    application.run(**app_options)

This works, and meets the requirement that I don't need to edit any code to deploy to a server; but I'm not sure it's the best approach. For one thing I need to remember that the second configuration is meant to be launched with "Debug" (not "Run") while the first is meant to be launched with "Run" (not "Debug") in PyCharm.

Is there a better approach to supporting these two approaches to debugging in PyCharm, using either some feature of PyCharm (e.g. that allows me to detect when "Debug" has been invoked rather than "Run") or smarter use of Flask's features.

like image 413
orome Avatar asked Apr 05 '26 20:04

orome


1 Answers

A very easy way to check if your application is running under the PyCharm debugger is:

'pydevd' in sys.modules
like image 190
yole Avatar answered Apr 08 '26 10:04

yole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!