File size: 3,468 Bytes
b755512 600896f 7b0995b 600896f b755512 600896f 0f07b0d b755512 0f07b0d b755512 0f07b0d b755512 0f07b0d 6145430 0f07b0d 6145430 0f07b0d b755512 0f07b0d b755512 6145430 b755512 0f07b0d 6145430 0f07b0d b755512 0f07b0d 600896f b755512 0f07b0d b755512 0f07b0d b755512 600896f 0f07b0d b755512 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
from flask import Flask, request, Response
import requests
import os
app = Flask(__name__)
# 代理的目标域名
TARGET_DOMAIN = "https://kusa.pics"
@app.route('/', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/<path:path>', methods=['GET', 'POST'])
def proxy(path):
"""
代理 POST 请求到目标域名,GET 请求返回运行状态。
"""
# 处理 GET 请求,直接返回 "api is running"
if request.method == 'GET':
return Response('api is running', status=200, headers={'Content-Type': 'text/plain; charset=utf-8'})
# 只允许 POST 请求进行代理
if request.method != 'POST':
return Response('Method Not Allowed', status=405, headers={'Allow': 'GET, POST'})
# 构造目标 URL
target_url = f"{TARGET_DOMAIN}/{path}"
if request.query_string:
target_url += f"?{request.query_string.decode()}"
try:
# 构造请求头
headers = dict(request.headers)
headers.pop('Host', None)
headers.pop('Content-Length', None)
# 发送代理请求
response = requests.request(
method=request.method,
url=target_url,
headers=headers,
data=request.get_data(),
stream=True,
allow_redirects=False
)
# 获取响应内容的编码,默认使用 UTF-8
encoding = response.encoding or 'utf-8'
content = response.content.decode(encoding, errors='replace')
# 构造响应头,排除特定头
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
response_headers = [(name, value) for (name, value) in response.headers.items()
if name.lower() not in excluded_headers]
# 设置 Content-Type
original_content_type = response.headers.get('Content-Type', 'text/plain')
if 'application/json' in original_content_type.lower():
content_type = 'application/json; charset=utf-8'
else:
content_type = f'text/plain; charset={encoding}'
# 构造响应
proxy_response = Response(content, response.status_code, headers=response_headers)
proxy_response.headers['Content-Type'] = content_type
# 添加 CORS 头
proxy_response.headers['Access-Control-Allow-Origin'] = '*'
proxy_response.headers['Access-Control-Allow-Methods'] = 'GET, POST'
proxy_response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
proxy_response.headers['Access-Control-Allow-Credentials'] = 'true'
return proxy_response
except requests.exceptions.RequestException as e:
print(f"代理请求出错: {e}")
return Response(f"代理服务器出错: {e}", status=500)
except Exception as e:
print(f"其他错误: {e}")
return Response(f"代理服务器出错: {e}", status=500)
@app.route('/', defaults={'path': ''}, methods=['PUT', 'DELETE', 'PATCH', 'OPTIONS'])
@app.route('/<path:path>', methods=['PUT', 'DELETE', 'PATCH', 'OPTIONS'])
def method_not_allowed(path):
"""
拒绝非 GET 和 POST 请求。
"""
return Response('Method Not Allowed', status=405, headers={'Allow': 'GET, POST'})
if __name__ == '__main__':
port = int(os.environ.get("PORT", 7860))
print(f"Flask 服务器已启动,监听 {port} 端口")
app.run(debug=True, host='0.0.0.0', port=port)
|