[Twisted-web] HTTP redirection from data_*/render_* methods

en.karpachov at ospaz.ru en.karpachov at ospaz.ru
Fri Jul 15 04:46:22 MDT 2005


I wondered if I can make an HTTP redirection (302) from inside of render_*
or data_* method. Here is a code snipped I wrote; I'd like to know if it
can be considered as "good" nevow practice?


from nevow import rend, loaders, inevow
from twisted.internet import defer

class MyPage(rend.Page):

    addSlash = True

    docFactory = loaders.xmlstr("""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" xmlns:nevow="http://nevow.com/ns/nevow/0.1">
  <body>
    <div nevow:render="redirect http://google.com">Nothing is here</div>
  </body>
</html>
""")

    buffered = True

    def renderHTTP(self, ctx):
        """The renderHTTP method is overloaded to add errback handler
        to the rendering Deferred object"""

        d = defer.maybeDeferred(rend.Page.renderHTTP, self, ctx)
        d.addErrback(self.onError, ctx)
        return d

    #
    # Custom exception-based class to request redirection
    #
    class __Redirect(Exception): pass

    def onError(self, failure, ctx):
        if isinstance(failure.value, self.__Redirect):
            #
            # If a redirection was requested, then drop the output buffer
            # and redirect the Request object
            #
            inevow.IRequest(ctx).redirect(failure.value.args[0])
            return ""
        #
        # Otherwise, fall through
        #
        return failure

    #
    # Convenience method to be called from inside of render_* or data_*
    # callback
    #
    def __redirect(self, url):
        raise self.__Redirect, url

    #
    #
    #
    def render_redirect(self, url):
        return lambda ctx, data: self.__redirect(url)



The "redirect" render directive could be used depending on some another
logic in the page, if some pattern was assigned to the containing tag.

Any comments will be very appreciated.

-- 
jk



More information about the Twisted-web mailing list