Finger的演化:步入基于组件的结构
-- dreamingk [2004-08-09 02:10:32]
简介 Introduction
This is the fourth part of the Twisted tutorial Twisted from Scratch, or The Evolution of Finger.这是Twisted教程,Finger的演化的第四部分。
In this section of the tutorial, we'll move our code to a component architecture so that adding new features is trivial.
在这一部分,我们将把代码放到一个组件结构中,这样加入新的特性就很简单了。
写可维护的代码 Write Maintainable Code
In the last version, the service class was three times longer than any other class, and was hard to understand. This was because it turned out to have multiple responsibilities. It had to know how to access user information, by rereading the file every half minute, but also how to display itself in a myriad of protocols. Here, we used the component-based architecture that Twisted provides to achieve a separation of concerns. All the service is responsible for, now, is supporting getUser/getUsers. It declares its support via the implements keyword. Then, adapters are used to make this service look like an appropriate class for various things: for supplying a finger factory to TCPServer, for supplying a resource to site's constructor, and to provide an IRC client factory for TCPClient. All the adapters use are the methods in FingerService they are declared to use: getUser/getUsers. We could, of course, skip the interfaces and let the configuration code use things like FingerFactoryFromService(f) directly. However, using interfaces provides the same flexibility inheritance gives: future subclasses can override the adapters.在上个版本中,服务类是其它类的三倍长,而且也难懂。这是因为它具有多重职责。 必须要知道如何取得用户信息,通过每半分钟重新读取一次文件,还要知道如何通过不同的协议来显示信息。 这里,我们使用Twisted提供的基于组件的结构,由此分而治之。所有的服务都提供getUser/getUsers。 通过implement关键字。然后适配器就能让这个服务成为一个可以用于多种用途的类:向TCPServer提供finger factory, 提供资源给站点的构造器,提供IRC客户端factory给TCPClient。适配器使用的是FingerService声明可用的方法:getUser/getUsers。 我们可以,当然了,忽略接口让配置代码直接使用FingerFactoryFromService。但是使用接口则可以提供和继承一样的灵活性:将来子类可以重载适配器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | # Do everything properly, and componentize from twisted.application import internet, service from twisted.internet import protocol, reactor, defer from twisted.protocols import basic, irc from twisted.python import components from twisted.web import resource, server, static, xmlrpc import cgi class IFingerService(components.Interface): def getUser(self, user): """Return a deferred returning a string""" def getUsers(self): """Return a deferred returning a list of strings""" class IFingerSetterService(components.Interface): def setUser(self, user, status): """Set the user's status to something""" def catchError(err): return "Internal error in server" class FingerProtocol(basic.LineReceiver): def lineReceived(self, user): d = self.factory.getUser(user) d.addErrback(catchError) def writeValue(value): self.transport.write(value+'\n') self.transport.loseConnection() d.addCallback(writeValue) class IFingerFactory(components.Interface): def getUser(self, user): """Return a deferred returning a string""" def buildProtocol(self, addr): """Return a protocol returning a string""" class FingerFactoryFromService(protocol.ServerFactory): __implements__ = IFingerFactory, protocol = FingerProtocol def __init__(self, service): self.service = service def getUser(self, user): return self.service.getUser(user) components.registerAdapter(FingerFactoryFromService, IFingerService, IFingerFactory) class FingerSetterProtocol(basic.LineReceiver): def connectionMade(self): self.lines = [] def lineReceived(self, line): self.lines.append(line) def connectionLost(self, reason): if len(self.lines) == 2: self.factory.setUser(*self.lines) class IFingerSetterFactory(components.Interface): def setUser(self, user, status): """Return a deferred returning a string""" def buildProtocol(self, addr): """Return a protocol returning a string""" class FingerSetterFactoryFromService(protocol.ServerFactory): __implements__ = IFingerSetterFactory, protocol = FingerSetterProtocol def __init__(self, service): self.service = service def setUser(self, user, status): self.service.setUser(user, status) components.registerAdapter(FingerSetterFactoryFromService, IFingerSetterService, IFingerSetterFactory) class IRCReplyBot(irc.IRCClient): def connectionMade(self): self.nickname = self.factory.nickname irc.IRCClient.connectionMade(self) def privmsg(self, user, channel, msg): user = user.split('!')[0] if self.nickname.lower() == channel.lower(): d = self.factory.getUser(msg) d.addErrback(catchError) d.addCallback(lambda m: "Status of %s: %s" % (msg, m)) d.addCallback(lambda m: self.msg(user, m)) class IIRCClientFactory(components.Interface): """ @ivar nickname """ def getUser(self, user): """Return a deferred returning a string""" def buildProtocol(self, addr): """Return a protocol""" class IRCClientFactoryFromService(protocol.ClientFactory): __implements__ = IIRCClientFactory, protocol = IRCReplyBot nickname = None def __init__(self, service): self.service = service def getUser(self, user): return self.service.getUser(user) components.registerAdapter(IRCClientFactoryFromService, IFingerService, IIRCClientFactory) class UserStatusTree(resource.Resource): __implements__ = resource.IResource, def __init__(self, service): resource.Resource.__init__(self) self.service = service self.putChild('RPC2', UserStatusXR(self.service)) def render_GET(self, request): d = self.service.getUsers() def formatUsers(users): l = ['<li><a href="%s">%s</a></li>' % (user, user) for user in users] return '<ul>'+''.join(l)+'</ul>' d.addCallback(formatUsers) d.addCallback(request.write) d.addCallback(lambda _: request.finish()) return server.NOT_DONE_YET def getChild(self, path, request): if path=="": return UserStatusTree(self.service) else: return UserStatus(path, self.service) components.registerAdapter(UserStatusTree, IFingerService, resource.IResource) class UserStatus(resource.Resource): def __init__(self, user, service): resource.Resource.__init__(self) self.user = user self.service = service def render_GET(self, request): d = self.service.getUser(self.user) d.addCallback(cgi.escape) d.addCallback(lambda m: '<h1>%s</h1>'%self.user+'<p>%s</p>'%m) d.addCallback(request.write) d.addCallback(lambda _: request.finish()) return server.NOT_DONE_YET class UserStatusXR(xmlrpc.XMLRPC): def __init__(self, service): xmlrpc.XMLRPC.__init__(self) self.service = service def xmlrpc_getUser(self, user): return self.service.getUser(user) class FingerService(service.Service): __implements__ = IFingerService, def __init__(self, filename): self.filename = filename self._read() def _read(self): self.users = {} for line in file(self.filename): user, status = line.split(':', 1) user = user.strip() status = status.strip() self.users[user] = status self.call = reactor.callLater(30, self._read) def getUser(self, user): return defer.succeed(self.users.get(user, "No such user")) def getUsers(self): return defer.succeed(self.users.keys()) application = service.Application('finger', uid=1, gid=1) f = FingerService('/etc/users') serviceCollection = service.IServiceCollection(application) internet.TCPServer(79, IFingerFactory(f) ).setServiceParent(serviceCollection) internet.TCPServer(8000, server.Site(resource.IResource(f)) ).setServiceParent(serviceCollection) i = IIRCClientFactory(f) i.nickname = 'fingerbot' internet.TCPClient('irc.freenode.org', 6667, i ).setServiceParent(serviceCollection) Source listing - listings/finger/finger19.py Advantages of Latest Version Readable -- each class is short Maintainable -- each class knows only about interfaces Dependencies between code parts are minimized Example: writing a new IFingerService is easy class IFingerSetterService(components.Interface): def setUser(self, user, status): """Set the user's status to something""" # Advantages of latest version class MemoryFingerService(service.Service): __implements__ = IFingerService, IFingerSetterService def __init__(self, **kwargs): self.users = kwargs def getUser(self, user): return defer.succeed(self.users.get(user, "No such user")) def getUsers(self): return defer.succeed(self.users.keys()) def setUser(self, user, status): self.users[user] = status f = MemoryFingerService(moshez='Happy and well') serviceCollection = service.IServiceCollection(application) internet.TCPServer(1079, IFingerSetterFactory(f), interface='127.0.0.1' ).setServiceParent(serviceCollection) Source listing - listings/finger/finger19a_changes.py Full source code here: # Do everything properly, and componentize from twisted.application import internet, service from twisted.internet import protocol, reactor, defer from twisted.protocols import basic, irc from twisted.python import components from twisted.web import resource, server, static, xmlrpc import cgi class IFingerService(components.Interface): def getUser(self, user): """Return a deferred returning a string""" def getUsers(self): """Return a deferred returning a list of strings""" class IFingerSetterService(components.Interface): def setUser(self, user, status): """Set the user's status to something""" def catchError(err): return "Internal error in server" class FingerProtocol(basic.LineReceiver): def lineReceived(self, user): d = self.factory.getUser(user) d.addErrback(catchError) def writeValue(value): self.transport.write(value+'\n') self.transport.loseConnection() d.addCallback(writeValue) class IFingerFactory(components.Interface): def getUser(self, user): """Return a deferred returning a string""" def buildProtocol(self, addr): """Return a protocol returning a string""" class FingerFactoryFromService(protocol.ServerFactory): __implements__ = IFingerFactory, protocol = FingerProtocol def __init__(self, service): self.service = service def getUser(self, user): return self.service.getUser(user) components.registerAdapter(FingerFactoryFromService, IFingerService, IFingerFactory) class FingerSetterProtocol(basic.LineReceiver): def connectionMade(self): self.lines = [] def lineReceived(self, line): self.lines.append(line) def connectionLost(self, reason): if len(self.lines) == 2: self.factory.setUser(*self.lines) class IFingerSetterFactory(components.Interface): def setUser(self, user, status): """Return a deferred returning a string""" def buildProtocol(self, addr): """Return a protocol returning a string""" class FingerSetterFactoryFromService(protocol.ServerFactory): __implements__ = IFingerSetterFactory, protocol = FingerSetterProtocol def __init__(self, service): self.service = service def setUser(self, user, status): self.service.setUser(user, status) components.registerAdapter(FingerSetterFactoryFromService, IFingerSetterService, IFingerSetterFactory) class IRCReplyBot(irc.IRCClient): def connectionMade(self): self.nickname = self.factory.nickname irc.IRCClient.connectionMade(self) def privmsg(self, user, channel, msg): user = user.split('!')[0] if self.nickname.lower() == channel.lower(): d = self.factory.getUser(msg) d.addErrback(catchError) d.addCallback(lambda m: "Status of %s: %s" % (msg, m)) d.addCallback(lambda m: self.msg(user, m)) class IIRCClientFactory(components.Interface): """ @ivar nickname """ def getUser(self, user): """Return a deferred returning a string""" def buildProtocol(self, addr): """Return a protocol""" class IRCClientFactoryFromService(protocol.ClientFactory): __implements__ = IIRCClientFactory, protocol = IRCReplyBot nickname = None def __init__(self, service): self.service = service def getUser(self, user): return self.service.getUser(user) components.registerAdapter(IRCClientFactoryFromService, IFingerService, IIRCClientFactory) class UserStatusTree(resource.Resource): __implements__ = resource.IResource, def __init__(self, service): resource.Resource.__init__(self) self.service = service self.putChild('RPC2', UserStatusXR(self.service)) def render_GET(self, request): d = self.service.getUsers() def formatUsers(users): l = ['<li><a href="%s">%s</a></li>' % (user, user) for user in users] return '<ul>'+''.join(l)+'</ul>' d.addCallback(formatUsers) d.addCallback(request.write) d.addCallback(lambda _: request.finish()) return server.NOT_DONE_YET def getChild(self, path, request): if path=="": return UserStatusTree(self.service) else: return UserStatus(path, self.service) components.registerAdapter(UserStatusTree, IFingerService, resource.IResource) class UserStatus(resource.Resource): def __init__(self, user, service): resource.Resource.__init__(self) self.user = user self.service = service def render_GET(self, request): d = self.service.getUser(self.user) d.addCallback(cgi.escape) d.addCallback(lambda m: '<h1>%s</h1>'%self.user+'<p>%s</p>'%m) d.addCallback(request.write) d.addCallback(lambda _: request.finish()) return server.NOT_DONE_YET class UserStatusXR(xmlrpc.XMLRPC): def __init__(self, service): xmlrpc.XMLRPC.__init__(self) self.service = service def xmlrpc_getUser(self, user): return self.service.getUser(user) class MemoryFingerService(service.Service): __implements__ = IFingerService, IFingerSetterService def __init__(self, **kwargs): self.users = kwargs def getUser(self, user): return defer.succeed(self.users.get(user, "No such user")) def getUsers(self): return defer.succeed(self.users.keys()) def setUser(self, user, status): self.users[user] = status application = service.Application('finger', uid=1, gid=1) f = MemoryFingerService(moshez='Happy and well') serviceCollection = service.IServiceCollection(application) internet.TCPServer(79, IFingerFactory(f) ).setServiceParent(serviceCollection) internet.TCPServer(8000, server.Site(resource.IResource(f)) ).setServiceParent(serviceCollection) i = IIRCClientFactory(f) i.nickname = 'fingerbot' internet.TCPClient('irc.freenode.org', 6667, i ).setServiceParent(serviceCollection) internet.TCPServer(1079, IFingerSetterFactory(f), interface='127.0.0.1' ).setServiceParent(serviceCollection) |
Source listing - listings/finger/finger19a.py
Aspect-Oriented Programming At last, an example of aspect-oriented programming that isn't about logging or timing. This code is actually useful! Watch how aspect-oriented programming helps you write less code and have fewer dependencies!
至少可以算作是面向方面编程的一个和logging以及timing无关的例子。这段代码很有用!要知道面向方面编程让你写更少的代码,还减小依赖!
翻译:Bruce Who([email protected])
return index-->TwistedTUT
Version: 1.3.0