了解基本 Python Google API 示例

Understanding Basic Python Google API Sample

我曾提到试图让 google java 示例代码在我之前关于 Whosebug 的一个问题中发挥作用,但在意识到这些示例被弃用的程度后放弃了尝试。自从大约 4 年前我涉足 python,我决定看一下 Google Blogger API for Python.

虽然大多数 API 调用都有意义,但我似乎无法将此示例正确地 运行!

这是我正在尝试的示例 运行:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Simple command-line sample for Blogger.

Command-line application that retrieves the users blogs and posts.

Usage:
  $ python blogger.py

You can also get help on all the command-line flags the program understands
by running:

  $ python blogger.py --help

To get detailed log output run:

  $ python blogger.py --logging_level=DEBUG
"""
from __future__ import print_function

__author__ = 'jcgregorio@google.com (Joe Gregorio)'

import sys

from oauth2client import client
from googleapiclient import sample_tools


def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv, 'blogger', 'v3', __doc__, __file__,
      scope='https://www.googleapis.com/auth/blogger')

  try:

      users = service.users()

      # Retrieve this user's profile information
      thisuser = users.get(userId='self').execute()
      print('This user\'s display name is: %s' % thisuser['displayName'])

      blogs = service.blogs()

      # Retrieve the list of Blogs this user has write privileges on
      thisusersblogs = blogs.listByUser(userId='self').execute()
      for blog in thisusersblogs['items']:
        print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))

      posts = service.posts()

      # List the posts for each blog this user has
      for blog in thisusersblogs['items']:
        print('The posts for %s:' % blog['name'])
        request = posts.list(blogId=blog['id'])
        while request != None:
          posts_doc = request.execute()
          if 'items' in posts_doc and not (posts_doc['items'] is None):
            for post in posts_doc['items']:
              print('  %s (%s)' % (post['title'], post['url']))
          request = posts.list_next(request, posts_doc)

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run'
      'the application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)

我在 PyCharm 和终端中都有 运行 这个示例,当代码编译和 运行 时(这比我能说的 Java 样本!)我似乎无法理解样本是从哪里获取信息的。

示例需要一个 client_secrets.json 文件,我在其中填充了从 Google API 控制台获得的客户端 ID 和客户端密钥,但是,我不知道如何该示例应该获取有关当前博客用户的数据,因为似乎没有 select 用户的输入,输入电子邮件地址或类似内容。该服务显然获得了当前用户,但实际上并没有这样做。

client_secrets.json:

{
  "web": {
    "client_id": "[[INSERT CLIENT ID HERE]]",
    "client_secret": "[[INSERT CLIENT SECRET HERE]]",
    "redirect_uris": [],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

事实上,在 运行 执行此代码时,我收到以下错误:

/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /google-api-python-client-master/samples/blogger/blogger.py
This user's display name is: Unknown
Traceback (most recent call last):
  File "/google-api-python-client-master/samples/blogger/blogger.py", line 83, in <module>
    main(sys.argv)
  File "/google-api-python-client-master/samples/blogger/blogger.py", line 62, in main
    for blog in thisusersblogs['items']:
KeyError: 'items'

Process finished with exit code 1

如果有人能帮助我理解我在理解这个示例的工作原理时遗漏了什么,我将不胜感激。我的 python 确实生锈了,但我希望尝试一下这个示例代码能帮助我再次使用它。

示例代码不言自明:

#libraries used to connect with googles api
from oauth2client import client
from googleapiclient import sample_tools


def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv, 'blogger', 'v3', __doc__, __file__,
      scope='https://www.googleapis.com/auth/blogger')

以上使用 Oath2 Flow,您被重定向并需要进行身份验证(至少在您第一次 运行 时)

 try:

      users = service.users()    #googleapiclient.discovery.Resource object

      # Retrieve this user's profile information
      thisuser = users.get(userId='self').execute()
      print('This user\'s display name is: %s' % thisuser['displayName'])

      blogs = service.blogs()   #googleapiclient.discovery.Resource object

 # Retrieve the list of Blogs this user has write privileges on
      thisusersblogs = blogs.listByUser(userId='self').execute()  #retrieves all blogs from the user (you = self) 
      for blog in thisusersblogs['items']:    #for loop that iterates over a JSON (dictionary) to get key value 'items'
        print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))

      posts = service.posts()    #googleapiclient.discovery.Resource object for posts

  # List the posts for each blog this user has
      for blog in thisusersblogs['items']:
        print('The posts for %s:' % blog['name'])  
        request = posts.list(blogId=blog['id'])     #uses #googleapiclient.discovery.Resource object for posts to get blog by id
        while request != None:
          posts_doc = request.execute()
          if 'items' in posts_doc and not (posts_doc['items'] is None):
            for post in posts_doc['items']:
              print('  %s (%s)' % (post['title'], post['url']))
          request = posts.list_next(request, posts_doc)

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run'
      'the application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)

运行这returns你所有的帖子如下:

This user's display name is: "something"
The blog named 'myTest' is at: http://BLOGNAME.blogspot.com/
The posts for myTest:
  POST NAME (http://BLOGNAME.blogspot.com/2016/06/postname.html)

也许您想从基本请求开始,而不是代码示例,以熟悉 API?

https://developers.google.com/blogger/docs/3.0/using#RetrievingABlog

从基础开始,例如:

Retrieving a blog

You can retrieve information for a particular blog by sending an HTTP GET request to the blog's URI. The URI for a blog has the following format:

https://www.googleapis.com/blogger/v3/blogs/blogId

根据您使用的 pyton 版本,您可以导入不同的库来执行您的请求,例如。 来自 http://docs.python-requests.org/en/master/user/quickstart/#make-a-request

import requests

r = requests.get('https://www.googleapis.com/blogger/v3/blogs/blogId')
print r.text

这应该返回一个 JSON :

{
  "kind": "blogger#blog",
  "id": "2399953",
  "name": "Blogger Buzz",
  "description": "The Official Buzz from Blogger at Google",
  "published": "2007-04-23T22:17:29.261Z",
  "updated": "2011-08-02T06:01:15.941Z",
  "url": "http://buzz.blogger.com/",
  "selfLink": "https://www.googleapis.com/blogger/v3/blogs/2399953",
  "posts": {
    "totalItems": 494,
    "selfLink": "https://www.googleapis.com/blogger/v3/blogs/2399953/posts"
  },
  "pages": {
    "totalItems": 2,
    "selfLink": "https://www.googleapis.com/blogger/v3/blogs/2399953/pages"
  },
  "locale": {
    "language": "en",
    "country": "",
    "variant": ""
  }
}

您可能想要查看 https://developers.google.com/blogger/docs/3.0/reference/#Blogs

添加使用 Google 驱动器和 Python 客户端库的基本工作示例。

Python 客户端库的推荐

我将添加另一个使用 google 驱动器和 python 客户端库的示例。

首先,我强烈建议使用 PyDrive 库,它使 OAuth 过程更加容易(使用 pip 安装:pip install PyDrive)。

here 中有更多详细信息。


如何 运行 与 Google 驱动器交互的基本 python 代码?

1 ) 转到 APIs 控制台并制作您自己的项目。

2 ) 搜索“Google Drive API”,select 条目,然后单击“启用”。

3 ) Select 左侧菜单中的“凭据”,单击“创建凭据”,select “OAuth 客户端 ID”。

4 ) 现在,需要设置产品名称和同意屏幕 -> 单击“配置同意屏幕”并按照说明进行操作。完成后:

一个。 Select“应用程序类型”为 Web 应用程序。

b。输入适当的名称。

c。输入 http://localhost:8080 for Authorized JavaScript origins.

d。输入 http://localhost:8080/ for Authorized redirect URIs.

e。点击“创建”。

5 ) 点击客户端ID右侧的“下载JSON”,下载client_secret_<long ID>.json
下载的文件包含您的应用程序的所有身份验证信息。
将文件重命名为“client_secrets.json”并将其放在您的工作目录中。


基本代码示例

添加您的代码并 运行 它 - 例如基本代码 returns 根目录中的所有文件:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()

drive = GoogleDrive(gauth)


# Auto-iterate through all files that matches this query
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
  print('title: %s, id: %s' % (file1['title'], file1['id']))

如果您在认证过程中收到403授权错误

您必须至少将您的 gmail 帐户添加为测试用户才能继续进行身份验证流程:


其他快照

步骤 4.c 和 4.d 的图像:

第 5 步的图片: