4

我正在使用 gdata-pyton-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

但这是使用电子邮件和密码登录。如何使用访问令牌?

4

2 回答 2

1

请参阅此文档页面,指导您如何使用您的令牌,尤其是最后的示例:

# 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)
于 2013-02-22T15:58:09.610 回答
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")

希望这可以帮助。

于 2013-03-01T10:08:49.743 回答