Last modified: Nov 15, 2024 By Alexander Williams
Flask Installation and Project Setup Guide: Quick Start Tutorial
Flask is a lightweight Python web framework that makes building web applications simple and enjoyable. In this guide, we'll walk through the process of installing Flask and setting up your first project.
Installing Flask
Before creating a Flask application, you need to install Flask using pip. Open your terminal and run the following command:
pip install flask
If you encounter any issues during installation, you might want to check out our guide on solving common Flask installation errors.
Creating Project Structure
A well-organized Flask project structure is crucial for maintainability. Here's a recommended basic structure:
my_flask_app/
├── app/
│ ├── __init__.py
│ ├── routes.py
│ └── templates/
├── config.py
└── run.py
Creating Flask Application Instance
Create a new file called run.py in your project root and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Understanding the Basic Components
The Flask(__name__)
creates a new Flask application instance. The __name__ parameter tells Flask where to look for resources like templates and static files.
The @app.route('/')
decorator defines the URL path for your function. You can learn more about template rendering in our render_template guide.
Running Your Application
To start your Flask application, run the following command in your terminal:
python run.py
You should see output similar to this:
* Serving Flask app "app"
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Environment Variables and Configuration
Create a config.py file to manage your application settings:
class Config:
SECRET_KEY = 'your-secret-key'
DEBUG = True
You can explore more advanced Flask applications like our Image Cartoonizer tutorial once you're comfortable with the basics.
Conclusion
You now have a basic Flask application up and running. This foundation will allow you to build more complex web applications by adding routes, templates, and database interactions.