内容目录
需求原因
中东的一个客户提供的api是谷歌云函数地址
国内是无法访问谷歌服务的
所以请求需要在香港服务器中转转发给谷歌云函数
python脚本
from flask import Flask, request, Response, jsonify
import requests
from functools import partial
app = Flask(__name__)
# 定义目标 URL
TARGET_URLS = {
'forward1': 'https://asia-east2-xxxxxxxx.cloudfunctions.net',
'usr2': 'https://example.com/other_endpoint',
'another_endpoint': 'https://example.com/another_endpoint'
}
# 动态创建路由
for key, target_url in TARGET_URLS.items():
def create_route(key, target_url):
def forward_func(path):
# 打印请求内容
print(f"Received {request.method} request to {key}/{path}")
print(f"Request JSON data: {request.json if request.method == 'POST' or request.method == 'PUT' else request.args.to_dict()}")
# 发送请求到目标 URL
data = request.json if request.method == 'POST' or request.method == 'PUT' else request.args.to_dict()
headers = {'Content-Type': 'application/json'}
full_target_url = f"{target_url}/{path}"
if request.method == 'GET':
response = requests.get(full_target_url, params=data, headers=headers)
elif request.method == 'POST':
response = requests.post(full_target_url, json=data, headers=headers)
elif request.method == 'PUT':
response = requests.put(full_target_url, json=data, headers=headers)
# 打印返回内容
print(f"Response content: {response.content}")
return Response(response.content, status=response.status_code, content_type=response.headers.get('Content-Type'))
forward_func.__name__ = f'{key}_endpoint'
app.route(f'/{key}/<path:path>', methods=['GET', 'POST', 'PUT'])(forward_func)
create_route(key, target_url)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
#关键字+URL 使用ps : curl http://localhost:5000/forward1/some_path OR http://localhost:5000/usr2/another_path
近期评论