我得到了应用的“授权码”。但如何使用它通过gdata-python-client在Blogger上发帖?

4 投票
2 回答
678 浏览
提问于 2025-04-17 16:24

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

不过这个例子是用邮箱和密码登录的。我该如何使用访问令牌呢?

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

希望这对你有帮助。

撰写回答