每5秒使用python将文本文件上传到谷歌驱动器

时间:2014-08-29 20:37:02

标签: google-app-engine python-2.7 text-files google-oauth google-drive-api

如何修改以下python代码,每5秒将ecg.txt上传到谷歌驱动器,我更新此文本文件。代码现在每次上传文件时都要求Oauth,我希望它只在第一次请求身份验证。

#!/usr/bin/python

import httplib2
import pprint

from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow


# Copy your credentials from the console
CLIENT_ID = XXXXXX
CLIENT_SECRET = XXXXX

# 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 = 'ecg.txt'

# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, 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='text/plain', resumable=True)
body = {
  'title': 'My document',
  'description': 'A test document',
  'mimeType': 'text/plain'
}

file = drive_service.files().insert(body=body, media_body=media_body).execute()
pprint.pprint(file)

1 个答案:

答案 0 :(得分:0)

如果您使用如下面的视频中所示的装饰器,它会将您的访问令牌存储在数据库中,并在需要时处理刷新。

https://www.youtube.com/watch?v=HoUdWBzUZ-M

https://developers.google.com/api-client-library/python/guide/google_app_engine

from oauth2client.appengine import OAuth2Decorator

decorator = OAuth2Decorator(client_id=CLIENT_ID, 
                            client_secret=CLIENT_SECRET,
                            scope=OAUTH_SCOPE,
                            callback_path=REDIRECT_URI)


class MainPage(webapp2.RequestHandler):

    @decorator.oauth_required #Simply place this above any function that requires login.
    def get(self):