Performance: API key authentication concept
This concept affects the server response time and initial page load speed by adding authentication checks before processing requests.
from flask import Flask, request from functools import lru_cache app = Flask(__name__) @lru_cache(maxsize=128) def validate_key(key): return key == 'expected_key' @app.before_request def check_api_key(): key = request.args.get('api_key') if not validate_key(key): return 'Unauthorized', 401 @app.route('/') def home(): return 'Hello World!'
from flask import Flask, request app = Flask(__name__) @app.before_request def check_api_key(): key = request.args.get('api_key') if key != 'expected_key': return 'Unauthorized', 401 @app.route('/') def home(): return 'Hello World!'
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No API key check | 0 | 0 | 0 | [OK] Good |
| API key check without caching | 0 | 0 | 0 | [X] Bad - adds server delay |
| API key check with caching | 0 | 0 | 0 | [!] OK - improved server response |
X-API-KEY: wrongkey?
from flask import Flask, request, jsonify
app = Flask(__name__)
VALID_API_KEY = 'secret123'
@app.route('/data')
def data():
api_key = request.headers.get('X-API-KEY')
if api_key == VALID_API_KEY:
return jsonify({'message': 'Access granted'})
else:
return jsonify({'error': 'Unauthorized'}), 401
from flask import Flask, request
app = Flask(__name__)
VALID_KEY = 'abc123'
@app.route('/info')
def info():
api_key = request.headers['X-API-KEY']
if api_key = VALID_KEY:
return 'Access allowed'
else:
return 'Access denied', 403
Pass the test and this pattern moves unknown