Flask is a micro web framework for Python based on Werkzeug and Jinja 2. It's lightweight, easy to use, and highly flexible, making it an excellent choice for building web applications of all sizes. This tutorial will guide you through the basics of setting up a Flask application, routing, templates, forms, and more.
Before we start, ensure you have Python installed on your system. You can download it from python.org. Once Python is installed, you need to set up a virtual environment for your project:
# Create a new directory for your project and navigate into it
mkdir my_flask_app
cd my_flask_app
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
# On Windows
venv\Scripts\activate
# On macOS/Linux
source venv/bin/activate
# Install Flask
pip install Flask
Let's create a simple "Hello, World!" application to get started:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Flask class from the flask module.app = Flask(__name__) creates an instance of the Flask class. The __name__ variable is passed to help Flask determine the root path of the application.@app.route('/') decorator defines the route for the home page. When you visit the root URL, the hello_world function is called, and it returns the string "Hello, World!".if __name__ == '__main__': ensures that the app runs only if the script is executed directly (not imported). app.run(debug=True) starts the Flask development server with debug mode enabled, which provides detailed error messages and automatically reloads the server when code changes are detected.Templates allow you to separate your Python code from HTML. Flask uses Jinja2 templating engine by default.
templates in the root of your project.templates folder, create a file named index.html.<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask App</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
Modify your app.py to render the template:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html', name='World')
if __name__ == '__main__':
app.run(debug=True)
Flask provides tools for handling forms, including form validation and CSRF protection.
pip install Flask-WTF
forms.py:# forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
app.py to handle the form:# app.py
from flask import Flask, render_template, request
from forms import MyForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
@app.route('/', methods=['GET', 'POST'])
def hello_world():
form = MyForm()
if form.validate_on_submit():
return f'Hello, {form.name.data}!'
return render_template('index.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
MyForm is a subclass of FlaskForm. It defines fields using WTForms classes and validators.Update index.html to include the form:
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask App</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name(size=20) }}
{{ form.submit() }}
</form>
</body>
</html>
{{ form.hidden_tag() }} is required for CSRF protection.Static files like CSS, JavaScript, and images are stored in a folder named static.
static in the root of your project.style.css, inside the static folder:/* static/style.css */
body {
font-family: Arial, sans-serif;
}
index.html to link the CSS file:<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flask App</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name(size=20) }}
{{ form.submit() }}
</form>
</body>
</html>
filename='style.css' specifies the path to the CSS file.Flask is a powerful and flexible framework for building web applications in Python. In this tutorial, we covered setting up a basic Flask application, using templates, handling forms, and managing static files. These concepts form the foundation of more complex Flask applications. As you continue learning, explore Flask extensions like Flask-SQLAlchemy for database integration, Flask-Login for user authentication, and Flask-Migrate for database migrations.
Remember to always keep your virtual environment activated when working on your Flask projects, and use pip freeze > requirements.txt to save your dependencies for easy setup in other environments. Happy coding!