在我的Django web应用程序中,我有一个向google的youtube api发出请求的函数,这个函数每次用户提交表单时都会被执行,下面是代码:
import googleapiclient.discovery
def myFunc():
youtube = googleapiclient.discovery.build(
api_service_name, api_version, developerKey=api_key)
request = youtube.search().list(
part="id",
maxResults=25,
q="surfing",
)
youtube_api_response = request.execute()
for object in youtube_api_response["items"]:
# my logic here
现在使用以下方法构建api客户端
googleapiclient.discovery.build(api_service_name, api_version, developerKey=api_key)
因此,每次用户提交表单时,这样的构建都需要大量的时间,并且会减慢网站的速度。是否有一种方法可以以某种方式存储此构建,或者每次重复使用相同的构建,而不需要一次又一次地构建以提高性能。
发布于 2022-09-18 18:23:16
我的建议是有一个你的客户的单一实例。然后,可以将该客户端传递给您想要使用的函数。更好的是,将客户端封装在自己的类中,只需从它调用函数即可。例如:
import googleapiclient.discovery
class GoogleClient:
def __init__(self):
self.api_service_name = "name"
self.api_key = "key"
self.api_version = "version"
self.client = googleapiclient.discovery.build(
self.api_service_name, self.api_version, developerKey=self.api_key)
def search(self, q):
request = self.client.search().list(
part="id",
maxResults=25,
q=q,
)
youtube_api_response = request.execute()
for object in youtube_api_response["items"]:
print("do whatever")
client = GoogleClient()
client.search("query")
https://stackoverflow.com/questions/73765327
复制相似问题