【发布时间】: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_token:result_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