Python requests library how to pass Authorization header with single token

后端 未结 8 1102
暗喜
暗喜 2020-12-02 14:02

I have a request URI and a token. If I use:

curl -s \"\" -H \"Authorization: TOK:\"

etc., I get a 200 and vie

相关标签:
8条回答
  • 2020-12-02 14:50

    Requests natively supports basic auth only with user-pass params, not with tokens.

    You could, if you wanted, add the following class to have requests support token based basic authentication:

    import requests
    from base64 import b64encode
    
    class BasicAuthToken(requests.auth.AuthBase):
        def __init__(self, token):
            self.token = token
        def __call__(self, r):
            authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
            r.headers['Authorization'] = authstr
            return r
    

    Then, to use it run the following request :

    r = requests.get(url, auth=BasicAuthToken(api_token))
    

    An alternative would be to formulate a custom header instead, just as was suggested by other users here.

    0 讨论(0)
  • 2020-12-02 14:51

    You can also set headers for the entire session:

    TOKEN = 'abcd0123'
    HEADERS = {'Authorization': 'token {}'.format(TOKEN)}
    
    with requests.Session() as s:
    
        s.headers.update(HEADERS)
        resp = s.get('http://example.com/')
    
    0 讨论(0)
提交回复
热议问题