Jupyter上第三方API的OAuth?

2024-04-30 06:10:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Jupyter笔记本上使用Python进行数据分析,并希望访问使用OAuth的第三方API(Mendeley)。过去Heroku上有一个手动生成令牌的服务器解决方案,但最近已经停止

这一定是一个非常常见的问题,但我找不到支持它的维护库。大多数PythonOAuth库仅用于服务器;有一个支持良好的JupyterHub OAuthenticator,但IFAICS使用OAuth的目的不同

ipyauth看起来是业务,但没有太多更新,也没有记录如何为新服务扩展它。这种情况通常意味着有更好的支持

请问目前维护的Jupyter Python第三方API库是什么


Tags: 目的服务器apiheroku笔记本jupyter手动解决方案
1条回答
网友
1楼 · 发布于 2024-04-30 06:10:34

好的,一个答案是只使用requests package,并每次复制和粘贴重定向的URL:

from requests_oauthlib import OAuth2Session
scope = 'all'
redirect_uri='http://localhost:8888/'
oauth = OAuth2Session('YourApplicationApiIdNumber', redirect_uri=redirect_uri, scope=scope)
authorization_url, state = oauth.authorization_url(
        "https://api.mendeley.com/oauth/authorize" )

print( 'Please go to %s to authorize access, and copy the final localhost URL' % authorization_url )
assert(False) # Stop processing until this is done.

。。。转换为一个变量:

authorization_response = 'http://localhost:8888/tree?TheStuffWereInterestedIn'

。。。然后从那里开始:

token = oauth.fetch_token(
        'https://api.mendeley.com/oauth/token',
        authorization_response=authorization_response.replace('http', 'https').replace(',',''),
        client_secret='YourClientSecret')
r = oauth.get('https://api.mendeley.com/documents?sort=last_modified&order=desc&limit=500', timeout=30)

您必须使用回调URL配置Mendeley应用程序接口。这是http://localhost:8888/ ,因为Jupyter可以在不丢失其他OAuth2参数的情况下显示这些内容。但请求OAuth实现不接受非https链接(也不接受Jupyter偶尔添加的尾随逗号),所以我们对其进行了篡改,如图所示

我想这种方法几乎适用于任何OAuth2API。当然,请求列表quite a few

相关问题 更多 >