Quantcast
Channel: Sullerton
Viewing all articles
Browse latest Browse all 12

Debugging a Flask app inside PyCharm

$
0
0

Flask’s simplicity is great.

from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Hello World!"
 
if __name__ == "__main__":
    app.run()

But once you’re up and running you’ll find you need to refine your servers settings to your liking. I had to make some changes to get PyCharm’s debugger hitting breakpoints.

The python argparse module makes it easy to add a little flavor to your command line params.

#my_app.py
from flask import Flask
app = Flask(__name__)
 
@app.route("/")
def hello():
    return "Hello World!"
 
if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Development Server Help')
    parser.add_argument("-d", "--debug", action="store_true", dest="debug_mode",
                  help="run in debug mode (for use with PyCharm)", default=False)
    parser.add_argument("-p", "--port", dest="port",
                  help="port of server (default:%(default)s)", type=int, default=5000)
 
    cmd_args = parser.parse_args()
    app_options = {"port": cmd_args.port }
 
    if cmd_args.debug_mode:
        app_options["debug"] = True
        app_options["use_debugger"] = False
        app_options["use_reloader"] = False
 
    app.run(**app_options)

This allows you to accept command line parameters. A simple help query against your app will show you a friendly message:

~username$ python my_app.py -h
usage: my_app.py [-h] [-d] [-p PORT]

Development Server Help

optional arguments:
-h, --help show this help message and exit
-d, --debug run in debug mode (for use with PyCharm)
-p PORT, --port PORT port of server (default:5000)

This will allow you to pass “-d” as an additional argument in your PyCharm Debug Configuration and it will play nicely with the pycharm debugger. I also added a port param so that you can run it on a different port; django burned 127.0.0.1:8000 into my chrome history.

Keep in mind you need to be running PyCharm 2.0+ for the debugger to work correctly with flask. You also lose the automatic reloading of the server, but you need to restart the debugger if you make changes to your code anyways.


Viewing all articles
Browse latest Browse all 12

Trending Articles