Proxying to another web service with Flask

前端 未结 3 1614
日久生厌
日久生厌 2020-12-04 11:13

I want to proxy requests made to my Flask app to another web service running locally on the machine. I\'d rather use Flask for this than our higher-level nginx instance so

3条回答
  •  我在风中等你
    2020-12-04 11:46

    I spent a good deal of time working on this same thing and eventually found a solution using the requests library that seems to work well. It even handles setting multiple cookies in one response, which took a bit of investigation to figure out. Here's the flask view function:

    from flask import request, Response
    import requests
    
    def _proxy(*args, **kwargs):
        resp = requests.request(
            method=request.method,
            url=request.url.replace(request.host_url, 'new-domain.com'),
            headers={key: value for (key, value) in request.headers if key != 'Host'},
            data=request.get_data(),
            cookies=request.cookies,
            allow_redirects=False)
    
        excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
        headers = [(name, value) for (name, value) in resp.raw.headers.items()
                   if name.lower() not in excluded_headers]
    
        response = Response(resp.content, resp.status_code, headers)
        return response
    

提交回复
热议问题