【问题标题】:flask-restful, how to access cookies within Response classes (add_resource)flask-restful,如何在响应类中访问 c​​ookie (add_resource)
【发布时间】:2021-06-11 08:49:28
【问题描述】:

我的程序是基于 flask-restful 构建的,即对于每个 url,我们都有一个这样的类:

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

这样添加的:

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

一切正常,我按预期获得了参数,但我无法弄清楚如何访问在 get 或 post 请求中发送的 cookie。我什至不知道如何访问标题。我只是在文档中找不到任何内容,也没有找到任何示例。所有示例都使用“普通 API”,其中我们有一个适当的请求对象。

为了清楚起见:我知道在构建响应时如何设置和创建 cookie 和标头,这里没有问题。

【问题讨论】:

  • 如果您来到这里并遇到同样的问题:self.reqparse.add_argument('Cookie_1', location='cookies') 在上面的示例中可以解决问题。在这里找到文档:flask-restful.readthedocs.io/en/latest/…

标签: cookies header flask-restful


【解决方案1】:

您可以使用request 对象来获取标头和cookie

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

他们都返回一个字典。

【讨论】:

  • 这似乎也有效。我在同一个 TestAPI.get 方法中使用并行运行的请求对此进行了测试,每个调用都有自己的请求实例。
猜你喜欢
  • 2022-08-20
  • 2012-06-13
  • 2010-09-11
  • 2018-06-14
  • 2016-05-10
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多