Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get request headers with python hug

Tags:

python

hug

In a function annotated as a hug api call, how can I get the headers for that call?

like image 389
monty0 Avatar asked Aug 01 '17 21:08

monty0


2 Answers

The easy, normal and fastest way: Hug provides request and body (POST) if they are present as arguments (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)}
like image 100
danius Avatar answered Sep 27 '22 22:09

danius


Create a custom directive [1]:

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

To use it, prepend the magic hug_ prefix:

@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}
like image 28
monty0 Avatar answered Sep 27 '22 21:09

monty0