本文整理汇总了Python中twisted.internet.defer.DeferredLock类的典型用法代码示例。如果您正苦于以下问题:Python DeferredLock类的具体用法?Python DeferredLock怎么用?Python DeferredLock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DeferredLock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Client
class Client(object):
def __init__(self, specFilename, exchange='signals'):
self.exchange = exchange
spec = txamqp.spec.load(specFilename)
delegate = TwistedDelegate()
self.clientConnected = ClientCreator(reactor, AMQClient,
delegate=delegate, vhost="/",
spec=spec).connectTCP("localhost", 5672)
self.conn = None
self.chan = None
self.finishLock = DeferredLock()
@inlineCallbacks
def finishChannelOpen(self):
yield self.finishLock.acquire()
if self.conn is None:
print "opening connection for", self
self.conn = yield self.clientConnected
authentication = {"LOGIN": "guest", "PASSWORD": "guest"}
yield self.conn.start(authentication)
if self.chan is None:
self.chan = yield self.conn.channel(1)
yield self.chan.channel_open()
yield self.newChan()
print "made channel for", self
self.finishLock.release()
def newChan(self):
# called once when the new channel is opened
return succeed(None)
示例2: NotificationConnector
class NotificationConnector(object):
"""Provide ready-to-use AMQP channels."""
def __init__(self, service, clock=reactor):
"""
@param service: An object implementing the same whenConnected() API as
the twisted.application.internet.ClientService class.
@param clock: An object implementing IReactorTime.
"""
self._service = service
self._clock = clock
self._channel = None
self._channel_lock = DeferredLock()
@inlineCallbacks
def __call__(self):
"""
@return: A deferred firing with a ready-to-use txamqp.protocol.Channel.
"""
# Serialize calls, in order to setup new channels only once.
yield self._channel_lock.acquire()
try:
if self._channel and self._channel.client.closed:
# If we have a client but it's closed, let's wait for it to be
# fully disconnected and spin a reactor iteration to give
# change to the AMQClient.connectionLost callback chain to
# settle (in particular our ClientService will be notified and
# will start connecting again).
yield self._channel.client.disconnected.wait()
yield deferLater(self._clock, 0, lambda: None)
client = yield self._service.whenConnected()
channel = yield client.channel(1)
# Check if we got a new channel, and initialize it if so.
if channel is not self._channel:
self._channel = channel
yield self._channel.channel_open()
# This tells the broker to deliver us at most one message at
# a time to support using multiple processes (e.g. in a
# load-balanced/HA deployment). If NotificationSource.get()
# gets called against the same UUID first by process A and then
# when it completes by process B, we're guaranteed that process
# B will see the very next message in the queue, because
# process A hasn't fetched any more messages than the one it
# received. See #729140.
yield self._channel.basic_qos(prefetch_count=1)
finally:
self._channel_lock.release()
returnValue(self._channel)
示例3: emailer
class emailer( LabradServer ):
name = 'Email Server'
@inlineCallbacks
def initServer( self ):
self.username, self.fromaddr, self.password = yield self.getInfoReg()
self.password = base64.b64decode(self.password)
self.toaddrs = {}
self.smtp = 'smtp.gmail.com:587'
self.sending = DeferredLock()
@inlineCallbacks
def getInfoReg(self):
reg = self.client.registry
yield reg.cd(['Servers','Email Server'])
username = yield reg.get('username')
fromaddr = yield reg.get('address')
password = yield reg.get('password')
returnValue([username,fromaddr,password])
@setting(0, "Set Recipients", recepients = '*s', returns = '')
def setRecepients(self, c, recepients):
"""Set the recipients of the email as a list of strings of email addresses"""
self.toaddrs[c.ID] = recepients
@setting(1, "Send", subject = 's', message = 's', returns = '')
def selectDP(self, c, subject, message):
"""Select Double Pass in the current context"""
if not self.toaddrs[c.ID]: raise Exception("Recipients not set")
yield self.sending.acquire()
session = smtplib.SMTP(self.smtp)
session.starttls()
session.login(self.username,self.password)
toaddrs = self.toaddrs[c.ID]
msg = MIMEMultipart()
msg['From'] = self.fromaddr
msg['To'] = COMMASPACE.join(toaddrs)
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
session.sendmail(self.fromaddr, toaddrs, msg.as_string())
session.quit()
self.sending.release()
def initContext(self, c):
"""Initialize a new context object."""
pass
def expireContext(self, c):
del(self.toaddrs[c.ID])
示例4: Pulser_729
class Pulser_729(LabradServer):
name = 'Pulser_729'
def initServer(self):
self.api = api()
self.inCommunication = DeferredLock()
self.initializeBoard()
def initializeBoard(self):
connected = self.api.connectOKBoard()
if not connected:
raise Exception("Pulser Not Found")
@setting(0, 'Reset DDS', returns = '')
def resetDDS(self , c):
"""
Reset the ram position to 0
"""
yield self.inCommunication.acquire()
yield deferToThread(self.api.resetAllDDS)
self.inCommunication.release()
@setting(1, "Program DDS", program = '*(is)', returns = '')
def programDDS(self, c, program):
"""
Programs the DDS, the input is a tuple of channel numbers and buf objects for the channels
"""
yield self.inCommunication.acquire()
yield deferToThread(self._programDDSSequence, program)
self.inCommunication.release()
@setting(2, "Reinitialize DDS", returns = '')
def reinitializeDDS(self, c):
"""
Reprograms the DDS chip to its initial state
"""
yield self.inCommunication.acquire()
yield deferToThread(self.api.initializeDDS)
self.inCommunication.release()
def _programDDSSequence(self, program):
'''takes the parsed dds sequence and programs the board with it'''
for chan, buf in program:
self.api.setDDSchannel(chan)
self.api.programDDS(buf)
self.api.resetAllDDS()
def wait(self, seconds, result=None):
"""Returns a deferred that will be fired later"""
d = Deferred()
reactor.callLater(seconds, d.callback, result)
return d
示例5: acquire
def acquire(self, timeout=None):
"""
This method operates the same as :meth:`DeferredLock.acquire` does
except it requires a timeout argument.
:param int timeout:
The number of seconds to wait before timing out.
:raises LockTimeoutError:
Raised if the timeout was reached before we could acquire
the lock.
"""
assert timeout is None \
or isinstance(timeout, (int, float)) and timeout > 0
lock = DeferredLock.acquire(self)
if timeout is None:
return lock
# Schedule a call to trigger finished.errback() which will raise
# an exception. If lock finishes first however cancel the timeout
# and unlock the lock by calling finished.
finished = Deferred()
lock.addCallback(
self._cancel_timeout,
reactor.callLater(timeout, self._timeout, finished))
lock.addCallback(self._call_callback, finished)
return finished
示例6: __init__
def __init__(self, omegleProto):
"""
Initializes an L{OmegleBot}.
@param omegleProto: an instance of a protocol that implements:
* typingCallback: when the stranger is typing
* stoppedTypingCallback: stranger no longer typing
* disconnectCallback: stranger OR bot has disconnected
* messageCallback: when the stranger has sent us a message
* recaptchaFailedCallback: when our submitted captcha fails
* recaptchaRequiredCallback: when omegle requires a captcha
* connectCallback: when we have found a stranger
* waitingCallback: when we are waiting for a stranger
"""
for callback_name in ('typingCallback',
'stoppedTypingCallback',
'disconnectCallback',
'messageCallback',
'recaptchaFailedCallback',
'recaptchaRequiredCallback',
'connectCallback',
'waitingCallback',
):
setattr(self, callback_name, getattr(omegleProto, callback_name, None))
self.status = DISCONNECTED
self.server = None
self.id = None
self.lock = DeferredLock()
self.activeRequests = set()
self.challenge = None
self.image = None
示例7: initServer
def initServer(self):
self.api = api()
self.channelDict = hardwareConfiguration.channelDict
self.collectionTime = hardwareConfiguration.collectionTime
self.collectionMode = hardwareConfiguration.collectionMode
self.sequenceType = hardwareConfiguration.sequenceType
self.isProgrammed = hardwareConfiguration.isProgrammed
self.timeResolution = float(hardwareConfiguration.timeResolution)
self.ddsDict = hardwareConfiguration.ddsDict
self.timeResolvedResolution = hardwareConfiguration.timeResolvedResolution
self.remoteChannels = hardwareConfiguration.remoteChannels
self.collectionTimeRange = hardwareConfiguration.collectionTimeRange
self.sequenceTimeRange = hardwareConfiguration.sequenceTimeRange
self.haveSecondPMT = hardwareConfiguration.secondPMT
self.haveDAC = hardwareConfiguration.DAC
self.inCommunication = DeferredLock()
self.clear_next_pmt_counts = 0
self.hwconfigpath = os.path.dirname(inspect.getfile(hardwareConfiguration))
print self.hwconfigpath
#LineTrigger.initialize(self)
#self.initializeBoard()
#yield self.initializeRemote()
#self.initializeSettings()
#yield self.initializeDDS()
self.ddsLock = True
self.listeners = set()
示例8: __init__
def __init__(self, config=None):
ApplicationSession.__init__(self, config)
global live
live = self
self.logger = logging.getLogger('Live')
self.logger.info("Config: %s", config)
self.account_id = config.extra['authid']
self.secret = config.extra['secret']
if '-' not in self.account_id:
self.account_id = "local-%s" % self.account_id
self.authid = '%s:%s' % (self.account_id, self.secret[-7:])
self.joined = False
self.lock = DeferredLock()
self.checks = {}
self.workers = {}
self.CallOptions = CallOptions()
示例9: __init__
def __init__(self, priority):
self._lock = DeferredLock()
self.priority = str(priority)
self.is_shutdown = False
self.state_pub = state_publisher.StatePublisher(())
self.flush()
reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)
示例10: __init__
def __init__(self, publisher, ignoreBuilders=None, send_logs=False,
max_connect_time=600, max_idle_time=300, heartbeat_time=900):
self.publisher = publisher
self.send_logs = send_logs
self.ignoreBuilders = []
if ignoreBuilders:
for i in ignoreBuilders:
if isinstance(i, basestring):
self.ignoreBuilders.append(re.compile(i))
else:
assert hasattr(i, 'match') and callable(i.match)
self.ignoreBuilders.append(i)
self.watched = []
self.max_connect_time = max_connect_time
self.max_idle_time = max_idle_time
self.heartbeat_time = heartbeat_time
self._disconnect_timer = None
self._idle_timer = None
# Lock to make sure only one thread is active at a time
self._thread_lock = DeferredLock()
# Set up heartbeat
self._heartbeat_loop = LoopingCall(self.heartbeat)
StatusPush.__init__(self, PulseStatus.pushEvents, filter=False)
示例11: __init__
def __init__(self, cxn, context, dataset):
super(Dataset, self).__init__()
self.accessingData = DeferredLock()
self.cxn = cxn
self.context = context # context of the first dataset in the window
self.dataset = dataset
self.data = None
self.setupDataListener(self.context)
示例12: initServer
def initServer(self):
self.api_dac = api_dac()
self.inCommunication = DeferredLock()
connected = self.api_dac.connectOKBoard()
if not connected:
raise Exception ("Could not connect to DAC")
self.d = yield self.initializeDAC()
self.listeners = set()
示例13: __init__
def __init__(self, name, conf):
_log.info("CF_INIT %s", name)
self.name, self.conf = name, conf
self.channel_dict = defaultdict(list)
self.iocs = dict()
self.client = None
self.currentTime = getCurrentTime
self.lock = DeferredLock()
示例14: __init__
def __init__(self, consumer):
self.consumer = consumer
assert IConsumer.implementedBy(consumer.__class__)
self._producers = []
self._sendingLock = DeferredLock()
self._localHeaderLength = 0
self._centralDirectoryLength = 0
示例15: initServer
def initServer(self):
self.channelDict = hardwareConfiguration.channelDict
self.collectionTime = hardwareConfiguration.collectionTime
self.collectionMode = hardwareConfiguration.collectionMode
self.sequenceType = hardwareConfiguration.sequenceType
self.isProgrammed = hardwareConfiguration.isProgrammed
self.inCommunication = DeferredLock()
self.connectOKBoard()
self.listeners = set()