问题
I am newbie to python and using Python Flask and generating REST API service.
I want to check authorization header which is sent the client.
But I can't find way to get HTTP header in flask.
Any help for getting HTTP header authorization is appreciated.
回答1:
from flask import request
request.headers.get('your-header-name')
request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:
request.headers['your-header-name']
回答2:
just note, The different between the methods are, if the header is not exist
request.headers.get('your-header-name')
will return None or no exception, so you can use it like
if request.headers.get('your-header-name'):
....
but the following will throw an error
if request.headers['your-header-name'] # KeyError: 'your-header-name'
....
You can handle it by
if 'your-header-name' in request.headers:
customHeader = request.headers['your-header-name']
....
回答3:
If any one's trying to fetch all headers that were passed then just simply use:
dict(request.headers)
it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy
来源:https://stackoverflow.com/questions/29386995/how-to-get-http-headers-in-flask