Ste*_*e-O 5 python python-3.x box-api boxapiv2
我正在尝试开始使用Box.com SDK,我有几个问题.
from boxsdk import OAuth2
oauth = OAuth2(
client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
store_tokens=your_store_tokens_callback_method,
)
auth_url, csrf_token = oauth.get_authorization_url('http://YOUR_REDIRECT_URL')
def store_tokens(access_token, refresh_token):
# store the tokens at secure storage (e.g. Keychain)
Run Code Online (Sandbox Code Playgroud)
1)什么是重定向网址以及如何使用它?我是否需要运行服务器才能使用它?
2)我在store_tokens方法中需要什么样的代码?
mro*_*haw 10
只有在您运行需要响应用户的身份验证请求的Web应用程序时,才需要重定向URL.如果您是通过编程进行身份验证,则可以将其设置为http:// localhost.在您需要用户手动进行身份验证的情况下,重定向URL应调用Web应用程序中的某些功能来存储和处理返回的身份验证代码.你需要运行服务器吗?好吧,如果你想对返回的身份验证代码做一些事情,你指定的URL应该在你的控制之下并调用代码来做一些有用的事情.
这是store_tokens
函数应该是什么样子的一个例子.它应该接受两个参数,access_token
和refresh_token
.在下面的示例中,函数将这些提交到本地存储,以便在API需要重新进行身份验证时使用:
从这里:
"""An example of Box authentication with external store"""
import keyring
from boxsdk import OAuth2
from boxsdk import Client
CLIENT_ID = 'specify your Box client_id here'
CLIENT_SECRET = 'specify your Box client_secret here'
def read_tokens():
"""Reads authorisation tokens from keyring"""
# Use keyring to read the tokens
auth_token = keyring.get_password('Box_Auth', 'mybox@box.com')
refresh_token = keyring.get_password('Box_Refresh', 'mybox@box.com')
return auth_token, refresh_token
def store_tokens(access_token, refresh_token):
"""Callback function when Box SDK refreshes tokens"""
# Use keyring to store the tokens
keyring.set_password('Box_Auth', 'mybox@box.com', access_token)
keyring.set_password('Box_Refresh', 'mybox@box.com', refresh_token)
def main():
"""Authentication against Box Example"""
# Retrieve tokens from secure store
access_token, refresh_token = read_tokens()
# Set up authorisation using the tokens we've retrieved
oauth = OAuth2(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
access_token=access_token,
refresh_token=refresh_token,
store_tokens=store_tokens,
)
# Create the SDK client
client = Client(oauth)
# Get current user details and display
current_user = client.user(user_id='me').get()
print('Box User:', current_user.name)
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
我建议看一下OAuth 2 教程。它将有助于更好地理解 OAuth 的工作原理以及各种参数的用途。
这是 Box 将发送可用于获取访问令牌的身份验证代码的 URL。例如,如果您的重定向 URL 设置为https://myhost.com
,那么您的服务器将收到一个 URL 类似于 的请求https://myhost.com?code=123456abcdef
。
请注意,您的重定向 URI 不需要是真实的服务器。例如,使用 WebView 的应用程序有时会输入虚假的重定向 URL,然后直接从 WebView 中的 URL 提取身份验证代码。
回调store_tokens
是可选的,但它可用于保存访问和刷新令牌,以防您的应用程序需要关闭。每次访问令牌和刷新令牌更改时都会调用它,让您有机会将它们保存到某个地方(磁盘、数据库等)。
然后,您可以稍后将这些令牌传递给OAuth2构造函数,以便您的用户不需要再次登录。