Created
August 21, 2013 18:36
-
-
Save earthling-shruti/6298302 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.contrib import messages | |
from django.core.urlresolvers import reverse | |
from django.db.models import F | |
from django.http import HttpResponseRedirect | |
from django.shortcuts import render_to_response | |
from django.template import RequestContext | |
from django.utils import timezone | |
from django.utils.translation import ugettext as _ | |
from django.views.generic import FormView | |
import twitter | |
from search.forms import SearchForm | |
from search.models import SearchTerm | |
class SearchView(FormView): | |
""" | |
Class that fetches and displays search results | |
""" | |
template_name = 'search.html' | |
form_class = SearchForm | |
def form_valid(self, form): | |
""" | |
Increments the count of the search phrase if it has been made before, | |
retrieves the latest results using the Twitter API and displays them | |
""" | |
search_phrase = form.cleaned_data['search_phrase'] | |
try: | |
existing_search_term = SearchTerm.objects.get(phrase=search_phrase) | |
except SearchTerm.DoesNotExist: | |
# create a new search term | |
new_search_term = SearchTerm(phrase=search_phrase, | |
repeat_count=1, | |
last_searched_date=timezone.now()) | |
new_search_term.save() | |
else: | |
# update the existing search term | |
SearchTerm.objects.filter(phrase=search_phrase).update( | |
repeat_count=F('repeat_count') + 1, | |
last_searched_date=timezone.now()) | |
# get the search results for the phrase | |
search_results = self.twitter_search(search_phrase) | |
context = RequestContext(self.request, | |
{'form': form, | |
'search_phrase': search_phrase, | |
'search_results': search_results}) | |
# return search results to the template | |
return render_to_response('search.html', context) | |
def twitter_search(self, phrase): | |
""" | |
Searches Twitter for a phrase and returns the search results | |
""" | |
consumer_key = settings.TWITTER_CONSUMER_KEY | |
consumer_secret = settings.TWITTER_CONSUMER_SECRET | |
oauth_token = settings.TWITTER_OAUTH_TOKEN | |
oauth_token_secret = settings.TWITTER_OAUTH_TOKEN_SECRET | |
api = twitter.Api(consumer_key, consumer_secret, oauth_token, | |
oauth_token_secret) | |
return api.GetSearch(phrase) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment