agagsder's picture
Upload 3 files
10cd7fe verified
# -*- coding: utf-8 -*-
"""
Hugging Face Space - Cloudflare Worker 代理
部署到 Hugging Face Spaces,用于国内访问 Cloudflare Worker API
"""
from flask import Flask, request, Response
import requests
import os
app = Flask(__name__)
# Cloudflare Worker 地址
WORKER_URL = "https://license-api.yunzun8.workers.dev"
# 代理访问密钥(防止滥用)
PROXY_KEY = os.environ.get("PROXY_KEY", "your_proxy_key_here")
@app.route("/", methods=["GET"])
def index():
return {"status": "ok", "message": "License API Proxy"}
@app.route("/<path:path>", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
def proxy(path):
"""代理所有请求到 Cloudflare Worker"""
# 验证代理密钥(从 header 或 query 获取)
proxy_key = request.headers.get("X-Proxy-Key") or request.args.get("proxy_key")
if proxy_key != PROXY_KEY:
return {"success": False, "error": "unauthorized", "message": "Invalid proxy key"}, 401
# 构建目标 URL
target_url = f"{WORKER_URL}/{path}"
# 获取查询参数(排除 proxy_key)
query_params = {k: v for k, v in request.args.items() if k != "proxy_key"}
if query_params:
query_string = "&".join(f"{k}={v}" for k, v in query_params.items())
target_url += f"?{query_string}"
# 准备请求头
headers = {
"Content-Type": request.content_type or "application/json",
}
try:
# 转发请求
if request.method == "GET":
resp = requests.get(target_url, headers=headers, timeout=30)
elif request.method == "POST":
resp = requests.post(target_url, headers=headers, data=request.get_data(), timeout=30)
elif request.method == "PUT":
resp = requests.put(target_url, headers=headers, data=request.get_data(), timeout=30)
elif request.method == "DELETE":
resp = requests.delete(target_url, headers=headers, timeout=30)
elif request.method == "OPTIONS":
# CORS 预检请求
return Response(
"",
status=200,
headers={
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
}
)
else:
return {"error": "Method not allowed"}, 405
# 返回响应
return Response(
resp.content,
status=resp.status_code,
headers={
"Content-Type": resp.headers.get("Content-Type", "application/json"),
"Access-Control-Allow-Origin": "*",
}
)
except requests.Timeout:
return {"success": False, "error": "timeout", "message": "请求超时"}, 504
except requests.RequestException as e:
return {"success": False, "error": "proxy_error", "message": str(e)}, 502
except Exception as e:
return {"success": False, "error": "server_error", "message": str(e)}, 500
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860)