实际任务是什么?
我试图从我的google appengine标准项目中访问google Apps API(Drive API,Sheets API)。因此,当提交表单时,它必须创建一个新的google工作表并将表单的内容写入工作表,然后工作表必须存储在与Google服务帐户或授权的电子邮件帐户关联的Google驱动器中(即,我们在授权电子邮件部分中提供的电子邮件帐户)
我实际尝试过什么?
我已使用google_auth
库来获取appengine的默认凭据,并且已在我的gae项目控制台上启用了两个驱动器,工作表API。
from googleapiclient import discovery
from google.auth import app_engine
from google.auth.transport.requests import AuthorizedSession
import httplib2
def creat_sample_sheet():
credentials = app_engine.Credentials()
http = AuthorizedSession(credentials)
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
result = service.spreadsheets().values()
print result
但它不起作用..这是我得到的tracback ......
File "/base/data/home/apps/vidyalay/1.397393333574060152/alumni_registration_dateycollege/sheet_handler.py" in creat_sample_sheet
30. discoveryServiceUrl=discoveryUrl)
File "/base/data/home/apps/vidyalay/1.397393333574060152/lib/oauth2client/_helpers.py" in positional_wrapper
133. return wrapped(*args, **kwargs)
File "/base/data/home/apps/vidyalay/1.397393333574060152/lib/googleapiclient/discovery.py" in build
222. cache)
File "/base/data/home/apps/vidyalay/1.397393333574060152/lib/googleapiclient/discovery.py" in _retrieve_discovery_doc
269. resp, content = http.request(actual_url)
Exception Type: TypeError at /alumni_dateycollege/sheet/
Exception Value: request() takes at least 3 arguments (2 given)
不知道我走在正确的道路上......
更新
通过跟随Daniel提到的this链接为我工作。但我不知道如何查看创建的电子表格。
这是我尝试下载创建的工作表。
service.spreadsheets().get(spreadsheetId=SHEET_ID, alt='media')
但这会为https://sheets.googleapis.com/v4/spreadsheets/1awnM7z_aomHx833Z5S_Z-agFusaidmgcCa0FJIFyGE8?alt=json
创建一个获取请求
网址。但实际上我想将media
传递给alt
参数而不是json
。我尝试了上述方法,但它没有成功。
答案 0 :(得分:2)
我设法自己解决了这个问题。
我已经使用我的Google服务帐户在服务帐户的google驱动器上创建电子表格(将表单存储到Google驱动器的工作表API)。然后我将该特定文件的编写者角色权限授予我自己的gmail id。现在,我可以在google驱动器中查看该特定表单。
from googleapiclient import discovery
import cloudstorage as gcs
# from oauth2client import client
# from oauth2client.contrib import appengine
# from google.appengine.api import memcache
import httplib2
from google.appengine.api import memcache
from oauth2client.contrib.appengine import AppAssertionCredentials
import logging
import os
import io
from googleapiclient.http import MediaIoBaseDownload
logger = logging.getLogger(__name__)
credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/spreadsheets')
drive_credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/drive')
http = credentials.authorize(httplib2.Http(memcache))
drive_http = drive_credentials.authorize(httplib2.Http(memcache))
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
def callback(request_id, response, exception):
if exception:
# Handle error
print exception
else:
print "Permission Id: %s" % response.get('id')
def list_drive_files(drive_service):
results = drive_service.files().list(
pageSize=10).execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print('{0} ({1})'.format(item['name'], item['id']))
def give_file_permission(drive_service, file_id):
batch = drive_service.new_batch_http_request(callback=callback)
user_permission = {
'type': 'user',
'role': 'writer',
'emailAddress': 'foobar@gmail.com' # email address of the user you want to give permission
}
batch.add(drive_service.permissions().create(
fileId=file_id,
body=user_permission,
fields='id',
))
batch.execute()
def creat_sample_sheet():
# data = {'properties': {'title': 'Academic Sheet'}}
# res = sheet_service.spreadsheets().create(body=data).execute()
# SHEET_ID = res['spreadsheetId']
SHEET_ID = '1awnM7z_aomHx833Z5S_Z-agFusaidmgcCa0FJIFyGE8'
sheet = service.spreadsheets().get(spreadsheetId=SHEET_ID, includeGridData=True)
drive_service = discovery.build('drive', 'v3', http=drive_http)
list_drive_files(drive_service)
# Sharing a file
# file_id = '1bgvJdXG0eg2JGaNlIcdtde_XJlg2gAUT_DOzHi75zys'
def write_to_sheet(form):
logger.info('Inside write to sheet')
first_name = form.cleaned_data.get('first_name', '')
sur_name = form.cleaned_data.get('sur_name', '')
email = form.cleaned_data.get('e_mail', '')
phone_no = form.cleaned_data.get('mobile_phone', '')
year_of_passing = form.cleaned_data.get('year_of_passing', '')
present_occupation = form.cleaned_data.get('present_occupation', '')
present_city = form.cleaned_data.get('present_city', '')
courses_attended = ', '.join([str(i) for i in form.cleaned_data.get('courses_attended', '')])
volunteer = form.cleaned_data.get('volunteer', '')
fields = [ 'first_name', 'sur_name', 'e_mail', 'mobile_phone', 'year_of_passing', 'present_occupation', 'present_city', 'courses_attended' , 'volunteer' ]
# data = {'properties': {'title': 'Form Sheet'}}
# # create sheet
# res = service.spreadsheets().create(body=data).execute()
# # sheet_id = res['spreadsheetId']
sheet_id = '1bgvJdXG0eg2JGaNlIcdtde_XJlg2gAUT_DOzHi75zys'
# print sheet_id
# update sheet
data = {'values': [[first_name, sur_name, email, phone_no, year_of_passing, present_occupation,
present_city, courses_attended, volunteer]]}
service.spreadsheets().values().append(spreadsheetId=sheet_id,
range='A1', body=data, valueInputOption='RAW').execute()
# Getting rows
# rows = service.spreadsheets().values().get(spreadsheetId=sheet_id,
# range='Sheet1').execute().get('values', [])
# for row in rows:
# print row