你会如何格式化这样的Python dict的Auth / OAuth标头?

时间:2013-11-05 17:31:34

标签: python twitter oauth xauth

我正在使用python-requests来使用xAuth及其私钥从Twitter获取access_token。目前,问题是我不知道如何格式化此标题:

  

授权:OAuth oauth_consumer_key =“key_here”,oauth_nonce =“72393267”,oauth_signature =“signature_here”,oauth_signature_method =“HMAC-SHA1”,oauth_timestamp =“1383672378”,oauth_version =“1.0”

目前我将其格式化如下:

  

{'授权':'OAuth',            'oauth_consumer_key':'dWW6V8isvSGRL4qbElrGw',            'oauth_nonce':params ['oauth_nonce'],            'oauth_signature':'',            'oauth_signature_method':'HMAC-SHA1',            'oauth_timestamp':params ['oauth_timestamp'],            'oauth_version':'1.0'            }

1 个答案:

答案 0 :(得分:1)

事实证明,我只需要把它放在一个字符串中(记住 ORDER IS EVERYTHING ,如果键/值不按顺序则不起作用)。标题如下所示

  

OAuth oauth_consumer_key =“consumer_key”,oauth_nonce =“61959852”,oauth_signature =“signature”,oauth_signature_method =“HMAC-SHA1”,oauth_timestamp =“1383694192”,oauth_version =“1.0”

我这么简单的代码如下:

def auth_header(creds, http_session):
    auth = 'OAuth ' + 'oauth_consumer_key=\"' + creds['oauth_consumer_key']
    auth = auth + '\",oauth_nonce=\"' + creds['oauth_nonce']
    auth = auth + '\",oauth_signature=\"' + creds['oauth_signature']
    auth = auth + '\",oauth_signature_method=\"' + creds['oauth_signature_method']
    auth = auth + '\",oauth_timestamp=\"' + creds['oauth_timestamp']
    auth = auth + '\",oauth_version=\"' + creds['oauth_version'] + '\"'
    http_session.headers['Authorization'] = auth