Source

stack2blog / stack2blog / stack2blogapp / views.py

Full commit
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseServerError
from django.http import HttpResponseRedirect, HttpResponse
from django.http import Http404
from django.template import RequestContext
from models import *
import stackexchange
import types
from pdb import set_trace


# Create your views here.
def home_page(request):
	# Get is someone looking at the homepage for the first time.
	if request.method == 'GET':
		# Get any error messages waiting.
		error_message = request.session.get("error_message", "")
		request.session["error_message"] = ""

		return render_to_response('home.html', locals(), context_instance=RequestContext(request))

	# Post. Make sure all is well.
	try:
		if not request.POST.has_key("userid"):
			raise RuntimeError("POST call doesn't have userid variable")

		try:
			userid = int(request.POST.get("userid", ""))
		except:
			raise RuntimeError("Invalid User ID - must be a number")

		# We don't try and get the user here to see if it exists, since it's an
		# extra api call.

	except RuntimeError, e:
		# TODO: Return the home_page, but with an error message.
		request.session["error_message"] = str(e)
		return HttpResponseRedirect("/")

	# everything was fine, redirect to user page.
	return HttpResponseRedirect("/userpage/" + str(userid))


def blurbifyAnswer(answer_obj):
	'''
	Given a StackExchange answer object, adds a method called "body_blurb" to it
	which gives back a blurb of the answer suitable for concise display on our site.
	'''
	def body_blurb(self):
		return self.body

	meth = types.MethodType(body_blurb, answer_obj, stackexchange.Answer)
	answer_obj.body_blurb = meth
	return answer_obj

def userpage(request, userid):
	try:
		userid = int(userid)
	except ValueError:
		bacHomeWithError("Invalid user ID - must be a number")

	cached = False
	# Check if this user is the one in the session.
	if request.session.has_key("so_userid") and request.session["so_userid"] == userid:
		# Get the answers out of the cache.
		if request.session.has_key("so_answers"):
			answers = request.session["so_answers"]
			cached = True

	if not cached:
		# Remember the userid.
		request.session["so_userid"] = userid

		site = stackexchange.Site(stackexchange.StackOverflow, app_key = "SL5xzbpFYUCSae3tqVlL7A")
		# site.be_inclusive()
		# so_user = site.user(userid)

		answers = []
		try:
			more_answers = site.answers(user_id=userid, pagesize=100, body=True)
			while (len(more_answers) > 0):
				answers += more_answers
				more_answers = more_answers.fetch_next()
		except:
			request.session["error_message"] = "There was an error processing your user page. Please make sure your id is correct, then try again."
			return HttpResponseRedirect("/")

		if len(answers) == 0:
			request.session["error_message"] = "That User ID doesn't exist; please try a different one"
			return HttpResponseRedirect("/")

		so_user_display_name = answers[0].owner_info[0]

		# Cache these answers so we won't have to go to so once again.
		# TODO: Turn this on to turn on caching.
		# request.session["so_answers"] = answers

	# Figure out what's published and unpublished.
	published_answers = [blurbifyAnswer(answer) for answer in answers if PublishedPost.objects.filter(postid = answer.id).count() > 0]
	unpublished_answers = [blurbifyAnswer(answer) for answer in answers if PublishedPost.objects.filter(postid = answer.id).count() == 0]

	for answer in published_answers:
		answer.publication_date = PublishedPost.objects.get(postid = answer.id).publication_date

	# Sort published answers by date.
	published_answers.sort(key=lambda ans: ans.publication_date, reverse=True)

	len_unpublished = len(unpublished_answers)

	# Get filter and sorting options.
	try:
		length_filter = request.GET["length_filter"]
		length_filter = int(length_filter)
	except:
		length_filter = 1000

	search_sort = request.GET.get("search_sort", "votes")
	if search_sort not in ('votes', 'question', 'answer'):
		search_sort = 'votes'

	search_order = request.GET.get("search_order", "dec")
	if search_order not in ('asc', 'dec'):
		search_order = 'dec'



	# Apply the filters to the unpublished answers.
	unpublished_answers = [answer for answer in unpublished_answers if len(answer.body) > length_filter]

	num_answers_remaining = len_unpublished - len(unpublished_answers)

	# Sort by the sort field.
	if search_sort == 'votes':
		def sortKey(answer):
			return answer.score
	elif search_sort == 'answer':
		def sortKey(answer):
			return len(answer.body)
	elif search_sort == 'question':
		def sortKey(answer):
			return answer.creation_date

	reverse = (search_order == "dec")
	unpublished_answers.sort(key = sortKey, reverse=reverse)

	search_order_post_votes = "dec"
	search_order_post_title = "dec"
	search_order_post_answer = "dec"

	if search_sort == 'votes':
		if search_order == 'asc':
			search_order_post_votes = 'dec'
		else:
			search_order_post_votes = 'asc'
	elif search_sort == 'answer':
		if search_order == 'asc':
			search_order_post_title = 'dec'
		else:
			search_order_post_title = 'asc'
	elif search_sort == 'question':
		if search_order == 'asc':
			search_order_post_answer = 'dec'
		else:
			search_order_answer = 'asc'

	return render_to_response('userpage.html', locals(), context_instance=RequestContext(request))

def post_answer(request, answer_id):
	try:
		answer_id = int(answer_id)
	except ValueError:
		request.session["error_message"] = "The answer you're trying to post doesn't exist."
		return HttpResponseRedirect("/")

	site = stackexchange.Site(stackexchange.StackOverflow, app_key = "SL5xzbpFYUCSae3tqVlL7A")
	site.be_inclusive()
	answer = site.answer(answer_id)

	return render_to_response('post_answer.html', locals(), context_instance=RequestContext(request))

def perform_post(request, answer_id):
	try:
		answer_id = int(answer_id)
	except ValueError:
		request.session["error_message"] = "The answer you're trying to post doesn't exist."
		return HttpResponseRedirect("/")


	post = PublishedPost(postid = answer_id)
	post.save()

	userid = request.session["so_userid"]

	return HttpResponseRedirect("/userpage/" + str(userid))

def how_to_find_id(request):
	return render_to_response('how_to_find_id.html', locals(), context_instance=RequestContext(request))