yuoop commited on
Commit
b755512
·
verified ·
1 Parent(s): 7b0995b

Update app.py

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