如何使用python hug获取请求标头

时间:2017-08-01 21:53:58

标签: python hug

在一个注释为拥抱api调用的函数中,如何获取该调用的标题?

2 个答案:

答案 0 :(得分: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}

答案 1 :(得分:2)

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

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