gpt4 book ai didi

python - 了解基本 Python Google API 示例

转载 作者:行者123 更新时间:2023-12-05 06:42:15 25 4
gpt4 key购买 nike

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

虽然大多数 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 和客户端 key 填充了该文件,但是,我看不到示例应该如何获取当前博客用户的数据,因为似乎没有用于选择用户、输入电子邮件地址或类似内容的输入。该服务显然获得了当前用户,但实际上并没有这样做。

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)

运行此命令会返回您的所有帖子,如下所示:

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

关于python - 了解基本 Python Google API 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com