2016-06-08 62 views
2

我提到試圖讓谷歌Java示例代碼工作在我以前的問題之一StackOverflow,但放棄了試圖做到這一點後,實現瞭如何不贊成樣品。大約四年前,由於我大概涉足python,因此我決定看看Google的Blogger API for Python。瞭解基本的Python谷歌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__ = '[email protected]oogle.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

示例代碼是自我解釋:

#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) 

也許你想開始使用b基礎請求,而不是代碼示例,以熟悉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 

這應該retunr一個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

+0

我更新了我的問題,包括對CLIENT_SECRETS的詳細信息,這似乎並沒有遏制任何對userIds的引用。我會嘗試在代碼的那一部分輸入userId,謝謝!示例代碼來自https://github.com/google/google-api-python-client/tree/master/samples/blogger。由於某種原因,他們的文檔並不是直截了當的,所以希望您的建議能夠奏效! – tatertot

+0

不幸的是,改變'self'引用實際上導致了一個錯誤的http請求。順便說一句,感謝您對Http請求的洞察!我剛剛在學校完成了一個使用http請求的項目,所以這也很有幫助。也許我只是期待太多這個樣本,因爲我從文檔中收集到它已經爲我創建了http請求。 – tatertot

+0

我剛剛添加了博客API參考指南,這是您真正想要使用的版本 – glls