gpt4 book ai didi

python - 应用引擎上的线程安全客户端库(Python)

转载 作者:行者123 更新时间:2023-12-03 12:59:47 25 4
gpt4 key购买 nike

我在Google的git存储库之一中找到了一些有关bigquery插入的示例代码。

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

如果您看到app.yaml,则说该代码应该是线程安全的,但是如果我浏览了客户端库的文档(https://developers.google.com/api-client-library/python/guide/thread_safety),则它应该不是线程安全的。我现在有些困惑,我的以下代码是否是线程安全的?
它在App Engine Standard Env上运行。

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)

最佳答案

如果您阅读引用的文档,它会说

The google-api-python-client library is built on top of the httplib2 library, which is not thread-safe. Therefore, if you are running as a multi-threaded application, each thread that you are making requests from must have its own instance of 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中的代码,那么我怀疑您是否处于线程状态。

关于python - 应用引擎上的线程安全客户端库(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37806753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com