【问题标题】:How to store access_token for more requests on API (Python)如何存储 access_token 以获取更多 API 请求(Python)
【发布时间】:2017-11-15 00:15:53
【问题描述】:

我正在通过 Python 的“请求”模块发出 API 请求。我得到了 access_token,它是一个不记名令牌。 我已将令牌放入这样的变量中:

def get_token():
    url = 'https://myapiurl.com/oauth/token'
    payload = {'username':'myusername', 'password':'mypassword'}
    headers = {'Content-Type': 'application/json', 'origin': 'https://blabla.com'}
    r = requests.post(url, data=json.dumps(payload),headers=headers)
    mytoken = r.json()['token_type']
    mytokentype = r.json()['access_token']
    token_param = str(mytoken) + ' ' + str(mytokentype)
    return token_param

输出是一个具有这种结构的字符串:

Bearer eyJ0eXAiOiJKV1QiLCJhb.....0sImF6cCI6ImVCOEdI

对于需要此 access_token 的以下 GET 请求,我需要此结构。我不想每次发出新的 GET 请求时都获得新的令牌。

我不知道如何:

1:存储一个access_token

2:检查access_token是否有效

3:使用此令牌在我的 API 上发出其他 GET 请求。

非常感谢您的任何建议。

【问题讨论】:

  • 一种解决方案是将 access_token 保存在全局变量中(如果您不使用任何数据库),然后将其与所有 get 请求一起使用,直到它过期。到期后,发出请求时会给出相应的错误,收到此错误后再次调用 `get_token()' 函数获取新令牌。
  • 是的,这有帮助,谢谢。将令牌存储在全局变量complete_tokenresult_accesstoken = result["access_token"] result_tokentype = result["token_type"] complete_token = str(result_tokentype) + " " + str(result_accesstoken) 使用该变量作为参数值:headers = {"Authorization": complete_token, "X-User-Groups": "app_create", "Content-Type": "application/json" }我现在可以使用此令牌发出其他 GET 请求。您知道如何检查请求是否有效(以及可能需要哪个模块)?
  • 发出请求并检查响应,这几乎就是全部。使用 Graph API Explorer 探索您可以从 API 中获得的一切。阅读 FB API 文档。

标签: python api python-requests access-token


【解决方案1】:

我的回答:

我已将 POST 请求的全部输出放入变量 result。 我的令牌的结构必须是这样的:“Bearer tokenstring”。 所以我将类型放入变量result_tokentype,将令牌字符串放入变量result_accesstoken。 最后我把它们放在了变量accessToken中:

result_tokentype = result["token_type"]
result_accesstoken = result["access_token"]
accessToken = str(result_tokentype) + " " + str(result_accesstoken)

现在我有了正确结构中的完整字符串,我可以将此变量用于下一个请求,例如:

url = "https://myurl.com"
headers = {"Authorization": accessToken, "key1": "value1", "Content-Type": "application/json" }
conn.request("GET", url, headers=headers)

这里最适合我。

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 2019-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2021-05-07
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    相关资源
    最近更新 更多