在 Python 脚本中调用 OAUTH2 API



我在这里找到了这篇有趣的文章 https://developer.byu.edu/docs/consume-api/use-api/oauth-20/oauth-20-python-sample-code 在本文中,有一个如何使用authorization_code流调用 OAuth2 API 的示例。这种方法的问题在于您需要打开一个新的浏览器,获取代码并粘贴到脚本中。我会直接从 Python 脚本中打开并获取代码。可能吗?

print "go to the following url on the browser and enter the code from the 
returned url: "
print "---  " + authorization_redirect_url + "  ---"
access_token = raw_input('access_token: ')

我今天一直在与同样的问题作斗争,发现以下内容对我有用。您将需要:

  1. 一个接口编号
  2. 密钥
  3. 访问令牌网址

然后我用了requests_oauthlib:https://github.com/requests/requests-oauthlib

from requests_oauthlib import OAuth2Session
# Both id and secret should be provided by whoever owns the api
myid = 'ID_Supplied'
my_secret = 'Secret_pass'
access_token_url = "https://example.com/connect/token" # suffix is also an example
client = BackendApplicationClient(client_id=myid)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(token_url=access_token_url, client_id=myid, 
client_secret=my_secret)
print(token)

最新更新