def search(request):
    # Grab the search term from the url
    query = request.GET.get('query', '')

    try:
        # Set the index to use
        index = gsearch.Index(name='stories-and-media-index2')

        # Run the search
        search_results = index.search(query + ' doc_type=story status=published')

    # If something went wrong just return 0 results
    except:
        search_results = []

    # Set up the result dict for the template
    results = []

    # Populate the result dict
    for search_item in search_results:
        item = {'id': int(search_item.doc_id.split(':')[1])}

        for field in search_item.fields:
            item[field.name] = field.value

        # Patch in the votes, in a real app this would be done outide the loop to reduce round trips to the datastore
        item['votes'] = StoryVote.get_by_id('StoryVote:%s' % item['id'])

        # Patch in the avatar, again this is sub-optimal and could be implemented in a more efficient way
        # were this not a prototype. Most likely by including the author email in the search index so that
        # the gravatar url can be calculated on the fly
        user = WinaUser.objects.get(id=item['author_id'])
        item['author_avatar'] = user.get_avatar()

        results.append(item)

    return render(request, 'frontend/search.html', {
        'title': 'Search for "%s"' % query,
        'query': query,
        'results': results,
    })
def index(request):
    # Get the top 10 stories with the highest vote count with at least 1 vote
    story_votes = StoryVote.query(StoryVote.status == 'published', StoryVote.total >= 1).order(-StoryVote.total).fetch(10)

    # Used to store all the ids needed for the sql query
    ids = []

    # Used to provide a way to easily access the vote data for a story in the template
    votes = {}

    for story in story_votes:
        id = story.key.id().split(':')[1]
        ids.append(id)
        votes[id] = {
            'upvotes': story.upvotes,
            'downvotes': story.downvotes,
            'total': story.total,
        }

    # Query for the full story object from the database
    db_stories = Story.objects.filter(pk__in=ids, status='published').order_by('-date_created')

    # Due to the limitations in django templates we need to combine the lists here
    stories = []
    for story in db_stories:
        stories.append({
            'story': story,
            'votes': votes[str(story.id)]
        })

    # Now we have the story objects out the db we need to resort them
    stories = sorted(stories, key=lambda x: x['votes']['total'], reverse=True)

    return render(request, 'frontend/stories.html', {
        'title': 'Home',
        'page_title': 'Trending Stories',
        'stories': stories,
    })