如何通过 python 拥抱请求 headers

How can I get request headers with python hug

在注释为拥抱 api 调用的函数中,我怎样才能获得该调用的 headers?

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

简单、正常和最快的方法: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)}