|
"""
|
|
API密钥管理系统 - 主应用文件
|
|
提供API密钥的添加、编辑、删除和管理功能
|
|
"""
|
|
import os
|
|
import time
|
|
import pytz
|
|
from flask import Flask, redirect, url_for, request, jsonify
|
|
from flask_compress import Compress
|
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
|
|
|
|
|
from config import SECRET_KEY
|
|
|
|
|
|
from core.api_manager import start_service
|
|
|
|
|
|
os.environ['TZ'] = 'Asia/Shanghai'
|
|
try:
|
|
|
|
time.tzset()
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
|
default_tz = pytz.timezone('Asia/Shanghai')
|
|
|
|
|
|
from routes.web import web_bp
|
|
from routes.api import api_bp
|
|
|
|
|
|
from utils.auth import AuthManager
|
|
|
|
from utils.db import init_db
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
compress = Compress()
|
|
|
|
app.config['COMPRESS_MIMETYPES'] = [
|
|
'text/html', 'text/css', 'text/xml', 'application/json',
|
|
'application/javascript', 'text/javascript', 'text/plain'
|
|
]
|
|
app.config['COMPRESS_LEVEL'] = 6
|
|
app.config['COMPRESS_MIN_SIZE'] = 500
|
|
app.config['COMPRESS_ALGORITHM'] = 'br,gzip'
|
|
|
|
compress.init_app(app)
|
|
|
|
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
|
|
app.secret_key = SECRET_KEY
|
|
|
|
|
|
@app.after_request
|
|
def add_cache_headers(response):
|
|
"""为静态资源添加缓存控制头"""
|
|
if request.path.startswith('/static/'):
|
|
|
|
max_age = 31536000
|
|
|
|
|
|
if request.path.endswith(('.css', '.js')):
|
|
|
|
response.headers['Cache-Control'] = f'public, max-age={max_age}'
|
|
elif request.path.endswith(('.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg')):
|
|
|
|
response.headers['Cache-Control'] = f'public, max-age={max_age}'
|
|
else:
|
|
|
|
response.headers['Cache-Control'] = 'public, max-age=604800'
|
|
|
|
|
|
response.headers['Vary'] = 'Accept-Encoding'
|
|
|
|
return response
|
|
|
|
|
|
@app.before_request
|
|
def authenticate():
|
|
"""请求拦截器 - 验证所有需要认证的请求"""
|
|
|
|
if request.path == '/login' or request.path.startswith('/static/'):
|
|
return
|
|
|
|
|
|
token = request.cookies.get('auth_token')
|
|
|
|
|
|
if not AuthManager.verify_token(token):
|
|
|
|
if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.path.startswith('/api/'):
|
|
return jsonify({"success": False, "error": "未授权访问"}), 401
|
|
|
|
return redirect(url_for('web.login'))
|
|
|
|
|
|
app.register_blueprint(web_bp)
|
|
app.register_blueprint(api_bp)
|
|
|
|
|
|
with app.app_context():
|
|
init_db()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
api_service_threads = start_service()
|
|
|
|
app.run(debug=True, host='0.0.0.0', port=7860)
|
|
|