pythonflaskgoogle-apiandroid-management-apigoogle-auth-library

I cant get my flask application authenticated through google and apis usable


im quite new to coding but this is barely documented so i need some help. Im building a flask application but I cant get the google auth flow working. Im using Pycharm and python version 3.9

My issues are : I cant find any beginner tutorial that explains how to go through the Auth flow.

I dont understand how to interact with google APis through flask. (i want to use the android-management-api)

I do understand that i need to create a service object but that only works when i can authenticate the google flow and this is where im already stuck for 5 days now.

I already followed the instructions from realpython and MattButton. when trying these instructions i keep getting errors. now im getting:

Error: While importing 'app', an ImportError was raised:

Traceback (most recent call last):
  File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\lib\site-packages\flask\cli.py", line 256, in locate_app
    __import__(module_name)
  File "C:\000 Projects\Applications\PY\flaskProjects\MDM\app.py", line 5, in <module>
    from flask_oauth import OAuth
  File "C:\000 Projects\Applications\PY\flaskProjects\MDM\venv\lib\site-packages\flask_oauth.py", line 13, in <module>
    from urlparse import urljoin
ModuleNotFoundError: No module named 'urlparse'


Process finished with exit code 2

Can somebody explain me what im doing wrong

my code is below:

from flask import Flask, redirect, url_for, session, request, jsonify, render_template
from datetime import datetime

from flask import Flask, redirect, url_for, session
from flask_oauth import OAuth
import urllib.parse


# You must configure these 3 values from Google APIs console
# https://code.google.com/apis/console
GOOGLE_CLIENT_ID = ''
GOOGLE_CLIENT_SECRET = ''
REDIRECT_URI = '/authorized'  # one of the Redirect URIs from Google APIs console

SECRET_KEY = 'development key'
DEBUG = True

app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()

google = oauth.remote_app('google',
                          base_url='https://www.google.com/accounts/',
                          authorize_url='https://accounts.google.com/o/oauth2/auth',
                          request_token_url=None,
                          request_token_params={'scope': 'https://www.googleapis.com/auth/androidmanagement',
                                                'response_type': 'code'},
                          access_token_url='https://accounts.google.com/o/oauth2/token',
                          access_token_method='POST',
                          access_token_params={'grant_type': 'authorization_code'},
                          consumer_key=GOOGLE_CLIENT_ID,
                          consumer_secret=GOOGLE_CLIENT_SECRET)


@app.route('/')
def index():
    access_token = session.get('access_token')
    if access_token is None:
        return redirect(url_for('login'))

    access_token = access_token[0]

    from urllib.request import Request, urlopen
    from urllib.error import URLError

    headers = {'Authorization': 'OAuth '+access_token}
    req = Request('https://www.googleapis.com/oauth2/v1/userinfo',
                  None, headers)
    try:
        res = urlopen(req)
    except URLError as e:
        if e.code == 401:
            # Unauthorized - bad token
            session.pop('access_token', None)
            return redirect(url_for('login'))
        return res.read()

    return res.read()


@app.route('/login')
def login():
    callback = url_for('authorized', _external=True)
    return google.authorize(callback=callback)


@app.route(REDIRECT_URI)
@google.authorized_handler
def authorized(resp):
    access_token = resp['access_token']
    session['access_token'] = access_token, ''
    return redirect(url_for('index'))


@google.tokengetter
def get_access_token():
    return session.get('access_token')


@app.route('/home')
def home():
    return render_template(
        'index.html',
        title='Home Page',
        year=datetime.now().year,
    )


@app.route('/devices')
def devices():
    return render_template(
        'devices.html',
        title='Devices',
        year=datetime.now().year,
    )


@app.route('/policies')
def policies():
    return render_template(
        'policies.html',
        title='Policies',
        year=datetime.now().year,
    )


@app.route('/enterprises')
def enterprises():
    return render_template(
        'enterprises.html',
        title='Enterprises',
        year=datetime.now().year,
    )


@app.route('/contact')
def contact():
    # """Renders the contact page."""
    return render_template(
        'contact.html',
        title='Contact',
        year=datetime.now().year,
        message='ICS-Vertex'
    )


@app.route('/about')
def about():
    return render_template(
        'about.html',
        title='About',
        year=datetime.now().year,
        message='Your application description page.'
    )


if __name__ == '__main__':
    app.run()


Solution

  • Solved! I found out that there were 2 conflicting libraries that both used the requests name