0
0
Flaskframework~5 mins

Route naming conventions in Flask

Choose your learning style9 modes available
Introduction

Route naming conventions help keep your web app organized and easy to understand. They make URLs clear and predictable for users and developers.

When creating URLs for different pages or actions in your Flask app
When you want your URLs to be easy to read and remember
When you want to follow common web standards for naming routes
When working with a team to keep code consistent
When you want to improve SEO by using meaningful URL names
Syntax
Flask
@app.route('/route-name')
def function_name():
    pass
Use lowercase letters and hyphens (-) to separate words in URLs.
Keep route names short but descriptive.
Examples
This is the main page route, usually named '/' for the homepage.
Flask
@app.route('/')
def home():
    return 'Home Page'
Use hyphens to separate words in multi-word routes.
Flask
@app.route('/about-us')
def about():
    return 'About Us Page'
Use angle brackets to capture variables in routes, like user IDs.
Flask
@app.route('/user/<int:user_id>')
def user_profile(user_id):
    return f'User {user_id} Profile'
Sample Program

This Flask app shows three routes following naming conventions: the homepage '/', a hyphenated multi-word route '/contact-us', and a dynamic route with a variable '/product/<int:product_id>'.

Flask
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the Home Page'

@app.route('/contact-us')
def contact():
    return 'Contact Us Here'

@app.route('/product/<int:product_id>')
def product_detail(product_id):
    return f'Product Details for product {product_id}'

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always use lowercase letters in route names to avoid confusion.

Use hyphens (-) instead of underscores (_) in URLs for better readability.

Keep routes simple and meaningful to help users and search engines.

Summary

Use clear, lowercase, hyphen-separated names for routes.

Dynamic parts of routes use <variable> syntax in Flask.

Consistent route naming makes your app easier to use and maintain.