Wednesday, July 17, 2013

Reusing code between views and viewlets

You may wonder, as i did today, how you can re-use code from your View inside a Viewlet. Just to help out the occasional googler, i'm recording my solution here.

Any Viewlet has its View as an attribute (see ViewletBase's __init__ method). So in your Viewlet class, you can do something like:
Class MyViewlet(ViewletBase):
    def reused_method(self):
            return self.view.original_method()

Thursday, July 11, 2013

try-except HTTPError and URLError

urllib2's HTTPError subclasses URLError, so the bit of code below would never get to the second except statement, because that error would aready be caught in the first except. To get this code to work, reverse the order.

                response = urlopen(url)
            except URLError:
                # This happens if the server can't be reached.
                # Most likely the service is down, in this case we don't want
                # to do anything.
                # Another possibility is that we have the API url wrong.
                return True
            except HTTPError:
                # as Flattr API does return an error code (404 not found) when
                # looking for users that do not exist, urllib2 treats that as
                # an error, so no need to investigate or differentiate between
                # that and a normal HTTP error. Both are enough to not validate
                # a Flattr user.
                return False