Search code examples
cookiesheaderflask-restful

flask-restful, how to access cookies within Response classes (add_resource)


My program is built on flask-restful, i.e. for every url we have a class like this:

class TestAPI(Resource):
    def __init__(self, **kwargs):
        self.__main_loop = kwargs['main_loop']
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('testKey', type=str, required=True, help='No textKey provided', location='json')
        super(TestAPI, self).__init__()

    def get(self):
        try:
            logger.info("Test get")
            return {"testAnswer": "Test Value"}

        except Exception as e:
            logger.error(e)
            return e

    def post(self):
        try:
            logger.info("Test post")

            args = self.reqparse.parse_args()
            logger.info("Items: " + str(args.items()))

            return args
        except Exception as e:
            logger.error(e)
            return e

which gets added like this:

self.__webserver_rest_api.add_resource(TestAPI, '/api/v1.0/test/', resource_class_kwargs=kwargs)

Everything is working fine, I get the parameters as expected, but I am not able to figure out how to access the cookies sent within the get or post request. I do not even know how to access the headers. I just can't find anything within the docs nor did I find any examples. All examples use the "normal API", where we have a proper request object.

For clarity: I do know how to set and create cookies and headers when building a response, that's no an issue here.


Solution

  • You can use the request object to get the headers and cookies

    from flask import request
    headers = request.headers
    cookies = request.cookies
    

    both of them return an dict.