我正在使用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
但这是使用电子邮件&登录密码。我如何使用访问令牌?
答案 0 :(得分: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)
答案 1 :(得分: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")
希望这会有所帮助。