Python OAUTH2-使用请求的Fitbit_oauthlib
上下文 我正在编写一个python/django应用程序,它可以访问Fitbit数据 问题 要访问用户数据,我必须获取他们的令牌,可重复使用该令牌访问健身数据。下面介绍了当前的步骤Python OAUTH2-使用请求的Fitbit_oauthlib,python,django,Python,Django,上下文 我正在编写一个python/django应用程序,它可以访问Fitbit数据 问题 要访问用户数据,我必须获取他们的令牌,可重复使用该令牌访问健身数据。下面介绍了当前的步骤 1。首先,我向用户提供一个链接: def register_2(request): if request.user.is_authenticated(): oauth = OAuth2Session( auth_2_client_id,
1。首先,我向用户提供一个链接:
def register_2(request):
if request.user.is_authenticated():
oauth = OAuth2Session(
auth_2_client_id,
redirect_uri = redirect_uri,
scope = fitbit_scope)
authorization_url, state = oauth.authorization_url(fitbit_url_authorise_2)
return render_to_response('register.html',{
"authorization_url" : authorization_url
},context_instance=RequestContext(request))
return HttpResponseRedirect("/")
2。用户进入Fitbit,登录其帐户并授权访问。
3。然后,用户返回到我的站点,返回的代码应允许我获取令牌。
def callback_2(request):
if request.user.is_authenticated():
code = request.GET.get('code')
state = request.GET.get('state')
oauth = OAuth2Session(
client_id = auth_2_client_id,
redirect_uri = redirect_uri
)
token = oauth.fetch_token(
code = code,
token_url = fitbit_url_access_2,
authorization_response = request.build_absolute_uri()
)
调用callback_2
后,我得到错误:
(missing_token) Missing access token parameter.
资源:
找到了解决这个问题的方法。经过所有的努力研究,这很简单。以下是使用requests.post()
和base64.b64encode()
的自定义方法
使用python3,我需要在b64编码之前将client_id:client_secret字符串转换为utf-8,然后从utf-8解码回字符串。e、 例如,
toConvert=client_id+”:“+client_secret
,encoded=base64.b64encode(toConvert.encode(“utf-8”))。decode(“utf-8”)
,头={‘授权’:‘基本’+编码,
def callback_2(request):
if request.user.is_authenticated():
code = request.GET.get('code')
state = request.GET.get('state')
url = fitbit_url_access_2
data = "client_id=" + auth_2_client_id + "&" +\
"grant_type=" + "authorization_code" + "&" +\
"redirect_uri=" + redirect_uri_special + "&" +\
"code=" + code
headers = {
'Authorization': 'Basic ' + base64.b64encode(auth_2_client_id + ':' + consumer_secret),
'Content-Type': 'application/x-www-form-urlencoded'}
r = requests.post(url, data=data, headers=headers).json()