Twitter Authentication in Django with Tweepy
While working on a recent project during my internship I had to come up with a way to authenticate users in our Django application. We use an Angular front-end that makes calls to Django.
I am going to strip out all the angular magic, but seriously. You need to go check it out. It makes building front-end applications in the browser stupid easy with just a little of javascript know how.
First off go make sure you check out the Tweepy documentation. I found it extremely helpful.
I am assuming you can set up the Django urls.py
file yourself. We have at least two routes we need to make.
- Start Twitter Authentication
- Callback from Twitter
In our first view we need to do a few things. We need to set up our twitter application’s consumer token, consumer secret and the callback url.
|
|
This authenticates your application with twitter so you can later authenticate a user. To authenticate a user you need to redirect them to twitter’s website to accept logging into your application. Tweepy has an easy way to get this url using .get_authorization_url()
. You should wrap any calls to outside services in try/except because you can never be sure when they will fail because of no fault of your own and when it does you can show a nice error message rather than everything crashing to a halt.
|
|
Your finished view file should look something like this:
|
|