[Twisted-Python] Application Start Up and Tear Down

Valentino Volonghi aka Dialtone dialtone at divmod.com
Mon Jul 9 03:27:21 EDT 2007

On Mon, 9 Jul 2007 11:18:50 +0600, Pavel Bastov <pbastov at gmail.com> wrote:
>I don't call reactor.run() explicitly.
>Here is how I launch it:
>application = service.Application('xoochat', uid = uid, gid = gid)

The right way to do this is defining your own Service like in this way:

import locale

from twisted.internet import defer

from twisted.cred.checkers import AllowAnonymousAccess
from twisted.python.components import registerAdapter
from twisted.cred.credentials import IAnonymous
from twisted.application.service import Service
from twisted.cred.portal import Portal

from nevow import inevow, appserver
#from nevow import guard

from starter.monkeypatches import VhostFakeRoot
from starter import storage, auth, guard, istarter
from starter.web import main

class StarterService(Service):
    def __init__(self, conf):
        self.conf = conf
    def privilegedStartService(self):
        locale.setlocale(locale.LC_TIME, self.conf['general']['lc_ctime'])
        dbconf = self.conf['db']
        self.db = p = storage.init(dbconf['engine'])
        ls = auth.LoginSystem(self.db, self.conf)
        p = Portal(ls)
        p.registerChecker(AllowAnonymousAccess(), IAnonymous)
        registerAdapter(main.Root, istarter.IAvatar, inevow.IResource)

        res = guard.SessionWrapper(p)
        vhost = VhostFakeRoot(res)
        self.site = appserver.NevowSite(vhost, logPath=self.conf['paths']['web'].path)

        from twisted.internet import reactor

        self.port = reactor.listenTCP(self.conf['web']['port'],

    def stopService(self):
        dl = []
        if self.port is not None:
            self.port = None
        if self.db is not None:
            self.db = None
        return defer.DeferredList(dl)

And you define your .tac file like this:

from twisted.application import service
from starter.service import StarterService
from configuration import main

application = service.Application('Starter')

Of course Twisted will call Service.privilegedStartService when everything startsup and after
it changed UID (or anyway after Service.startService).

Then when everything stops it will call Service.stopService.

You can of course register other services as children of this parent one by using .setServiceParent().

Valentino Volonghi aka dialtone
Blog: http://www.twisted.it

More information about the Twisted-Python mailing list