Using Google OAuth2 with Flask

后端 未结 9 2111
粉色の甜心
粉色の甜心 2020-12-07 07:44

Can anyone point me to a complete example for authenticating with Google accounts using OAuth2 and Flask, and not on App Engine?

I am trying to have users g

9条回答
  •  我在风中等你
    2020-12-07 07:59

    Give Authomatic a try (I'm the maintainer of that project). It is very simple to use, works with any Python framework and supports 16 OAuth 2.0, 10 OAuth 1.0a providers and OpenID.

    Here is a simple example about how to authenticate a user with Google and get his/her list of YouTube videos:

    # main.py
    
    from flask import Flask, request, make_response, render_template
    from authomatic.adapters import WerkzeugAdapter
    from authomatic import Authomatic
    from authomatic.providers import oauth2
    
    
    CONFIG = {
        'google': {
            'class_': oauth2.Google,
            'consumer_key': '########################',
            'consumer_secret': '########################',
            'scope': oauth2.Google.user_info_scope + ['https://gdata.youtube.com'],
        },
    }
    
    app = Flask(__name__)
    authomatic = Authomatic(CONFIG, 'random secret string for session signing')
    
    
    @app.route('/login//', methods=['GET', 'POST'])
    def login(provider_name):
        response = make_response()
    
        # Authenticate the user
        result = authomatic.login(WerkzeugAdapter(request, response), provider_name)
    
        if result:
            videos = []
            if result.user:
                # Get user info
                result.user.update()
    
                # Talk to Google YouTube API
                if result.user.credentials:
                    response = result.provider.access('https://gdata.youtube.com/'
                        'feeds/api/users/default/playlists?alt=json')
                    if response.status == 200:
                        videos = response.data.get('feed', {}).get('entry', [])
    
            return render_template(user_name=result.user.name,
                                   user_email=result.user.email,
                                   user_id=result.user.id,
                                   youtube_videos=videos)
        return response
    
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    There is also a very simple Flask tutorial which shows how to authenticate a user by Facebook and Twitter and talk to their APIs to read the user's newsfeeds.

提交回复
热议问题