1

應用程序試圖通過服務帳戶的幫助,使用Google Apps Directory API獲取用戶信息列表(> 200個用戶)。通過Memcache高效使用Google API特定服務對象

if not memcache.get('directory_service'): 
    f = file(KEY_FILE, 'r') 
    key = f.read() 
    f.close() 

    credentials = SignedJwtAssertionCredentials(
     service_email, 
     key, 
     'https://www.googleapis.com/auth/admin.directory.user', 
     sub=GoogleAppAdminEmail) 
    http_auth = credentials.authorize(Http()) 

    directory_service = build('admin', 'directory_v1', http=http_auth) 
    memcache.set('directory_service', directory_service, 60 * 60 * 2) 
else: 
    directory_service = memcache.get('directory_service') 
user = directory_service.users().get(userKey=username).execute() 

我認爲這將是更好地保存directory_service對象在內存緩存以減少執行時間,從而使第二個請求開始應用程序將從內存緩存獲取對象。

但是我在執行Memcache後得到了HttpError 401

File "C:\Users\test\appcode\oauth2client\util.py", line 135, in positional_wrapper 

    return wrapped(*args, **kwargs) 

File "C:\Users\test\appcode\googleapiclient\http.py", line 723, in execute 

    raise HttpError(resp, content, uri=self.uri) 

HttpError: <HttpError 401 when requesting https://www.googleapis.com/admin/directory/v1/users/username%40mydomain.com?alt=json returned "Login Required"> 

什麼是處理這種情況的有效途徑?

回答

1

對存儲directory_service對象沒有興趣,因爲它是在不調用外部API的情況下創建的。

你應該存儲的是http_auth對象,因爲這個對象的生成成本很高。

此外,服務帳戶中的令牌每秒只能請求一定次數。我不認爲確切的限制是在某處記錄的,但如果您嘗試從同一個服務帳戶中同時生成太多令牌,則會出現Rate limit exceeded錯誤。

好的做法是將令牌存儲在某些共享存儲服務中。它可以是memcache或數據存儲。 Google API客戶端附帶您應該使用的an App Engine specific StorageByKeyName class。它由數據存儲支持,並使用Memcache作爲可選緩存層。

+0

即使我保存'http_auth'對象,我也遇到了同樣的錯誤。 – Rookie 2015-03-03 06:56:30

+0

我會迴應David所說的,存儲auth令牌本身比嘗試存儲執行auth流和請求的對象更健壯。對於你的使用模式(你實際上可能會碰到的)的最壞情況是醃製對象內的令牌將會過期,導致auth錯誤,但是你的應用仍然認爲它可以安全地抓取對象,因此不會需要生成一個新的。您可能需要存儲時間,直到令牌與對象一起到期,並且這可能會阻止問題,如果確實發生了這種情況。 – Nick 2015-05-22 16:40:33