1

请看下面的代码:

@login_required
def dashboard(request):
    code = request.GET.get('code', '')
    payload = {
        "client_id" : settings.GITHUB_CLIENT_ID,
        "client_secret" : settings.GITHUB_CLIENT_SECRET,
        "code" : code,
        "state" : settings.STATE,
    }
    response = requests.post('https://github.com/login/oauth/access_token', params=payload)
    # final_response = requests.get('https://api.github.com/user', auth=GitHubTokenAuth(access_token))
    return HttpResponse(response)
    # authenticated_user = final_response.json()
    # return render(request, 'core/dashboard.html', {'authenticated_user':authenticated_user})

response变量返回的值类似于:

access_token=eiwfbvdsvefieebrferferwfreferfersfwrb&scope=a%20list%20of%20scopes&token_type=bearer

如何访问 的值,access_token以便我可以使用注释掉final_response变量的值?感谢期待!

4

1 回答 1

1

您可以使用以下parse_qs方法urllib

>>> from urllib.parse import parse_qs
>>> parse_qs(response.text)
{'access_token': ['eiwfbvdsvefieebrferferwfreferfersfwrb'], 'scope': ['a list of scopes'], 'token_type': ['bearer']}

请注意,您将为list每个键获得一个。要访问第一个元素,请使用以下语法:

>>> result = parse_qs(response.text)
>>> result['access_token'][0]
'eiwfbvdsvefieebrferferwfreferfersfwrb'
于 2018-09-21T03:16:56.627 回答