Flask Routing & Views
Routing is one of Flask's core features, allowing you to map URLs to Python functions that handle the requests.
Basic Routing
@app.route('/')
def home():
return 'Home Page'
@app.route('/about')
def about():
return 'About Page'
Variable Rules
@app.route('/user/<username>')
def show_user_profile(username):
return f'User {username}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post {post_id}'
HTTP Methods
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
URL Building
from flask import url_for
@app.route('/')
def index():
return url_for('login', next='/') # Outputs: /login?next=/
Redirects
from flask import redirect
@app.route('/old-page')
def old_page():
return redirect(url_for('new_page'))
Error Handling
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
Blueprint Routing
from flask import Blueprint
auth = Blueprint('auth', __name__)
@auth.route('/login')
def login():
return 'Login Page'
# Register blueprint in main app
app.register_blueprint(auth, url_prefix='/auth')
Best Practices
- Use meaningful route names
- Keep view functions focused
- Use blueprints for larger applications
- Validate all input data
- Handle errors gracefully