我在一个小应用程序中结合了Dropbox和google驱动器,允许你选择一个Dropbox文件并将其上传到google驱动器但是我每次使用这个应用程序时都要复制两次授权码,这不是很舒服,如何在每次使用时都避免使用或获取授权码?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'me'
import dropbox
import httplib2
import pprint
from funciones import *
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow
import os
from aux import *
import requests
from StringIO import StringIO
#keys dropbox
app_key = 'mykey'
app_secret = 'mysecret'
#keys drive
CLIENT_ID = 'myid'
CLIENT_SECRET = 'mysecret'
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
#parte dropbox
authorize_url = flow.start()
print '1. Go to: ' + authorize_url
print '2. Click "Allow" (you might have to log in first)'
print '3. Copy the authorization code.'
code = raw_input("Enter the authorization code here: ").strip()
access_token, user_id = flow.finish(code)
client = dropbox.client.DropboxClient(access_token)
#print 'linked account: ', client.account_info()
folder_metadata = client.metadata('/')
#print "metadata:", folder_metadata
#print folder_metadata['contents'][0]['path']
print 'Archivos del directorio'
print '***********************'
for files in folder_metadata['contents']:
f = files['path']
print f[1:]
downloaded = raw_input("Introduzca el nobre del fichero que desea subir a google drive: ").strip()
f, metadata = client.get_file_and_metadata('/'+downloaded)
#print 'metadata: ', metadata['mime_type']
out = open(downloaded, 'wb')
out.write(f.read())
out.close()
#parte drive
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
# Path to the file to upload
FILENAME = downloaded
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)
# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)
drive_service = build('drive', 'v2', http=http)
# Insert a file
media_body = MediaFileUpload(FILENAME, mimetype=metadata['mime_type'], resumable=True)
body = {
'title': 'Subido desde dropbox',
'description': 'A test document',
'mimeType': metadata['mime_type']
}
file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)
retrieve_all_files(drive_service)
os.remove(downloaded)
答案 0 :(得分:3)
Google和Dropbox之间的故事有所不同。我对Dropbox方面更有信心(因为我在那里工作):
access_token, user_id = flow.finish(code)
,您就可以保存access_token
并在同一用户想要使用该应用时重复使用它。 (只需使用保存的令牌client = dropbox.client.DropboxClient(access_token)
。)