【问题标题】:How can I get request headers with python hug如何使用 python hug 获取请求标头
【发布时间】:2017-08-01 21:53:58
【问题描述】:

在一个被注解为一个 hug api 调用的函数中,我怎样才能获得该调用的标头?

【问题讨论】:

    标签: python hug


    【解决方案1】:

    简单、正常和最快的方法:如果 requestbody (POST) 作为参数 (https://github.com/timothycrosley/hug/issues/120) 存在,Hug 会提供它们。

    @hug.get('/headers', output=hug.output_format.json)
    def headers(request, header_name: hug.types.text=None):
        if header_name is None:
            return request.headers
        return {header_name: request.get_header(header_name)}
    

    【讨论】:

      【解决方案2】:

      创建自定义指令 [1]:

      @hug.directive()
      def headers(request=None, **kwargs):
          """Returns the request"""
          return request and request.headers
      

      要使用它,请在前面加上魔术hug_ 前缀:

      @hug.post('/sns/test')
      def sns_test(hug_headers):
          message_type = 'X-AMZ-SNS-MESSAGE-TYPE'
          is_subscription = message_type in hug_headers \
                            and hug_headers[message_type] == 'SubscriptionConfirmation'
          return {'is_sub': is_subscription}
      

      【讨论】:

      • 不需要为此创建任何指令,如果作为参数存在,Hub 会提供请求
      • 谢谢@danigosa。我无法从文档中弄清楚这一点,但它非常有意义。
      • 使用拥抱的一个缺点是它的文档很差,没有文档记录。有时我认为他们在颜色、css 和图像上花费的时间比放置代码示例的时间要多,我希望他们在未来改进这一点
      猜你喜欢
      • 2016-03-21
      • 1970-01-01
      • 2013-11-16
      • 2019-02-02
      • 1970-01-01
      • 2022-08-07
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多