1

我在Google的一個git倉庫中發現了一些關於bigquery插入的示例代碼。應用程序引擎上線程安全的客戶端庫(python)

https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/bigquery/main.py

如果你看到的app.yaml它說這個代碼應該是線程安全的,但如果我在客戶端的lib的文檔(https://developers.google.com/api-client-library/python/guide/thread_safety)lokking它不應該是線程安全的。我現在有點困惑,我的下面的代碼是線程安全的還是不是? 它運行在應用程序引擎標準環境中。

import pprint 

from googleapiclient.discovery import build 
from oauth2client.client import GoogleCredentials 


credentials = GoogleCredentials.get_application_default() 

# Create the bigquery api client 
service = build('bigquery', 'v2', credentials=credentials) 

response = service.datasets().list(projectId='PROJECTID').execute() 

pprint.pprint(response) 

---- ----更新添 的回答後,我改變了我的代碼如下。這個現在應該是好的:

import pprint 

from googleapiclient.discovery import build 
from oauth2client.contrib.appengine import AppAssertionCredentials 
import httplib2 


credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/bigquery') 


# Create the bigquery api client 
service = build('bigquery', 'v2') 


def get(): 
    # authorize http object with client credentials 
    http = credentials.authorize(httplib2.Http()) 
    response = service.datasets().list(projectId='PROJECTID').execute(http=http) 

    pprint.pprint(response) 

回答

1

如果你讀的文檔就引用它說

在谷歌的API的Python客戶端庫是建立在httplib2的 庫之上,這是不線程安全的。因此,如果您以多線程應用程序的形式運行,則您發出請求 的每個線程必須具有自己的httplib2.Http()實例。

然後他們繼續告訴你如何做到這一點。如果你按照說明,那麼是的,它會。

您的示例代碼過於簡單,不試圖什麼是在文檔

# Create a new Http() object for every request 
    def build_request(http, *args, **kwargs): 
    new_http = httplib2.Http() 
    return apiclient.http.HttpRequest(new_http, *args, **kwargs) 
    service = build('api_name', 'api_version', requestBuilder=build_request) 

    # Pass in a new Http() manually for every request 
    service = build('api_name', 'api_version') 
    http = httplib2.Http() 
    service.stamps().list().execute(http=http) 

概述所以,如果你在一個線程的情況下想你的代碼,它不會是線程安全的。 如果您只是從REPL嘗試該代碼,那麼我懷疑您處於線程狀態。

+1

請你看看更新嗎?謝謝 –

相關問題