如何使用Python Hug获取请求头

5
在一个被注释为 hug api 调用的函数中,如何获取该调用的头信息?
2个回答

4

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

@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)}

3

创建一个自定义指令[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}

1
不需要为此创建任何指令,hug会将请求作为参数提供。 - danius
谢谢@danigosa。从文档中我没有弄明白这一点,但现在完全可以理解了。 - monty0
使用Hug的一个缺点是它的文档不够完善,没有记录。有时我认为他们花费更多的时间在颜色、CSS和图像上,而不是放置代码示例,希望他们将来能改进这一点。 - danius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接