Skip to content

Instantly share code, notes, and snippets.

@marius92mc
Last active August 29, 2015 14:14
Show Gist options
  • Save marius92mc/309ec53acbed0042c4e6 to your computer and use it in GitHub Desktop.
Save marius92mc/309ec53acbed0042c4e6 to your computer and use it in GitHub Desktop.
import tweepy
CONSUMER_KEY = '...'
CONSUMER_SECRET = '...'
API = ""
initial_logged_in_user = ""
def main(request):
""" main view of app, either login page or info page """
# if we haven't authorised yet, direct to login page
if check_key(request):
return HttpResponseRedirect(reverse('app:info_loading'))
else:
return render(request, 'app/login_with_twitter.html')
def get_api(request):
# set up and return a twitter api object
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
access_key = request.session['access_key_tw']
access_secret = request.session['access_secret_tw']
oauth.set_access_token(access_key, access_secret)
api = tweepy.API(oauth)
return api
def unauth(request):
if check_key(request):
# api = get_api(request)
request.session.clear()
logout(request)
return HttpResponseRedirect(reverse('app:main'))
error_string = ""
class ChangedUserForm(forms.Form):
new_user = forms.CharField(max_length=100)
def newUser(request, user):
error_string = ""
changed_user = False
if request.method == 'POST':
form = ChangedUserForm(request.POST)
if form.is_valid():
new_user = form.cleaned_data['new_user']
new_user = new_user.lower()
try:
global API
validateAPI(API)
user = API.get_user(new_user)
changed_user = True
except Exception, e:
error_string = "There isn't any user with the specified username."
return changed_user, user, error_string
class ContactForm(forms.Form):
name = forms.CharField(max_length=100) # must be the same with column names from the table
email = forms.CharField(max_length=100)
comment = forms.CharField(max_length=500)
def newContact(request):
#...
def info_loading(request):
if check_key(request):
api = get_api(request)
global API
API = api
try:
user = api.me()
except tweepy.TweepError as e:
#print e.message[0]['message']
return render(request, 'app/info_loading.html', { \
'limit_exceeded': "API calls limit exceeded."})
global initial_logged_in_user
initial_logged_in_user = user
db_op.saveLoggedInUser(user)
return render(request, 'app/info_loading.html', { \
'user': user, \
})
else:
return HttpResponseRedirect(reverse('app:main'))
def info(request):
if check_key(request):
api = get_api(request) # !!!!!! api at every step, user = api.me() represents exactly the user with wich I've logged in
global API # so we know that we refer to the global variable, not a new local one
API = api # we need to save the API for further calls
try:
user = api.me() # here in user we have all that tweepy needs, from here I can make API calls with object "user"
except tweepy.TweepError as e:
#print e.message[0]['message']
return render(request, 'app/info_loading.html', { \
'limit_exceeded': "API calls limit exceeded."})
global initial_logged_in_user
initial_logged_in_user = user # we need to save it for further calls
db_op.saveLoggedInUser(user)
changed_user, user, error_string = newUser(request, user)
#if changed_user == True:
#db_op.saveLoggedInUser(user)
return render(request, 'app/info.html', {
'user': user,
'display_change_user': display_change_user,
'error_string': error_string,
'generated_hour': generated_at.getHour(),
'generated_date': generated_at.getDate(),
'user_stats': user_stats,
})
else:
return HttpResponseRedirect(reverse('app:main'))
def validateAPI(API):
if API is "":
return HttpResponseRedirect(reverse('app:info_loading'))
new_query = ""
def auth(request):
# start the OAuth process, set up a handler with our details
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
# direct the user to the authentication url
# if user is logged-in and authorized then transparently goto the callback URL
auth_url = ""
try:
auth_url = oauth.get_authorization_url()
except tweepy.TweepError:
print 'Error! Failed to get request token.'
response = HttpResponseRedirect(auth_url)
# store the request token
request.session['request_token'] = (oauth.request_token['oauth_token'], oauth.request_token['oauth_token_secret'])
return response
def callback(request):
verifier = request.GET.get('oauth_verifier')
oauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
token = request.session.get('request_token')
# remove the request token now we don't need it
request.session.delete('request_token')
# import pdb; pdb.set_trace()
#oauth.set_request_token(token[0], token[1])
#print request.session['request_token'][0], " ", request.session['request_token'][1]
oauth.request_token = token
print request.session
print token[0], "-", token[1]
print oauth.request_token[0], "-", oauth.request_token[1]
print verifier
# get the access token and store
#try:
oauth.get_access_token(verifier)
#except tweepy.TweepError as e:
# print e.message
# print 'Error, failed to get access token'
request.session['access_key_tw'] = oauth.access_token # de salvat undeva
request.session['access_secret_tw'] = oauth.access_token_secret # de salvat undeva
# saving access_token_key and access_token_secret in a file
file_access_tokens = open("app/access_tokens", "w")
file_access_tokens.write(str(oauth.access_token))
file_access_tokens.write("\n")
file_access_tokens.write(str(oauth.access_token_secret))
file_access_tokens.close()
response = HttpResponseRedirect(reverse('app:info_loading'))
return response
def check_key(request):
""" Check to see if we already have an access_key stored,
if we do then we have already gone through OAuth. If not then we haven't
and we probably need to. """
try:
#access_key = request.session.get('access_key_tw', None)
access_key = request.session['access_key_tw']
if not access_key:
return False
except KeyError:
return False
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment