The code imports various libraries and modules to interact with the operating system, handle JSON data, build a web application, and make HTTP requests, and configures the Google API for YouTube. It defines functions to authorize and list live broadcasts using the YouTube API, sanitize file names, and maps function names to their corresponding functions in the module.
npm run import -- "list broadcasts"
import os
import re
import json
import flask
import requests
import_notebook("list live stream",
"globals("))
import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
HOME_DIR = os.environ.get("HOME") or os.environ.get("USERPROFILE")
def list_broadcasts():
credentials = youtube_authorize()
youtube = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials)
broadcasts = youtube.liveBroadcasts().list(part='id,snippet', mine=True).execute()
return broadcasts["items"]
# Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
#flask.session['credentials'] = credentials_to_dict(credentials)
#return flask.jsonify(**broadcasts)
def sanitize_filename(name):
"""Sanitize a string to be a valid filename."""
return re.sub(r"[^\w.-]", "_", name) # Replace invalid characters with "_"
__all__ = {
"list_broadcasts": list_broadcasts
}
import os
import re
import json
import logging
import google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery
import flask
import requests
from googleapiclient.discovery import build
# Set up logging
logging.basicConfig(level=logging.INFO)
# Set API constants
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
HOME_DIR = os.environ.get("HOME") or os.environ.get("USERPROFILE")
def sanitize_filename(name):
"""
Sanitize a string to be a valid filename.
Args:
name (str): The string to sanitize.
Returns:
str: The sanitized string.
"""
return re.sub(r"[^\w.-]", "_", name) # Replace invalid characters with "_"
def youtube_authorize():
"""
Authorize with the YouTube API.
Returns:
google.oauth2.credentials.Credentials: The authorized credentials.
"""
# Create a flow instance to handle authorization
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
'credentials.json',
SCOPES
)
# Prompt the user to grant the necessary permissions
flow.run_local_server(port=0)
# Save the credentials to a file
credentials = flow.credentials
# Save the credentials to the session
flask.session['credentials'] = credentials_to_dict(credentials)
return credentials
def list_broadcasts():
"""
List live YouTube broadcasts.
Returns:
list: A list of live broadcasts.
"""
# Check if we have already authorized with the YouTube API
if 'credentials' not in flask.session:
logging.info("No stored credentials found.")
return []
# Get the authorized credentials
credentials = youtube_authorize()
# Create a YouTube API client instance
youtube = build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
# Get the live broadcasts
broadcasts = youtube.liveBroadcasts().list(part='id,snippet', mine=True).execute()
# Return the live broadcasts
return broadcasts.get("items", [])
def credentials_to_dict(credentials):
"""
Convert credentials to a dictionary.
Args:
credentials (google.oauth2.credentials.Credentials): The credentials to convert.
Returns:
dict: The credentials as a dictionary.
"""
return {
'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'scopes': credentials.scopes
}
Code Breakdown
The code imports various libraries and modules, including:
os
for interacting with the operating systemre
for regular expressionsjson
for handling JSON dataflask
for building a web applicationrequests
for making HTTP requestsgoogle.oauth2.credentials
for handling Google OAuth credentialsgoogle_auth_oauthlib.flow
for Google OAuth flowgoogleapiclient.discovery
for interacting with the Google APIThe code defines several constants:
SCOPES
: a list of API scopes for the YouTube APIAPI_SERVICE_NAME
: the name of the API service (YouTube)API_VERSION
: the version of the API (v3)HOME_DIR
: the home directory of the user (determined by the HOME
or USERPROFILE
environment variables)The list_broadcasts
function:
youtube_authorize
function (not shown in this excerpt)liveBroadcasts().list
methodThe sanitize_filename
function:
The __all__
dictionary defines a mapping of function names to their corresponding functions in the module. In this case, the only function defined is list_broadcasts
.