http API requests are executed for more than 20 seconds

Viewed 39

I have an application on django that can search for YouTube videos via the YouTube Data API v3 and translate their description using the Yandex Translate API. Often everything works fine, both services respond normally. But about once every 10 calls, the request stretches for about 20 seconds. This happens with both translation and YouTube.

I look in the developer console, in the column "Waiting (Time to receive the first byte)" just these 20 seconds. I do not understand why this is so, it is unlikely that the problem is on the side of the services, because it is observed on both. But I can't figure out what my problem is then...

I tried to set DEBUG to False, it was advised somewhere. But the problem has not gone away.

Code of functions for receiving data from YouTube:

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os
import pickle

SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"]


def auth():
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
    api_service_name = "youtube"
    api_version = "v3"
    credentials_filename = "credentials.json"
    credentials = None
    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
        credentials = pickle.load(token)
    if not credentials or not credentials.valid:
        if credentials and credentials.expired and credentials.refresh_token:
            credentials.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(credentials_filename, SCOPES)
            credentials = flow.run_local_server(port=8000)
        with open("token.pickle", "wb") as token:
            pickle.dump(credentials, token)
    return build(api_service_name, api_version, credentials=credentials)

def search(youtube, **kwargs):
    return youtube.search().list(part="snippet", **kwargs).execute()

Their call code:

yt = auth()
response = search(yt, q=request.POST['search'], maxResults=20, type='video')['items']

Function code for Yandex API:

endpoint_url = 'https://translate.api.cloud.yandex.net/translate/v2/translate'
list_texts = [str(texts[key]) for key in texts]
body = {
    "targetLanguageCode": language,
    "texts": list_texts,
    "folderId": self.folder_id,
}
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer {0}".format(self.token)
}
response = requests.post(endpoint_url, json=body, headers=headers)
0 Answers
Related