()
This context opens a requests session and loads the youtube cookies file.
This context opens a requests session and loads the youtube cookies file.
This context opens a requests session and loads the youtube cookies file .
def youtube_session() -> Iterator[requests.Session]:
    """This context opens a requests session and loads the youtube cookies file."""

    pickle_file = os.path.join(settings.BASE_DIR, "config/youtube_cookies.pickle")
    session = requests.session()
    # Have yt-dlp deal with consent cookies etc to setup a valid session
    extractor = yt_dlp.extractor.youtube.YoutubeIE()
    extractor._downloader = yt_dlp.YoutubeDL()
    extractor.initialize()
    session.cookies.update(extractor._downloader.cookiejar)

    try:
        if os.path.getsize(pickle_file) > 0:
            with open(pickle_file, "rb") as f:
                session.cookies.update(pickle.load(f))
    except FileNotFoundError:
        pass

    headers = {"User-Agent": yt_dlp.utils.random_user_agent()}
    session.headers.update(headers)
    yield session

    with open(pickle_file, "wb") as f:
        pickle.dump(session.cookies, f)
def youtube_session ( ) -> Iterator [ requests . Session ] : pickle_file = os . path . join ( settings . BASE_DIR , "config/youtube_cookies.pickle" ) session = requests . session ( ) # Have yt-dlp deal with consent cookies etc to setup a valid session extractor = yt_dlp . extractor . youtube . YoutubeIE ( ) extractor . _downloader = yt_dlp . YoutubeDL ( ) extractor . initialize ( ) session . cookies . update ( extractor . _downloader . cookiejar ) try : if os . path . getsize ( pickle_file ) > 0 : with open ( pickle_file , "rb" ) as f : session . cookies . update ( pickle . load ( f ) ) except FileNotFoundError : pass headers = { "User-Agent" : yt_dlp . utils . random_user_agent ( ) } session . headers . update ( headers ) yield session with open ( pickle_file , "wb" ) as f : pickle . dump ( session . cookies , f )