Performance: Permission checking in routes
This affects the server response time and perceived page load speed by controlling how quickly permission checks allow or block route access.
from flask import g, request, abort @app.before_request def load_user(): g.user = get_user_from_cache_or_db(request.headers.get('Authorization')) @app.route('/dashboard') def dashboard(): if not g.user or not g.user.has_permission('view_page'): abort(403) return render_template('dashboard.html')
from flask import request, abort def check_permission(): user = get_user_from_db(request.headers.get('Authorization')) if not user.has_permission('view_page'): abort(403) @app.route('/dashboard') def dashboard(): check_permission() return render_template('dashboard.html')
| Pattern | DB Queries | Server Delay | Impact on LCP | Verdict |
|---|---|---|---|---|
| Check permissions with DB query on every route | Multiple per request | 50-100ms delay | Delays LCP significantly | [X] Bad |
| Cache user and permissions per request | One or cached | Minimal delay | Improves LCP | [OK] Good |
abort() function stops a request and returns an HTTP error code.abort(403) is correct.from flask import abort, Flask, request
app = Flask(__name__)
@app.route('/admin')
def admin_panel():
if not (request.args.get('is_admin') == 'true'):
abort(403)
return 'Welcome Admin'/admin?is_admin=false?from flask import abort, Flask
app = Flask(__name__)
@app.route('/secret')
def secret():
if user.is_admin == False:
abort(403)
return 'Secret Data'user.is_admin but user is not defined or passed in the function.check_permission() that aborts with 403 if the user is not an admin. Which of these is the best way to use it in a Flask route?Pass the test and this pattern moves unknown