python - 如何从appengine访问Google Apps API?

标签 python google-app-engine google-sheets-api

实际任务是什么?

我正在尝试从我的 google appengine 标准项目访问 google Apps API(Drive API、Sheets API)。因此,当提交表单时,它必须创建一个新的谷歌工作表并将表单的内容写入该工作表,然后该工作表必须存储在与谷歌服务帐户或授权电子邮件帐户关联的谷歌驱动器中(即,我们在授权电子邮件部分提供的电子邮件帐户)

我实际上尝试了什么?

我已使用 google_auth 库获取 appengine 的默认凭据,并在我的 gae 项目控制台上启用了 Drive、Sheets 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)

不知道我走在正确的道路上..

更新

关注this丹尼尔提到的链接对我有用。但我不知道如何查看创建的电子表格。

这是我尝试下载创建的工作表。

service.spreadsheets().get(spreadsheetId=SHEET_ID, alt='media')

但这会创建一个对 https://sheets.googleapis.com/v4/spreadsheets/1awnM7z_aomHx833Z5S_Z-agFusaidmgcCa0FJIFyGE8?alt=json 的获取请求 网址。但我实际上想将 media 传递给 alt 参数而不是 json。我尝试了上面的方法,但不起作用。

最佳答案

我自己设法解决了这个问题。

我已使用我的 Google 服务帐户在服务帐户的 Google 驱动器上创建电子表格(工作表 API 负责将工作表存储到 Google 驱动器)。然后我将该特定文件的作者角色权限授予我自己的 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

关于python - 如何从appengine访问Google Apps API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40860402/

相关文章:

python - 在 pypy 翻译期间指定安装的 native 库路径

python - ,= 在 python 中是什么意思?

python - pandas 使用日期时间对象重新索引 DataFrame

python - 如何使用 webDriver(python)最大化 chrome 中的窗口

java - 从 MySQL 导出表并导入到 Google Sheet

google-sheets-api - batchUpdate 调用如何计入使用限制?

mysql - 如何从 Google 云 SQL 调用或导入表到 Spark 数据框?

安卓应用引擎java : authenticating users

java - App Engine Java 单元测试环境设置

python - 使用 python/pandas 将数据框写入谷歌表格