Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / howto / tutorial / listings / finger / finger14.tac
1 # Read from file
2 from twisted.application import internet, service
3 from twisted.internet import protocol, reactor, defer
4 from twisted.protocols import basic
5
6 class FingerProtocol(basic.LineReceiver):
7     def lineReceived(self, user):
8         d = self.factory.getUser(user)
9
10         def onError(err):
11             return 'Internal error in server'
12         d.addErrback(onError)
13
14         def writeResponse(message):
15             self.transport.write(message + '\r\n')
16             self.transport.loseConnection()
17         d.addCallback(writeResponse)
18
19
20 class FingerService(service.Service):
21     def __init__(self, filename):
22         self.users = {}
23         self.filename = filename
24
25     def _read(self):
26         for line in file(self.filename):
27             user, status = line.split(':', 1)
28             user = user.strip()
29             status = status.strip()
30             self.users[user] = status
31         self.call = reactor.callLater(30, self._read)
32
33     def startService(self):
34         self._read()
35         service.Service.startService(self)
36
37     def stopService(self):
38         service.Service.stopService(self)
39         self.call.cancel()
40
41     def getUser(self, user):
42         return defer.succeed(self.users.get(user, "No such user"))
43
44     def getFingerFactory(self):
45         f = protocol.ServerFactory()
46         f.protocol = FingerProtocol
47         f.getUser = self.getUser
48         return f
49
50
51 application = service.Application('finger', uid=1, gid=1)
52 f = FingerService('/etc/users')
53 finger = internet.TCPServer(79, f.getFingerFactory())
54
55 finger.setServiceParent(service.IServiceCollection(application))
56 f.setServiceParent(service.IServiceCollection(application))