How to Create a Flask App: Simple Steps for Beginners
To create a Flask app, first install Flask with
pip install flask. Then, create a Python file with from flask import Flask, define an app using app = Flask(__name__), and add routes with @app.route(). Finally, run the app using app.run().Syntax
The basic syntax to create a Flask app includes importing Flask, creating an app instance, defining routes, and running the app.
- from flask import Flask: Imports the Flask class.
- app = Flask(__name__): Creates the app object.
- @app.route('/'): Defines a URL route.
- def function(): Defines the function to run when the route is accessed.
- app.run(): Starts the Flask development server.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, Flask!' if __name__ == '__main__': app.run()
Example
This example shows a simple Flask app that displays 'Hello, Flask!' when you visit the home page.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, Flask!' if __name__ == '__main__': app.run()
Output
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
When you open http://127.0.0.1:5000/ in a browser, it shows:
Hello, Flask!
Common Pitfalls
Common mistakes when creating a Flask app include:
- Not installing Flask before running the app.
- Forgetting to check
if __name__ == '__main__'before callingapp.run(), which can cause issues when importing. - Using incorrect route decorators or missing the
@app.routedecorator. - Not running the app in the correct environment or port conflicts.
python
from flask import Flask app = Flask(__name__) # Wrong: missing route decorator # def home(): # return 'Hello, Flask!' # Right way: @app.route('/') def home(): return 'Hello, Flask!' if __name__ == '__main__': app.run()
Quick Reference
| Step | Description |
|---|---|
| Install Flask | Run pip install flask in your terminal. |
| Import Flask | Use from flask import Flask in your Python file. |
| Create App | Define app = Flask(__name__). |
| Define Routes | Use @app.route('/') to set URL paths. |
| Run App | Call app.run() inside if __name__ == '__main__'. |
Key Takeaways
Install Flask using pip before creating your app.
Create the app with Flask(__name__) and define routes with @app.route decorators.
Always use if __name__ == '__main__' before running app.run() to avoid import issues.
Test your app by visiting the URL shown in the terminal after running the app.
Avoid missing route decorators or syntax errors to ensure your app works correctly.