Skip to content

Instantly share code, notes, and snippets.

@palevell
Created December 28, 2019 21:06
Show Gist options
  • Save palevell/0014a2fff7d8d5d08d9f8679df3d6131 to your computer and use it in GitHub Desktop.
Save palevell/0014a2fff7d8d5d08d9f8679df3d6131 to your computer and use it in GitHub Desktop.
Plugging Tweepy into the Django-Allauth package was easier than I thought.
# utils.py - Saturday, December 28, 2019
# -*- coding: utf-8 -*-
""" I have been experimenting to see which web framework would make the better
wrapper for Tweepy. I decided on Django, with the Allauth package.
Afer going through the Django-Allauth Tutorial at
https://wsvincent.com/django-allauth-tutorial/ and playing with the DjangoTweepy repository at
https://github.com/martinjc/DjangoTweepy/blob/master/src/twitter_auth/utils.py,
this is what I contrived.
USAGE:
from . utils import get_api
...
api = get_api(request)
me = api.me()
screen_name = me.screen_name
whoami = api.get_user(screen_name)
print(whoami)
"""
import tweepy
from allauth.socialaccount import app_settings
def get_api(request):
""" This was borrowed from
https://github.com/martinjc/DjangoTweepy/blob/master/src/twitter_auth/utils.py
:param request:
:return: Tweepy API object
"""
# Get current Twitter app (API keys stored here)
app = get_current_app(request, 'twitter')
# Create Tweepy OAuth Handler
oauth = tweepy.OAuthHandler(app.client_id, app.secret)
# Retrieve access token from the current session, created by Allauth
access_key = request.session['oauth_%s_access_token' % 'api.twitter.com']['oauth_token']
access_secret = request.session['oauth_%s_access_token' % 'api.twitter.com']['oauth_token_secret']
# Set access token in Tweepy OAuth Handler
oauth.set_access_token(access_key, access_secret)
# Return Tweepy API object
return tweepy.API(oauth)
def get_current_app(request, provider):
""" This chunk of code was borrowed from
django-allauth/allauth/socialaccount/adapter.py
:param request:
:param provider:
:return: app:
"""
from allauth.socialaccount.models import SocialApp
config = app_settings.PROVIDERS.get(provider, {}).get('APP')
if config:
app = SocialApp(provider=provider)
for field in ['client_id', 'secret', 'key']:
setattr(app, field, config.get(field))
else:
app = SocialApp.objects.get_current(provider, request)
return app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment