2013-02-19 56 views
4

我正在使用gdata-pyton-client。 我有我的應用程序的「授權碼」。但現在呢?我如何使用它在博客中發佈?我有我的應用程序的「授權碼」。但是,如何使用它在使用gdata-python-client的博客中發佈?

我用下面的代碼,並得到誒授權碼,

CLIENT_ID = 'my-client-id' 
CLIENT_SECRET = 'my-secret' 

SCOPES = ['https://www.googleapis.com/auth/blogger'] 
USER_AGENT = 'my-app' 

token = gdata.gauth.OAuth2Token(
           client_id=CLIENT_ID, client_secret=CLIENT_SECRET, scope=' '.join(SCOPES), 
           user_agent=USER_AGENT) 

print token.generate_authorize_url(redirect_url='urn:ietf:wg:oauth:2.0:oob') 
print token.get_access_token(TOKEN-THAT-I-GOT-FROM-ABOVE-URL) 

但是現在我如何使用它?

我該如何授權博客發佈給博主? 我一直在使用這個例子對我的測試目的: https://code.google.com/p/gdata-python-client/source/browse/samples/blogger/BloggerExampleV1.py

但這是登錄使用電子郵件&密碼。我如何使用訪問令牌?

回答

1

你可以試試下面的解決方案。

請確保以下所有進口都在那裏。

from apiclient.discovery import build 
from oauth2client.file import Storage 
from oauth2client.client import AccessTokenRefreshError 
from oauth2client.client import flow_from_clientsecrets 
from oauth2client.tools import run 

設置你的client_secrets.json這樣

設置的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" 
    } 
} 

對於未來的參考,你可以存儲在一個文件blogger.dat證書更快的處理

FLOW = flow_from_clientsecrets(Path_to_client_secrets.json,scope='https://www.googleapis.com/auth/blogger',message=MISSING_CLIENT_SECRETS_MESSAGE) 

storage = Storage('blogger.dat') 
credentials = storage.get() 
if credentials is None or credentials.invalid: 
    credentials = run(FLOW, storage) 

一旦證書都完成設置。它的時間發佈!所以我們創建一個httplib2.Http對象來處理我們的HTTP請求,並使用我們良好的證書對它進行授權。

http = httplib2.Http() 
http = credentials.authorize(http) 

service = build("blogger", "v2", http=http) 

一旦完成我們所建立的博客體,並張貼

try: 
    body = { 
     "kind": "blogger#post", 
     "id": "6814573853229626501", 
     "title": "posted via python", 
     "content":"<div>hello world test</div>" 
     } 

    request = service.posts().insert(your_blogId_ID,body) 

    response = request.execute() 
    print response 

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

希望這會有所幫助。

+0

謝謝特拉維斯,我會試試這個,讓你知道結果.. – 2013-03-01 12:47:09

+0

它是否適合你? – 2013-03-08 21:56:55

1

this documentation page指導你如何使用您的令牌,特別是例如在最後:

# Find a token to set the Authorization header as the request is being made 
token = self.token_store.find_token(url) 
# Tell the token to perform the request using the http_client object 
# By default, the http_client is an instance of atom.http.HttpClient which uses httplib to   make requests 
token.perform_request(self.http_client, 'GET', url, data=None, headers) 
+0

jknupp,感謝這個例子,但我對Python編程非常新,這也是我第一次使用GData。我仍然不明白如何授權客戶端,以便它可以發佈到博客... – 2013-02-23 18:03:10

相關問題