Source

txMysql / txmysql / web / root.py

#-*- test-case-name: txmysql.test.test_web -*-
import os

from twisted.python import log
from twisted.internet import defer, reactor
from twisted.web import http, resource, server, static

from txmysql import settings


class Root(resource.Resource):
    def __init__(self):
        resource.Resource.__init__(self)
        self.putChild("static", static.File("txmysql/static"))

    def _failed(self, reason):
        log.err(reason)
        return http.Response(
            code=500,
            headers=None,
            stream=reason.getErrorMessage()
        )

    def _got(self, result, request):
        request.setResponseCode(http.OK)
        request.write(result)
        request.finish()

    def getStaticFile(self, deferred):
        filepath = os.path.join(settings.TXMYSQL_ROOT.path, "txmysql/static/root.html")
        template = open(filepath, "r")
        contents = template.read()
        deferred.callback(contents)

    def render_GET(self, request):
        self.d = defer.Deferred()
        self.d.addCallback(self._got, request)
        self.d.addErrback(self._failed)
        reactor.callLater(0.1, self.getStaticFile, self.d)
        return server.NOT_DONE_YET

    def getChild(self, path, request):
        if path == "":
            return self
        return resource.Resource.getChild(self, path, request)