首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我想使用Pycharm从python创建google工作表,但它不起作用。

我想使用Pycharm从python创建google工作表,但它不起作用。
EN

Stack Overflow用户
提问于 2022-07-12 19:55:42
回答 2查看 106关注 0票数 0

我试着用Pycharm中的python创建google,但我尝试了非常没有排除bug。在这里,我提交了我的完整代码并显示了我的错误结果。

代码语言:javascript
运行
复制
    # [START sheets_create]
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def create(title):
    """
    Creates the Sheet the user has access to.
    Load pre-authorized user credentials from the environment.
    TODO(developer) - See https://developers.google.com/identity
    for guides on implementing OAuth2 for the application.\n"
        """
    creds = 'conof.json'
    # pylint: disable=maybe-no-member
    try:
        service = build('sheets', 'v4', credentials=creds)
        spreadsheet = {
            'properties': {
                'title': title
            }
        }
        spreadsheet = service.spreadsheets().create(body=spreadsheet,
                                                    fields='spreadsheetId') \
            .execute()
        print(f"Spreadsheet ID: {(spreadsheet.get('spreadsheetId'))}")
        return spreadsheet.get('spreadsheetId')
    except HttpError as error:
        print(f"An error occurred: {error}")
        return error


if __name__ == '__main__':
    # Pass: title
    create("mysheet1")
    # [END sheets_create]

这是我从google开发站点中找到的默认代码,我在这里添加了我从google生成的json文件。我很难解决图书馆的错误,我使用的是windows平台。

我的错误是

代码语言:javascript
运行
复制
    C:\Users\pc\PycharmProjects\createShee\venv\Scripts\python.exe C:/Users/pc/PycharmProjects/createShee/mumu.py
Traceback (most recent call last):
  File "C:\Users\pc\PycharmProjects\createShee\mumu.py", line 37, in <module>
    create("mysheet1")
  File "C:\Users\pc\PycharmProjects\createShee\mumu.py", line 19, in create
    service = build('sheets', 'v4', credentials=creds)
  File "C:\Users\pc\PycharmProjects\createShee\venv\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\pc\PycharmProjects\createShee\venv\lib\site-packages\googleapiclient\discovery.py", line 298, in build
    service = build_from_document(
  File "C:\Users\pc\PycharmProjects\createShee\venv\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\pc\PycharmProjects\createShee\venv\lib\site-packages\googleapiclient\discovery.py", line 604, in build_from_document
    http = _auth.authorized_http(credentials)
  File "C:\Users\pc\PycharmProjects\createShee\venv\lib\site-packages\googleapiclient\_auth.py", line 124, in authorized_http
    return credentials.authorize(build_http())
AttributeError: 'str' object has no attribute 'authorize'

Process finished with exit code 1

请帮我解决这个项目。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-13 01:14:06

方法的凭据参数只能接受以下对象:

凭据: oauth2client.Credentials或google.auth.credentials.Credentials,用于身份验证的凭据。

创建凭据对象的一种简单方法是在Python Quickstart of Google 中使用身份验证。

只需遵循快速启动指南,将作用域更改为'https://www.googleapis.com/auth/spreadsheets',并将try-except块替换为创建电子表格中的try-以外块。

您的代码应该如下所示:

代码语言:javascript
运行
复制
from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

def create(title):
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    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)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('sheets', 'v4', credentials=creds)
        spreadsheet = {
            'properties': {
                'title': title
            }
        }
        spreadsheet = service.spreadsheets().create(body=spreadsheet,
                                                    fields='spreadsheetId') \
            .execute()
        print(f"Spreadsheet ID: {(spreadsheet.get('spreadsheetId'))}")
        return spreadsheet.get('spreadsheetId')
    except HttpError as error:
        print(f"An error occurred: {error}")
        return error


if __name__ == '__main__':
    create("mysheet1")

输出:

注释:确保安装“快速启动指南”中包含的必要包,下载凭据json文件,将其保存在与脚本相同的目录中,并将其重命名为credentials.json

参考资料:

票数 1
EN

Stack Overflow用户

发布于 2022-07-12 20:06:59

尝试将creds = 'conof.json'替换为

代码语言:javascript
运行
复制
credentials = google.oauth2.credentials.Credentials.from_authorized_user_file('conof.json)

并根据需要添加导入。

当前正在向credentials参数传递build中的字符串;但是,build希望将特定类型的凭据对象传递给它。可以使用上面的代码行从JSON文件中获取此凭据对象。有关更多细节,请参见这个答案

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72957715

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档