7

Flask和requests做一个简单的请求代理

 3 years ago
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实现定时任务并且通知

Nginx设置Referer来防止盗图

Graphviz dot简明教程

jQuery简明教程

Python RQ(Redis Queue)添加gevent支持

读《超级运营术》- 如何做社区?

技术人,光有技术是不行的

搭建aria2服务器

使用shairport-sync搭建airplay音频服务器

VirtManager Windows自适应屏幕

使用btrfs组建RAID1

Swagger? 不好用

Golang/Python最佳实践

读《毛泽东选集》

GORM源码阅读与分析




About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK