aipxy / app.py
lix02's picture
Create app.py
44d9ed4 verified
raw
history blame
2.07 kB
from flask import Flask, request, Response
import requests
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def proxy(path):
# 解析请求 URL
url = request.url
url_obj = requests.compat.urlparse(url)
# 默认目标主机为 chatgpt.com,若路径以 /assets 开头则切换为 cdn.oaistatic.com
target_host = 'chatgpt.com'
if url_obj.path.startswith('/assets'):
target_host = 'cdn.oaistatic.com'
new_url = url_obj._replace(netloc=target_host).geturl()
# 创建新的 Headers 对象,复制原始请求头
new_headers = dict(request.headers)
# 设置 User-Agent 为模拟无头浏览器的标识,这里结合了 Edge 和 HeadlessChrome 的特征
new_headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/92.0.4515.107 Safari/537.36 Edg/92.0.902.55'
# 添加额外的 HTTP 头信息以模拟无头浏览器的请求行为
new_headers['sec-ch-ua'] = '"Chromium";v="92", " Not A;Brand";v="99", "HeadlessChrome";v="92"'
new_headers['sec-ch-ua-mobile'] = '?0'
new_headers['sec-ch-ua-platform'] = '"Windows"'
new_headers['sec-fetch-site'] = 'none'
new_headers['sec-fetch-mode'] = 'navigate'
new_headers['sec-fetch-user'] = '?1'
new_headers['sec-fetch-dest'] = 'document'
# 构造新的请求,保留原有的 method、body(非 GET/HEAD 请求)
if request.method in ['GET', 'HEAD']:
resp = requests.request(request.method, new_url, headers=new_headers, allow_redirects=True)
else:
resp = requests.request(request.method, new_url, headers=new_headers, data=request.get_data(), allow_redirects=True)
# 创建响应对象
response = Response(resp.content, resp.status_code)
for key, value in resp.headers.items():
if key.lower() not in ['content-encoding', 'content-length', 'transfer-encoding', 'connection']:
response.headers[key] = value
return response
if __name__ == '__main__':
app.run(debug=True)