7
Flask和requests做一个简单的请求代理
source link: https://jiajunhuang.com/articles/2020_09_27-flask_proxy.md.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Flask和requests做一个简单的请求代理
有的时候,我们需要做一些简单的代理工作,比如,把一个内部系统,通过已有的鉴权方式暴露出去。
代码如下:
# 代理接口
import logging
import requests
from flask import Blueprint, request, Response
proxy_bp = Blueprint("proxy_bp", __name__, url_prefix="/proxy")
BASE_URL = "代理目标地址"
def get_token():
return "已有系统的token获取"
@proxy_bp.route("/<path:url>", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
def proxy(url):
url = "{}/{}?{}".format(BASE_URL, url, request.query_string.decode("utf8"))
method = request.method
json_body = request.get_json()
headers = {"Authorization": "Bearer {}".format(get_token())}
resp = requests.request(method, url, json=json_body, headers=headers)
logging.info("proxy got result: %s", resp.text)
content_type = resp.headers.get("Content-Type", "text/html")
return Response(resp.text, status=resp.status_code, content_type=content_type)
当然,这个只支持JSON,不过改成支持form也不难。
关注公众号,获得及时更新
Crontab + Sendmail实现定时任务并且通知
Python RQ(Redis Queue)添加gevent支持
使用shairport-sync搭建airplay音频服务器
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK