29 lines
1001 B
Python
29 lines
1001 B
Python
"""Request limiting and HTML/SSE cache headers with app-scoped state."""
|
|
|
|
import time
|
|
|
|
from flask import current_app, jsonify, request
|
|
|
|
|
|
def rate_limit():
|
|
path = request.path
|
|
if path in ('/healthz', '/api/visitor/human/poll') or path.startswith('/static') or path.startswith('/api/human/'):
|
|
return None
|
|
ip = request.remote_addr or 'unknown'
|
|
now = time.time()
|
|
hits = current_app.extensions['rate_hits'][ip]
|
|
while hits and now - hits[0] > 60:
|
|
hits.pop(0)
|
|
if len(hits) >= current_app.config['RATE_LIMIT_PER_MIN']:
|
|
return jsonify({'e': '请求太频繁,请稍后几秒再试', 'd': 1}), 429
|
|
hits.append(now)
|
|
return None
|
|
|
|
|
|
def no_cache_html(response):
|
|
if response.mimetype in ('text/html', 'text/event-stream') or request.path.startswith('/api/'):
|
|
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate'
|
|
response.headers['Pragma'] = 'no-cache'
|
|
response.headers['Expires'] = '0'
|
|
return response
|