@implementer
(interfaces.IProtocolFactory, interfaces.ILoggingContext)
@_oldStyle
class
Factory:
"""
This is a factory which produces protocols.
By default, buildProtocol will create a protocol of the class given in
self.protocol.
"""
# put a subclass of Protocol here:
protocol
=
None
numPorts
=
0
noisy
=
True
@classmethod
def
forProtocol(
cls
, protocol,
*
args,
*
*
kwargs):
"""
Create a factory for the given protocol.
It sets the C{protocol} attribute and returns the constructed factory
instance.
@param protocol: A L{Protocol} subclass
@param args: Positional arguments for the factory.
@param kwargs: Keyword arguments for the factory.
@return: A L{Factory} instance wired up to C{protocol}.
"""
factory
=
cls
(
*
args,
*
*
kwargs)
factory.protocol
=
protocol
return
factory
def
logPrefix(
self
):
"""
Describe this factory for log messages.
"""
return
self
.__class__.__name__
def
doStart(
self
):
"""Make sure startFactory is called.
Users should not call this function themselves!
"""
if
not
self
.numPorts:
if
self
.noisy:
_loggerFor(
self
).info(
"Starting factory {factory!r}"
,
factory
=
self
)
self
.startFactory()
self
.numPorts
=
self
.numPorts
+
1
def
doStop(
self
):
"""Make sure stopFactory is called.
Users should not call this function themselves!
"""
if
self
.numPorts
=
=
0
:
# this shouldn't happen, but does sometimes and this is better
# than blowing up in assert as we did previously.
return
self
.numPorts
=
self
.numPorts
-
1
if
not
self
.numPorts:
if
self
.noisy:
_loggerFor(
self
).info(
"Stopping factory {factory!r}"
,
factory
=
self
)
self
.stopFactory()
def
startFactory(
self
):
"""This will be called before I begin listening on a Port or Connector.
It will only be called once, even if the factory is connected
to multiple ports.
This can be used to perform 'unserialization' tasks that
are best put off until things are actually running, such
as connecting to a database, opening files, etcetera.
"""
def
stopFactory(
self
):
"""This will be called before I stop listening on all Ports/Connectors.
This can be overridden to perform 'shutdown' tasks such as disconnecting
database connections, closing files, etc.
It will be called, for example, before an application shuts down,
if it was connected to a port. User code should not call this function
directly.
"""
def
buildProtocol(
self
, addr):
"""
Create an instance of a subclass of Protocol.
The returned instance will handle input on an incoming server
connection, and an attribute "factory" pointing to the creating
factory.
Alternatively, L{None} may be returned to immediately close the
new connection.
Override this method to alter how Protocol instances get created.
@param addr: an object implementing L{twisted.internet.interfaces.IAddress}
"""
p
=
self
.protocol()
p.factory
=
self
return
p