[Python][Flask] Routes vs Endpoints
Understanding Routes vs. Endpoints in Flask
Differences between routes and endpoints in Flask
-
Route
The path that users type in the browser, such as"/blog/"or"/sign_up". It is defined with a decorator:@blog.route('/')def load_main_page():...When someone visits
http://localhost:5000/blog/, Flask runsload_main_page(). -
Endpoint
The internal name Flask uses to identify the function handling a given route. By default, this is"<blueprint_name>.<function_name>"unless it is renamed. For example, if the blueprint is namedblogand the function isload_main_page, the endpoint becomesblog.load_main_page. -
url_for()
This function generates a URL by looking up the endpoint name:url_for('blog.load_main_page')returns the route
"/blog/"ifurl_prefix='/blog'.
Example
# Blueprint definitionblog = Blueprint('blog', __name__)
@blog.route('/')def load_main_page(): # Renders the main page return render_template('index.html')
@blog.route('/sign_up', methods=['GET', 'POST'])def sign_up(): if request.method == 'POST': # Create user, log in, then redirect: return redirect(url_for('.load_main_page')) return render_template('signup.html')
-
Route:
-
"/"and"/sign_up"are the browser-accessible URLs.
-
-
Endpoint:
-
blog.load_main_page -
blog.sign_up
-
redirect(url_for('.load_main_page'))
The endpoint .load_main_page is internally referenced, and Flask knows to build a URL pointing to "/blog/".
Why It Matters
-
url_for()needs the endpoint name (the function name), not the route path. -
This separation helps Flask keep the browser-level address (the route) distinct from the code that handles it (the endpoint).
Comments
Post a Comment