你们都看到了我是新来的。如果有什么问题就告诉我。
我在处理oauth2.0 (特别是获取访问令牌)时遇到了问题。
我现在正在使用这个代码:
#esse bloco serve para criar o access_token, e vai atualizar o access_token sempre, retornando ele para o principal
SCOPES = 'https://www.googleapis.com/auth/drive'
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# Esse bloco pode ser um problema para um server. É sempre preciso rodar esse bloco em um desktop para obter as chaves com autenticação.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Salva as credenciais para uma proxima vez
with open('token.json', 'w') as token:
token.write(creds.to_json())
a_file = open('token.json', "r")
tokens = json.load(a_file)
access_token = tokens['token']此代码存在一些问题:
有没有一种方法可以自动完成(不需要一个人)?以及如何使用此方法更新访问令牌?
编辑:
既然它是被指出的,下面是token.json通常的结果
{"token": "*******", "refresh_token": "*****", "token_uri": "********", "client_id": "*********************", "client_secret": "****************", "scopes": "https://www.googleapis.com/auth/drive", "expiry": "2021-09-17T15:45:39Z"}发布于 2021-09-20 11:57:47
第一部分
当第一个访问令牌过期时,它不再工作(因此令牌不会刷新)。
首先,请检查token.json并验证是否存储了刷新令牌。或者您可以查看下面的代码。
def initialize_drive():
"""Initializes the drive service object.
Returns:
drive an authorized drive service object.
"""
# Parse command-line arguments.
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[tools.argparser])
flags = parser.parse_args([])
# Set up a Flow object to be used if we need to authenticate.
flow = client.flow_from_clientsecrets(
CLIENT_SECRETS_PATH, scope=SCOPES,
message=tools.message_if_missing(CLIENT_SECRETS_PATH))
# Prepare credentials, and authorize HTTP object with them.
# If the credentials don't exist or are invalid run through the native client
# flow. The Storage object will ensure that if successful the good
# credentials will get written back to a file.
storage = file.Storage('drive.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
credentials = tools.run_flow(flow, storage, flags)
http = credentials.authorize(http=httplib2.Http())
# Build the service object.
drive = build('drive', 'v3', http=http)
return drive第二部分
有没有一种方法可以自动完成(不需要一个人)?以及如何使用此方法更新访问令牌?
是的,您可以使用服务帐户。服务帐户就像虚拟用户。一个服务帐户有自己的谷歌驱动器帐户,所以你可以上传和下载。您还可以像其他用户一样,与服务帐户共享个人驱动器帐户上的目录。然后,服务帐户将拥有上传和下载的权限。由于它是预先授权的,用户不需要同意它的访问。
注意:服务帐户只应在开发人员拥有的驱动器帐户上使用。如果您正在访问您的用户驱动器帐户,那么您应该使用Oauth2。
def initialize_drive():
"""Initializes an drive API V3 service object.
Returns:
An authorized Google Drive API V3 service object.
"""
credentials = ServiceAccountCredentials.from_json_keyfile_name(
KEY_FILE_LOCATION, SCOPES)
# Build the service object.
drive = build('drive', 'v3', credentials=credentials)
return analytics链接
https://stackoverflow.com/questions/69253735
复制相似问题