我提到尝试在我之前的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文件,我使用我的客户端ID和从Google API控制台获取的客户端机密密钥填充该文件,但是,我不知道该示例应如何获取当前数据博主用户,因为它似乎不是选择用户,输入电子邮件地址或类似内容的输入。该服务显然获得了当前用户,但实际上并没有这样做。
的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肯定是生锈的,但我希望玩这个示例代码可以帮助我再次使用它。
答案 0 :(得分:0)
示例代码是自解释的:
#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
从基础知识开始,例如:
检索博客
您可以通过发送HTTP来检索特定博客的信息 GET请求博客的URI。博客的URI具有以下内容 格式:
根据您使用的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
答案 1 :(得分:0)
添加了一个使用Python客户端库的Google驱动器的基本工作示例。
Python客户端库推荐
我将添加另一个示例,将google drive与python客户端库一起使用。
首先,我强烈建议使用PyDrive库,该库使OAuth流程更加容易(使用pip:pip install PyDrive
安装)。
here中的更多详细信息。
如何运行与Google驱动器进行交互的基本python代码?
1)转到API控制台并创建自己的项目。
2)搜索“ Google Drive API”,选择条目,然后单击“启用”。
3)从左侧菜单中选择“凭据”,点击“创建凭据”,然后选择“ OAuth客户端ID”。
4)现在,需要设置产品名称和同意屏幕->单击“配置同意屏幕”,然后按照说明进行操作。完成后:
a。选择“应用程序类型”作为Web应用程序。
b。输入适当的名称。
c。为http://localhost:8080
输入Authorized JavaScript origins
。
http://localhost:8080/
输入Authorized redirect URIs
。
e。点击“创建”。
5)单击客户端ID右侧的“下载JSON”以下载client_secret_<long ID>.json
。
下载的文件包含您应用程序的所有身份验证信息。
重命名文件为“ client_secret s .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步的图片: