This project is a step-by-step guide to building simple Flask applications. It covers creating Flask apps, adding routes, handling requests, working with templates, custom error handling, and more.
- Python 3.x
- Flask (installed via pip)
- A code editor like Visual Studio Code
- Basic knowledge of Python and web development
Open Visual Studio Code and create a folder called flask-project-tutorial
(for example).
In the terminal, create and activate a virtual environment:
python -m venv flask-venv
.\flask-venv\Scripts\activate # Windows
Inside the virtual environment, install Flask:
pip install flask
Save installed packages to requirements.txt
:
pip freeze > requirements.txt
Create your first Flask app (app1.py
):
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello World"
if __name__ == "__main__":
app.run(debug=True)
Add dynamic routes to handle user input via URLs:
@app.route('/greet/<name>')
def greet(name):
return f"Good morning, {name}."
Render HTML templates using Jinja2:
@app.route('/')
def home():
return render_template('app3.html', message="Welcome to Flask with templates!")
Capture form input and display it dynamically:
@app.route('/greet', methods=['POST'])
def greet():
user_name = request.form['name']
return f"Hello, {user_name}"
Customize the 404 error page:
@app.errorhandler(404)
def page_not_found(e):
return render_template('app5.html'), 404
Use static files for styling (e.g., CSS):
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
Implement URL redirection based on user roles:
@app.route('/user/<name>')
def user_identification(name):
if name == "admin":
return redirect(url_for('hello_admin'))
else:
return redirect(url_for('hello_guest', name=name))
Activate the virtual environment:
.\flask-venv\Scripts\activate
Run any of the apps (e.g., app1.py
):
python app1.py
Access the app in your browser at http://127.0.0.1:5000, or at http://127.0.0.1:5001, depending on how you've configured your project.