How to debug a Flask app

前端 未结 13 2347
陌清茗
陌清茗 2020-11-22 03:08

How are you meant to debug errors in Flask? Print to the console? Flash messages to the page? Or is there a more powerful option available to figure out what\'s happening

相关标签:
13条回答
  • 2020-11-22 03:57

    Quick tip - if you use a PyCharm, go to Edit Configurations => Configurations and enable FLASK_DEBUG checkbox, restart the Run.

    0 讨论(0)
  • 2020-11-22 03:58

    If you are running it locally and want to be able to step through the code:

    python -m pdb script.py

    0 讨论(0)
  • 2020-11-22 03:59

    One can also use the Flask Debug Toolbar extension to get more detailed information embedded in rendered pages.

    from flask import Flask
    from flask_debugtoolbar import DebugToolbarExtension
    import logging
    
    app = Flask(__name__)
    app.debug = True
    app.secret_key = 'development key'
    
    toolbar = DebugToolbarExtension(app)
    
    @app.route('/')
    def index():
        logging.warning("See this message in Flask Debug Toolbar!")
        return "<html><body></body></html>"
    

    Start the application as follows:

    FLASK_APP=main.py FLASK_DEBUG=1 flask run
    
    0 讨论(0)
  • 2020-11-22 04:02

    From the 1.1.x documentation, you can enable debug mode by exporting an environment variable to your shell prompt:

    export FLASK_APP=/daemon/api/views.py  # path to app
    export FLASK_DEBUG=1
    python -m flask run --host=0.0.0.0
    
    0 讨论(0)
  • 2020-11-22 04:03

    If you want to debug your flask app then just go to the folder where flask app is. Don't forget to activate your virtual environment and paste the lines in the console change "mainfilename" to flask main file.

    export FLASK_APP="mainfilename.py"
    export FLASK_DEBUG=1
    python -m flask run --host=0.0.0.0
    

    After you enable your debugger for flask app almost every error will be printed on the console or on the browser window. If you want to figure out what's happening, you can use simple print statements or you can also use console.log() for javascript code.

    0 讨论(0)
  • 2020-11-22 04:04

    If you're using Visual Studio Code, replace

    app.run(debug=True)
    

    with

    app.run()
    

    It appears when turning on the internal debugger disables the VS Code debugger.

    0 讨论(0)
提交回复
热议问题