序列化和反序列化oauth2client.client.OAuth2Credentials文件

2024-05-19 10:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个对象,它是来自web服务的OAuth2授权的凭据。我想保存用户凭据,以便将来继续使用它们。我用的是Django。你知道吗

对象是:<oauth2client.client.OAuth2Credentials object at 0x104b47310>

我不确定如何将凭据字符串化,然后从字符串重新构建凭据对象。你知道吗

要求的样本代码:

#!/usr/bin/python

import httplib2

from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow


# Copy your credentials from the console
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'

# Check https://developers.google.com/webmaster-tools/search-console-api-original/v3/ for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/webmasters.readonly'

# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)

webmasters_service = build('webmasters', 'v3', http=http)

# Retrieve list of properties in account
site_list = webmasters_service.sites().list().execute()

# Filter for verified websites
verified_sites_urls = [s['siteUrl'] for s in site_list['siteEntry']
                       if s['permissionLevel'] != 'siteUnverifiedUser'
                          and s['siteUrl'][:4] == 'http']

# Printing the URLs of all websites you are verified for.
for site_url in verified_sites_urls:
  print site_url
  # Retrieve list of sitemaps submitted
  sitemaps = webmasters_service.sitemaps().list(siteUrl=site_url).execute()
  if 'sitemap' in sitemaps:
    sitemap_urls = [s['path'] for s in sitemaps['sitemap']]
    print "  " + "\n  ".join(sitemap_urls)

Tags: theinfromimportclienthttpurlfor
1条回答
网友
1楼 · 发布于 2024-05-19 10:28:10

可以使用pickle模块序列化和反序列化python对象。以下是未经测试的代码:

import pickle

# Store OAuth2Credentials to a file
with open(FILENAME, 'wb') as credentials_file:
    pickle.dump(credentials, credentials_file)

# Read OAuth2Credentials from file
with open(FILENAME, 'rb') as credentials_file:
   credentials = pickle.load(credentials_file)


相关问题 更多 >

    热门问题