Routes, Templates, and Forms
Flask: Python Web Framework Essentials
Flask is a powerful yet simple web framework for Python that lets you build web applications quickly. This guide covers the core concepts you need to get started with Flask development.
1. Flask Routes
Routes define the URLs your app responds to. You use the @app.route()
decorator to bind a URL to a Python function (called a "view").
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Welcome to Home Page'
@app.route('/about')
def about():
return 'About Us Page'
if __name__ == '__main__':
app.run(debug=True)
When users visit /, they see the home page. When they visit /about, they see the about page.
2. Flask Templates (HTML with Jinja2)
Flask uses the Jinja2 template engine to render HTML with Python code.
Project Structure
/flask_app
├── app.py
└── /templates
└── index.html
└── about.html
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', name="LetDigitalFly")
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome {{ name }}!</h1>
<p>This is the homepage.</p>
</body>
</html>
templates/about.html
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h2>About Page</h2>
<p>Welcome to the about page of our Flask App.</p>
</body>
</html>
The {{ name }} syntax is part of Jinja2, allowing dynamic content in your HTML.
3. Flask Forms (POST Request Handling)
Add a Simple Form Page
Update app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
return render_template('form.html')
@app.route('/submit', methods=['POST'])
def submit():
username = request.form['username']
return f'Hello, {username}!'
if __name__ == '__main__':
app.run(debug=True)
Create templates/form.html
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<h2>Enter Your Name</h2>
<form method="post" action="/submit">
<input type="text" name="username" placeholder="Your Name" required>
<input type="submit" value="Submit">
</form>
</body>
</html>
When the form is submitted, it sends a POST request to /submit, and the server responds with a personalized message.
Summary
Feature | Description |
---|---|
Routes | Map URLs to Python functions |
Templates | Render dynamic HTML using Jinja2 |
Forms | Capture user input using POST/GET |