Home > Software engineering >  How to properly redirect a requests library response to a flask response?
How to properly redirect a requests library response to a flask response?

Time:07-05

I want to redirect a response from the reqeusts library as a proper flask response. I want to save the body, status code and headers, coockies. In case of an error response I want to redirect this error as a flask response too.

I tried this. But ran into an error:

import requests
import flask

def f():
   resp = requests.get(...)
   return flask.Response(response=resp.json(), status=resp.status_code, headers=resp.headers)

Error:

ValueError: too many values to unpack (expected 2)

CodePudding user response:

You could use flask's make_response, from its documentation:

Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers.

your code would have to change to:

def f():
    resp = requests.get(...)
    flask_resp = Response(response=resp.text)
    for key, value in resp.headers.items():
        flask_resp.headers[key] = value

    return flask_resp

UPDATE regarding cookies

the above code as is, doesnt set the cookies. from curl client i can see an error:

< Transfer-Encoding: chunked
< 
* Illegal or missing hexadecimal sequence in chunked-encoding
* Closing connection 0
curl: (56) Illegal or missing hexadecimal sequence in chunked-encoding

meaning some of these headers is "corrupting" the headers Flask sends back. I tried to set header only for the set-cookie header, i.e:

def f():
    resp = requests.get(...)
    flask_resp = Response(response=resp.text)
    for key, value in resp.headers.items():
        if key == 'Set-Cookie':
            flask_resp.headers[key] = value

    return flask_resp

and then the cookies were populated in the browser. So, some of the other headers from the resp.headers.items() is causing the problem. You can play with it and isolate what and why is causing the problem.

  • Related