How to Run a Flask App: Simple Steps to Start Your Server
To run a Flask app, create a Python file with your app code and use
flask run in the terminal after setting the FLASK_APP environment variable. Alternatively, run your script directly with python your_app.py if it includes app.run().Syntax
To run a Flask app, you typically set the FLASK_APP environment variable to your app's Python file and then run flask run in your terminal. Alternatively, you can run the Python script directly if it contains app.run().
- FLASK_APP=your_app.py: Tells Flask which file to run.
- flask run: Starts the Flask development server.
- app.run(): Starts the server when running the script directly.
bash
export FLASK_APP=app.py
flask runOutput
* Serving Flask app 'app.py'
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Example
This example shows a minimal Flask app that returns 'Hello, World!' when you visit the home page. You can run it by setting FLASK_APP and using flask run, or by running the script directly.
python
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' if __name__ == '__main__': app.run()
Output
* Serving Flask app 'app.py'
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Common Pitfalls
Common mistakes when running Flask apps include:
- Not setting the
FLASK_APPenvironment variable before runningflask run. - Trying to run
flask runwithout an app file or with a wrong filename. - Forgetting to include
app.run()when running the script directly. - Running Flask in production mode without proper server setup (Flask's built-in server is for development only).
bash
Wrong way: flask run # Error: "Could not locate a Flask application" Right way: export FLASK_APP=app.py flask run
Quick Reference
| Command | Description |
|---|---|
| export FLASK_APP=app.py | Set the app file to run |
| flask run | Start the Flask development server |
| python app.py | Run the app script directly if it has app.run() |
| CTRL+C | Stop the running Flask server |
Key Takeaways
Set the FLASK_APP environment variable before running flask run.
Use flask run for development; use app.run() if running script directly.
Flask's built-in server is for development only, not production.
Common errors come from missing FLASK_APP or wrong filenames.
Stop the server anytime with CTRL+C in the terminal.