Introduction to Flask
Flask is a lightweight WSGI web application framework in Python. It's designed to make getting started quick and easy, with the ability to scale up to complex applications.
What is Flask?
Flask is:
- A micro web framework written in Python
- Based on Werkzeug WSGI toolkit and Jinja2 template engine
- Extremely lightweight and modular
- Great for small to medium web applications and APIs
Installation
# Create and activate a virtual environment
python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
# Install Flask
pip install flask
Minimal Flask Application
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Key Features
- Routing: Easy URL routing with decorators
- Templates: Jinja2 templating engine
- Development Server: Built-in development server
- Request Handling: Request and response objects
- Extensions: Modular design with extensions
Project Structure
flask_app/ ├── app.py # Main application file ├── static/ # Static files (CSS, JS, images) │ ├── style.css │ └── script.js └── templates/ # HTML templates └── index.html
Running the Application
# Run the development server
flask run
# Or alternatively
python app.py
Debug Mode
Enable debug mode for automatic reloading and better error messages:
if __name__ == '__main__':
app.run(debug=True)
Configuration
app.config['SECRET_KEY'] = 'your-secret-key'
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
Next Steps
Now that you have a basic Flask application running, you can explore:
- Creating more complex routes
- Working with templates
- Handling form submissions
- Connecting to databases