|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | + |
| 3 | +import os |
| 4 | + |
| 5 | +import flask |
| 6 | +import google.oauth2.credentials |
| 7 | +import google_auth_oauthlib.flow |
| 8 | +import googleapiclient.discovery |
| 9 | + |
| 10 | +# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains |
| 11 | +# the OAuth 2.0 information for this application, including its client_id and |
| 12 | +# client_secret. |
| 13 | +CLIENT_SECRETS_FILE = "client_secret.json" |
| 14 | + |
| 15 | +# This OAuth 2.0 access scope allows for full read/write access to the |
| 16 | +# authenticated user's account and requires requests to use an SSL connection. |
| 17 | +SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] |
| 18 | +API_SERVICE_NAME = 'youtube' |
| 19 | +API_VERSION = 'v3' |
| 20 | + |
| 21 | +app = flask.Flask(__name__) |
| 22 | +# Note: A secret key is included in the sample so that it works, but if you |
| 23 | +# use this code in your application please replace this with a truly secret |
| 24 | +# key. See http://flask.pocoo.org/docs/0.12/quickstart/#sessions. |
| 25 | +app.secret_key = 'REPLACE ME - this value is here as a placeholder.' |
| 26 | + |
| 27 | + |
| 28 | +@app.route('/') |
| 29 | +def index(): |
| 30 | + if 'credentials' not in flask.session: |
| 31 | + return flask.redirect('authorize') |
| 32 | + |
| 33 | + # Load the credentials from the session. |
| 34 | + credentials = google.oauth2.credentials.Credentials( |
| 35 | + **flask.session['credentials']) |
| 36 | + |
| 37 | + client = googleapiclient.discovery.build( |
| 38 | + API_SERVICE_NAME, API_VERSION, credentials=credentials) |
| 39 | + return channels_list_by_username(client, |
| 40 | + part='snippet,contentDetails,statistics', |
| 41 | + forUsername='GoogleDevelopers') |
| 42 | + |
| 43 | + |
| 44 | +@app.route('/authorize') |
| 45 | +def authorize(): |
| 46 | + # Create a flow instance to manage the OAuth 2.0 Authorization Grant Flow |
| 47 | + # steps. |
| 48 | + flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( |
| 49 | + CLIENT_SECRETS_FILE, scopes=SCOPES) |
| 50 | + flow.redirect_uri = flask.url_for('oauth2callback', _external=True) |
| 51 | + authorization_url, state = flow.authorization_url( |
| 52 | + # This parameter enables offline access which gives your application |
| 53 | + # both an access and refresh token. |
| 54 | + access_type='offline', |
| 55 | + # This parameter enables incremental auth. |
| 56 | + include_granted_scopes='true') |
| 57 | + |
| 58 | + # Store the state in the session so that the callback can verify that |
| 59 | + # the authorization server response. |
| 60 | + flask.session['state'] = state |
| 61 | + |
| 62 | + return flask.redirect(authorization_url) |
| 63 | + |
| 64 | + |
| 65 | +@app.route('/oauth2callback') |
| 66 | +def oauth2callback(): |
| 67 | + # Specify the state when creating the flow in the callback so that it can |
| 68 | + # verify the authorization server response. |
| 69 | + state = flask.session['state'] |
| 70 | + flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( |
| 71 | + CLIENT_SECRETS_FILE, scopes=SCOPES, state=state) |
| 72 | + flow.redirect_uri = flask.url_for('oauth2callback', _external=True) |
| 73 | + |
| 74 | + # Use the authorization server's response to fetch the OAuth 2.0 tokens. |
| 75 | + authorization_response = flask.request.url |
| 76 | + flow.fetch_token(authorization_response=authorization_response) |
| 77 | + |
| 78 | + # Store the credentials in the session. |
| 79 | + # ACTION ITEM for developers: |
| 80 | + # Store user's access and refresh tokens in your data store if |
| 81 | + # incorporating this code into your real app. |
| 82 | + credentials = flow.credentials |
| 83 | + flask.session['credentials'] = { |
| 84 | + 'token': credentials.token, |
| 85 | + 'refresh_token': credentials.refresh_token, |
| 86 | + 'token_uri': credentials.token_uri, |
| 87 | + 'client_id': credentials.client_id, |
| 88 | + 'client_secret': credentials.client_secret, |
| 89 | + 'scopes': credentials.scopes |
| 90 | + } |
| 91 | + |
| 92 | + return flask.redirect(flask.url_for('index')) |
| 93 | + |
| 94 | +def print_response(response): |
| 95 | + if response: |
| 96 | + return flask.jsonify(**response) |
| 97 | + else: |
| 98 | + return ('This request does not return a response. For these samples, ' + |
| 99 | + 'this is generally true for requests that delete resources, ' + |
| 100 | + 'such as <code>playlists.delete()</code>, but it is also ' + |
| 101 | + 'true for some other methods, such as <code>videos.rate()</code>.') |
| 102 | + |
| 103 | +# Build a resource based on a list of properties given as key-value pairs. |
| 104 | +# Leave properties with empty values out of the inserted resource. |
| 105 | +def build_resource(properties): |
| 106 | + resource = {} |
| 107 | + for p in properties: |
| 108 | + # Given a key like "snippet.title", split into "snippet" and "title", where |
| 109 | + # "snippet" will be an object and "title" will be a property in that object. |
| 110 | + prop_array = p.split('.') |
| 111 | + ref = resource |
| 112 | + for pa in range(0, len(prop_array)): |
| 113 | + is_array = False |
| 114 | + key = prop_array[pa] |
| 115 | + |
| 116 | + # For properties that have array values, convert a name like |
| 117 | + # "snippet.tags[]" to snippet.tags, and set a flag to handle |
| 118 | + # the value as an array. |
| 119 | + if key[-2:] == '[]': |
| 120 | + key = key[0:len(key)-2:] |
| 121 | + is_array = True |
| 122 | + |
| 123 | + if pa == (len(prop_array) - 1): |
| 124 | + # Leave properties without values out of inserted resource. |
| 125 | + if properties[p]: |
| 126 | + if is_array: |
| 127 | + ref[key] = properties[p].split(',') |
| 128 | + else: |
| 129 | + ref[key] = properties[p] |
| 130 | + elif key not in ref: |
| 131 | + # For example, the property is "snippet.title", but the resource does |
| 132 | + # not yet have a "snippet" object. Create the snippet object here. |
| 133 | + # Setting "ref = ref[key]" means that in the next time through the |
| 134 | + # "for pa in range ..." loop, we will be setting a property in the |
| 135 | + # resource's "snippet" object. |
| 136 | + ref[key] = {} |
| 137 | + ref = ref[key] |
| 138 | + else: |
| 139 | + # For example, the property is "snippet.description", and the resource |
| 140 | + # already has a "snippet" object. |
| 141 | + ref = ref[key] |
| 142 | + return resource |
| 143 | + |
| 144 | +# Remove keyword arguments that are not set |
| 145 | +def remove_empty_kwargs(**kwargs): |
| 146 | + good_kwargs = {} |
| 147 | + if kwargs is not None: |
| 148 | + for key, value in kwargs.iteritems(): |
| 149 | + if value: |
| 150 | + good_kwargs[key] = value |
| 151 | + return good_kwargs |
| 152 | + |
| 153 | +def channels_list_by_username(client, **kwargs): |
| 154 | + kwargs = remove_empty_kwargs(**kwargs) # See full sample for function |
| 155 | + response = client.channels().list( |
| 156 | + **kwargs |
| 157 | + ).execute() |
| 158 | + |
| 159 | + return print_response(response) |
| 160 | + |
| 161 | + |
| 162 | + |
| 163 | +if __name__ == '__main__': |
| 164 | + # When running locally, disable OAuthlib's HTTPs verification. When |
| 165 | + # running in production *do not* leave this option enabled. |
| 166 | + os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' |
| 167 | + app.run('localhost', 8090, debug=True) |
0 commit comments