了解基本的Python Google API示例
在我之前关于StackOverflow的一个问题中,我提到尝试让GoogleJava示例代码工作,但在意识到这些示例是多么不受欢迎之后,我放弃了尝试。由于大约4年前我涉猎过python,我决定看看Google Blogger API for python 虽然大多数API调用都有意义,但我似乎无法使此示例正确运行 以下是我尝试运行的示例:了解基本的Python Google API示例,python,google-api,blogger,Python,Google Api,Blogger,在我之前关于StackOverflow的一个问题中,我提到尝试让GoogleJava示例代码工作,但在意识到这些示例是多么不受欢迎之后,我放弃了尝试。由于大约4年前我涉猎过python,我决定看看Google Blogger API for python 虽然大多数API调用都有意义,但我似乎无法使此示例正确运行 以下是我尝试运行的示例: #!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 Google Inc. Al
#!/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和客户端密钥填充了该文件,但是,我不知道该示例应该如何获取当前blogger用户的数据,因为似乎没有用于选择用户、输入电子邮件地址或类似内容的输入。该服务显然获得了当前用户,但实际上似乎没有这样做
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
/usr/local/ceral/python/2.7.11/Frameworks/python.framework/Versions/2.7/bin/python2.7/google-api-python-client-master/samples/blogger/blogger.py
此用户的显示名称为:未知
回溯(最近一次呼叫最后一次):
文件“/google-api-python-client-master/samples/blogger/blogger.py”,第83行,在
主(系统argv)
文件“/google-api-python-client-master/samples/blogger/blogger.py”,主文件第62行
对于thisusersblogs['items']中的博客:
KeyError:“项”
进程已完成,退出代码为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流,您将被重定向并需要进行身份验证(至少在您第一次运行此流时)
运行此命令将返回所有帖子,如下所示:
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
从基础开始,例如:
检索博客
您可以通过发送HTTP来检索特定博客的信息
获取对博客URI的请求。博客的URI包含以下内容
格式:
根据您使用的pyton版本,您可以导入不同的库来执行您的请求,例如。
从
这应该是一个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": ""
}
}
您可能想查看添加一个使用Python客户端库使用Google drive的基本工作示例 Python客户端库建议 我将添加另一个将GoogleDrive与python客户端库结合使用的示例 首先,我强烈建议使用使OAuth过程更容易的库(使用pip安装:
pip安装PyDrive
)
更多详情请参阅
如何运行与Google drive交互的基本python代码? 1)转到API控制台,制作您自己的项目 2)搜索“Google Drive API”,选择条目,然后单击“启用” 3)从左侧菜单中选择“凭据”,单击“创建凭据”,选择“OAuth客户端ID” 4)现在,需要设置产品名称和同意屏幕->单击“配置同意屏幕”,然后按照说明操作。完成后: a。选择“应用程序类型”作为Web应用程序 b。输入适当的名称 c。输入<代码>http://localhost:8080用于
授权的JavaScript源代码
d。输入<代码>http://localhost:8080/用于授权重定向URI
e。单击“创建”
5)点击客户端ID右侧的“下载JSON”下载Client\u secret\u.JSON
下载的文件包含应用程序的所有身份验证信息
将文件重命名为“client_secrets.json”,并将其放在工作目录中
基本代码示例 添加代码并运行它-例如,返回根目录中所有文件的基本代码:
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的图像:
我更新了我的问题,添加了更多关于客户机密的信息,这些信息似乎没有提及用户ID。我将尝试在这部分代码中输入userId,谢谢!示例代码来自这里:。由于某些原因,他们的文档对我来说并不直接,所以希望你的建议能奏效!不幸的是,更改“self”引用实际上导致http请求中断。顺便说一下,感谢您对Http请求的深入了解!我刚刚在学校完成了一个处理http请求的项目,所以这也很有帮助。也许我只是对这个示例期望过高,因为我从文档中收集到它已经为我创建了http请求。我刚刚添加了blogger API参考指南,这是您真正想要使用的。我开始怀疑blogger API是否真的是我想要实现的目标。我的项目包括获取一个博客URL列表,并获取与这些博客相关的所有帖子数据。也许有可能,但我不确定。我仍然很想让示例代码正常工作,就像
{
"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": ""
}
}
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']))