This repository has been archived on 2024-07-11. You can view files and clone it, but cannot push or open issues or pull requests.
proxyapi/app.py

74 lines
2.4 KiB
Python
Raw Normal View History

2024-01-15 11:33:52 +08:00
import requests
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/proxy', methods=['POST'])
def proxy():
"""
代理接口转发请求到指定的 URL
接受 JSON 格式的请求体其中应包含 URLHTTP 方法和其他可选参数
返回格式化的响应包含状态码消息释义和数据
"""
req_data = request.json
# 确保提供了 url 和 method
if 'url' not in req_data or 'method' not in req_data:
return jsonify({'status': 'error', 'msg': 'URL or Method not provided', 'data': {}}), 400
url = req_data['url']
method = req_data['method'].lower()
# 支持的请求方法
supported_methods = {'get', 'post', 'put', 'delete', 'patch'}
if method not in supported_methods:
return jsonify({'status': 'error', 'msg': 'Unsupported method', 'data': {}}), 400
# 提取请求参数
params = req_data.get('params', {})
data = req_data.get('data', {})
json_data = req_data.get('json', {})
headers = req_data.get('headers', {})
cookies = req_data.get('cookies', {})
timeout = req_data.get('timeout', 10)
allow_redirects = req_data.get('allow_redirects', True)
try:
# 使用 requests 发送请求
response = requests.request(method, url, params=params, data=data, json=json_data,
headers=headers, cookies=cookies, timeout=timeout,
allow_redirects=allow_redirects)
# 尝试解析 JSON如果不是 JSON 则保持原样
try:
response_json = response.json()
except ValueError:
response_json = {}
# 构建响应数据
response_data = {
'url': response.url,
'headers': dict(response.headers),
'status_code': response.status_code,
'text': response.text,
'json': response_json,
'cookies': requests.utils.dict_from_cookiejar(response.cookies)
}
return jsonify({
'status': 'success',
'msg': 'Request successful',
'data': response_data
}), response.status_code
except requests.RequestException as e:
# 请求过程中出现异常
return jsonify({
'status': 'error',
'msg': str(e),
'data': {}
}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)