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

请你看看更新吗?谢谢 –

相关问题