Issue
In my Django web application i have this function that makes a request to google's youtube api, this function gets excuted each time a user submits a form Here is the code:
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
Now building the api client using
googleapiclient.discovery.build(api_service_name, api_version, developerKey=api_key)
So building this way each time a user submits a form will require a lot of time and slow down the website. Is there a way to store this build somehow or reuse the same one each time without the need of building again and again to improve the performance.
Solution
My suggestion would be to have a single instance of your client. You could then pass that client to the function you want to use. Even better, wrap your client in a class of its own and simply just call functions from that. Such as:
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")
Answered By - Brady R
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.