使用flask和requests实现http代理服务器

代码:

# -*- coding: utf-8 -*-
from contextlib import closing
import requests
from flask import Flask, request, Response

app = Flask(__name__)


@app.before_request
def before_request():
    url = request.url
    method = request.method
    data = request.data or request.form or None
    headers = dict()
    for name, value in request.headers:
        if not value or name == 'Cache-Control':
            continue
        headers[name] = value

    with closing(
        requests.request(method, url, headers=headers, data=data, stream=True)
    ) as r:
        resp_headers = []
        for name, value in r.headers.items():
            if name.lower() in ('content-length', 'connection',
                                'content-encoding'):
                continue
            resp_headers.append((name, value))
        return Response(r, status=r.status_code, headers=resp_headers)

app.run(port=8007, debug=True)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 实际环境 系统环境 macOS Sierra(10.12.5) Apache Apache/2.4.25 (Uni...
    boborz阅读 19,191评论 1 23
  • 昨天很晚才到达的青岛,第一次带孩子坐飞机,还是挺坎坷的。先是因为天气原因,在机场延误三个多小时,小家伙因为第一次到...
    D055小倩阅读 1,215评论 0 0
  • 致自己: 2016年,辛苦了整整一年,该好好地谢谢自己。 谢谢自己,面对压力的时候,能坚持下来。 谢谢自己,受到伤...
    玲珑煦暖的阳光阅读 2,271评论 0 0
  • 原文地址:http://www.cnblogs.com/powertoolsteam/p/MVC_knowledg...
    寒剑飘零阅读 12,724评论 5 170
  • 自以为那样就会很爽很痛快的方式在别人看来不过就是小孩子的不成熟脾性和愚蠢的方式罢了,何必以卵击石呢!
    感动在暹罗阅读 1,261评论 0 0