Commits

edanm committed 7d6f4bc

Converted to more efficient api requests

Comments (0)

Files changed (4)

stack2blog/stack2blogapp/models.py

 # Create your models here.
 class PublishedPost(models.Model):
 	postid = models.IntegerField()
-	publication_date = models.DateTimeField(auto_now_add = True)
+	publication_date = models.DateTimeField(auto_now_add = True)

stack2blog/stack2blogapp/stackexchange.py

 		# kind of a cheat, but oh well
 		return self.fetch_page(self.page)
 
-	def fetch_page(self, page):
+	def fetch_page(self, page, **kw):
 		"""Returns a new resultset containing data from the specified page of the results. It re-uses all parameters that were passed in
 to the initial function which created the resultset."""
 		new_params = list(self.build_info)
 		new_params[4] = new_params[4].copy()
+		new_params[4].update(kw)
 		new_params[4]['page'] = page
 		return new_params[0].build(*new_params[1:])
 	
 		else:
 			raise NeedsAwokenError(self)
 	
-	def fetch(self):
+	def fetch(self, **kw):
 		"""Fetch, from the API, the data this sequence is meant to hold."""
 
-		res = self.site.build(self.url, self.m_type, self.collection)
+		res = self.site.build(self.url, self.m_type, self.collection, kw)
 		if self.fetch_callback != None:
 			self.fetch_callback(res)
 		return res
 		self.votes = (self.up_vote_count, self.down_vote_count)
 		self.url = 'http://' + self.site.root_domain + '/questions/' + str(self.question_id) + '/' + str(self.id) + '#' + str(self.id)
 	
-	question = property(lambda self: self._question if self._question is not None else self.site.question(self.question_id))
-	owner = property(lambda self: self._owner if self._owner is not None else self.site.user(self.owner_id))
+	def _get_user(s,id):
+		s._owner = self.site.user(id)
+		return s._owner
+	def _set_user(s,ob):
+		s._owner = pb
+	def _get_quest(s,id):
+		s._question = self.site.question(id)
+		return s._question
+	def _set_quest(s,ob):
+		s._question = ob
+	
+	question = property(lambda self: self._question if self._question is not None else self._get_quest(self.question_id), _set_quest)
+	owner = property(lambda self: self._owner if self._owner is not None else self._get_user(self.owner_id), _set_user)
 
 	def __unicode__(self):
 		return u'Answer %d [%s]' % (self.id, self.title)
 		Question: 'questions/%s',
 	}
 	
+	def _kw_to_str(self, ob):
+		try:
+			if not isinstance(ob, str):
+				i = iter(ob)
+				return ';'.join(i)
+			else:
+				return ob
+		except TypeError:
+			return str(ob).lower()
+
 	def _request(self, to, params):
 		url = 'http://' + self.domain + '/' + self.api_version + '/' + to
 
 				done = True
 			else: url += '&'
 
-			url += '%s=%s' % (k, str(v))
+			url += '%s=%s' % (k, self._kw_to_str(v))
 
 		if self.app_key != None:
 			url += ('?' if not '?' in url else '&') + 'key=' + self.app_key
 		except urllib2.URLError, e:
 			raise StackExchangeError(e)
 	
+	def _user_prop(self, qs, typ, coll, kw, prop='user_id'):
+		if prop not in kw:
+			raise LookupError('No user ID provided.')
+		else:
+			tid = kw[prop]
+			del kw[prop]
+
+			return self.build('users/%d/%s' % (tid, qs), typ, coll, kw)
+
 	def be_inclusive(self):
 		"""Include the body and comments of a post, where appropriate, by default."""
 
 		"""Builds a StackExchangeResultset object from the given URL and type."""
 
 		if 'body' not in kw:
-			kw['body'] = str(self.include_body)
+			kw['body'] = str(self.include_body).lower()
 		if 'comments' not in kw:
-			kw['comments'] = str(self.include_comments)
+			kw['comments'] = str(self.include_comments).lower()
 
 		json = self._request(url, kw)
 		
 		a, = self.answers((nid,), **kw)
 		return a
 	
-	def answers(self, ids, **kw):
-		"""Retrieves a set of the answers with the IDs specified in the 'ids' parameter."""
-		return self._get(Answer, ids, 'answers', kw)
+	def answers(self, ids=None, **kw):
+		"""Retrieves a set of the answers with the IDs specified in the 'ids' parameter, or by the
+		user_id specified."""
+		if ids == None:
+			return self._user_prop('answers', Answer, 'answers', kw)
+		else:
+			return self._get(Answer, ids, 'answers', kw)
 
 	def comment(self, nid, **kw):
 		"""Retrieves an object representing a comment with the ID `nid`."""
 		c, = self.comments((nid,), **kw)
 		return c
 	
-	def comments(self, ids, **kw):
+	def comments(self, ids=None, **kw):
 		"""Retrieves a set of the comments with the IDs specified in the 'ids' parameter."""
-		return self._get(Comment, ids, 'comments', kw)
+		if ids == None:
+			return self._user_prop('comments', Comment, 'comments', kw)
+		else:
+			return self._get(Comment, ids, 'comments', kw)
 	
 	def question(self, nid, **kw):
 		"""Retrieves an object representing a question with the ID `nid`. Note that an answer ID can not be specified -
 		q, = self.questions((nid,), **kw)
 		return q
 	
-	def questions(self, ids, **kw):
+	def questions(self, ids=None, **kw):
 		"""Retrieves a set of the comments with the IDs specified in the 'ids' parameter."""
 		if 'answers' not in kw:
 			kw['answers'] = 'true'
-		return self._get(Question, ids, 'questions', kw)
+		if ids == None:
+			return self._user_prop('questions', Question, 'questions', kw)
+		else:
+			return self._get(Question, ids, 'questions', kw)
 	
 	def recent_questions(self, **kw):
 		"""Returns the set of the most recent questions on the site, by last activity."""
 		"""Returns the set of all the badges which can be awarded on the site, excluding those which are awarded for specific tags."""
 		return self.build('badges', Badge, 'badges', kw)
 	
-	def badges(self, ids, **kw):
-		"""Returns information on the badges with the IDs specified in the 'ids' parameter."""
-		return self._get(Badge, ids, 'badges', kw)
+	def badges(self, ids=None, **kw):
+		"""Returns the users with the badges with IDs."""
+		if ids == None:
+			return self._user_prop('badges', Badge, 'users', kw)
+		else:
+			return self._get(Badge, ids, 'users', kw)
 
 	def badge(self, nid, **kw):
 		"""Returns an object representing the badge with the ID 'nid'."""

stack2blog/stack2blogapp/templates/userpage.html

 {% extends "superpage.html" %}
 
-{% block title %} {{so_user.display_name}}'s page - Stack2Blog {% endblock %}
+{% block title %} {{so_user_display_name}}'s page - Stack2Blog {% endblock %}
 
 
 {% block head %}
 
 <div id="userpage_container" class="container_16">
 
-	<h1 class="grid_12" class="display_name"> Welcome {{so_user.display_name}} </h1>
+	<h1 class="grid_12" class="display_name"> Welcome {{so_user_display_name}} </h1>
 	<div class="clear"></div>
 
 	<p class="grid_12">

stack2blog/stack2blogapp/views.py

 		try:
 			userid = int(request.POST.get("userid", ""))
 		except:
-			request.session["error_message"] = "Invalid User id (must be a number)"
-			return HttpResponseRedirect("/")
-			raise RuntimeError("Invalid user id")
+			raise RuntimeError("Invalid User ID - must be a number")
 
-		# TODO: Try and get the SO user here to make sure the userid is valid.
+		# 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.
-		return HttpResponseServerError(str(e))
+		request.session["error_message"] = str(e)
+		return HttpResponseRedirect("/")
 
 	# everything was fine, redirect to user page.
 	return HttpResponseRedirect("/userpage/" + str(userid))
 	answer_obj.body_blurb = meth
 	return answer_obj
 
+def backHomeWithError(request, message):
+	request.session["error_message"] = message
+	return HttpResponseRedirect("/")
+
 def userpage(request, userid):
 	try:
 		userid = int(userid)
 	except ValueError:
-		request.session["error_message"] = "Invalid user ID"
-		return HttpResponseRedirect("/")
+		bacHomeWithError("Invalid user ID - must be a number")
 
 	cached = False
 	# Check if this user is the one in the session.
 		request.session["so_userid"] = userid
 
 		site = stackexchange.Site(stackexchange.StackOverflow, app_key = "SL5xzbpFYUCSae3tqVlL7A")
-		site.be_inclusive()
-		so_user = site.user(userid)
+		# site.be_inclusive()
+		# so_user = site.user(userid)
 
 		answers = []
-		more_answers = so_user.answers.fetch()
+		more_answers = site.answers(user_id=userid, pagesize=100, body=True)
 		while (len(more_answers) > 0):
 			answers += more_answers
-			more_answers = so_user.answers.fetch_next()
+			more_answers = more_answers.fetch_next()
+
+		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.