yuoop commited on
Commit
0f07b0d
·
verified ·
1 Parent(s): 4622128

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -64
app.py CHANGED
@@ -5,76 +5,77 @@ import os
5
  app = Flask(__name__)
6
 
7
  # 代理的目标域名
8
- TARGET_DOMAIN = "https://generativelanguage.googleapis.com"
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
- # 构造请求头
20
- headers = dict(request.headers)
21
- # 删除 Host 头,防止目标服务器出错
22
- headers.pop('Host', None)
23
- # 删除 Content-Length,让 requests 自动处理
24
- headers.pop('Content-Length', None)
25
-
26
-
27
- # 发送请求
28
- response = requests.request(
29
- method=request.method,
30
- url=target_url,
31
- headers=headers,
32
- data=request.get_data(), # 获取原始请求体
33
- stream=True, # 使用流式传输,处理大文件
34
- allow_redirects=False # 禁止重定向,让客户端处理
35
- )
36
-
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
- proxy_response = Response(response.raw.read(), # 使用 raw.read() 读取流式响应
44
- response.status_code,
45
- headers=response_headers)
46
-
47
- # 添加 CORS 头
48
- proxy_response.headers['Access-Control-Allow-Origin'] = '*'
49
- proxy_response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE, PATCH'
50
- proxy_response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
51
- proxy_response.headers['Access-Control-Allow-Credentials'] = 'true'
52
-
53
- return proxy_response
54
-
55
- except requests.exceptions.RequestException as e:
56
- print(f"代理请求出错: {e}")
57
- return Response(f"代理服务器出错: {e}", status=500)
58
-
59
- except Exception as e:
60
- print(f"其他错误: {e}")
61
- return Response(f"代理服务器出错: {e}", status=500)
62
-
 
 
63
 
64
  @app.after_request
65
  def after_request(response):
66
- """
67
- 处理 OPTIONS 请求,添加 CORS 头。
68
- """
69
- if request.method == 'OPTIONS':
70
- response.headers['Access-Control-Allow-Origin'] = '*'
71
- response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE, PATCH'
72
- response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
73
- response.headers['Access-Control-Allow-Credentials'] = 'true'
74
- return response
75
-
76
 
77
  if __name__ == '__main__':
78
- port = int(os.environ.get("PORT", 7860))
79
- print(f"Flask 服务器已启动,监听 {port} 端口")
80
- app.run(debug=True, host='0.0.0.0', port=port)
 
5
  app = Flask(__name__)
6
 
7
  # 代理的目标域名
8
+ TARGET_DOMAIN = "https://generativelanguage.googleapis.com"
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
+ # 构造请求头
20
+ headers = dict(request.headers)
21
+ # 删除 Host 头,防止目标服务器出错
22
+ headers.pop('Host', None)
23
+ # 删除 Content-Length,让 requests 自动处理
24
+ headers.pop('Content-Length', None)
25
+
26
+ # 发送请求
27
+ response = requests.request(
28
+ method=request.method,
29
+ url=target_url,
30
+ headers=headers,
31
+ data=request.get_data(), # 获取原始请求体
32
+ stream=True, # 使用流式传输,处理大文件
33
+ allow_redirects=False # 禁止重定向,让客户端处理
34
+ )
35
+
36
+ # 获取响应内容的编码,默认使用 UTF-8
37
+ encoding = response.encoding or 'utf-8'
38
+ content = response.content.decode(encoding, errors='replace') # 解码并替换无法解码的字符
39
+
40
+ # 构造响应
41
+ excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
42
+ response_headers = [(name, value) for (name, value) in response.headers.items()
43
+ if name.lower() not in excluded_headers]
44
+
45
+ proxy_response = Response(content, response.status_code, headers=response_headers)
46
+
47
+ # 设置 Content-Type,确保客户端正确解析
48
+ proxy_response.headers['Content-Type'] = f'text/plain; charset={encoding}'
49
+
50
+ # 添加 CORS
51
+ proxy_response.headers['Access-Control-Allow-Origin'] = '*'
52
+ proxy_response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE, PATCH'
53
+ proxy_response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
54
+ proxy_response.headers['Access-Control-Allow-Credentials'] = 'true'
55
+
56
+ return proxy_response
57
+
58
+ except requests.exceptions.RequestException as e:
59
+ print(f"代理请求出错: {e}")
60
+ return Response(f"代理服务器出错: {e}", status=500)
61
+
62
+ except Exception as e:
63
+ print(f"其他错误: {e}")
64
+ return Response(f"代理服务器出错: {e}", status=500)
65
 
66
  @app.after_request
67
  def after_request(response):
68
+ """
69
+ 处理 OPTIONS 请求,添加 CORS 头。
70
+ """
71
+ if request.method == 'OPTIONS':
72
+ response.headers['Access-Control-Allow-Origin'] = '*'
73
+ response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS, PUT, DELETE, PATCH'
74
+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
75
+ response.headers['Access-Control-Allow-Credentials'] = 'true'
76
+ return response
 
77
 
78
  if __name__ == '__main__':
79
+ port = int(os.environ.get("PORT", 7860))
80
+ print(f"Flask 服务器已启动,监听 {port} 端口")
81
+ app.run(debug=True, host='0.0.0.0', port=port)