How to use the twisted.internet.reactor function in Twisted

To help you get started, we’ve selected a few Twisted examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github OpenObservatory / ooniprobe-debian / ooni / nettests / blocking / web_connectivity.py View on Github external
def experiment_tcp_connect(self, socket):
        log.msg("* connecting to {}".format(socket))
        ip_address, port = socket.split(":")
        port = int(port)
        result = {
            'ip': ip_address,
            'port': port,
            'status': {
                'success': None,
                'failure': None,
                'blocked': None
            }
        }
        point = TCP4ClientEndpoint(reactor, ip_address, port)
        d = point.connect(TCPConnectFactory())
        @d.addCallback
        def cb(p):
            result['status']['success'] = True
            result['status']['blocked'] = False
            self.report['tcp_connect'].append(result)

        @d.addErrback
        def eb(failure):
            result['status']['success'] = False
            result['status']['failure'] = failureToString(failure)
            self.report['tcp_connect'].append(result)

        return d
github twisted / twisted / doc / core / howto / tutorial / listings / finger / finger22.py View on Github external
def _read(self):
        self.users.clear()
        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)
github Nikasa1889 / FaceDetectionStream / echoServer.py View on Github external
if __name__ == '__main__':

    log.startLogging(sys.stdout)

    ServerFactory = BroadcastServerFactory
    # ServerFactory = BroadcastPreparedServerFactory

    factory = ServerFactory(u"ws://127.0.0.1:9000")
    factory.protocol = BroadcastServerProtocol
    listenWS(factory)

    webdir = File(".")
    web = Site(webdir)
    reactor.listenTCP(8080, web)

    reactor.run()
github shaunduncan / helga / helga / plugins / reminders.py View on Github external
reminder = db.reminders.find_one(reminder_id)
    if not reminder:
        logger.error('Tried to locate reminder %s, but it returned None', reminder_id)
        _scheduled.discard(reminder_id)
        return

    client.msg(reminder['channel'], reminder['message'])

    # If this repeats, figure out the next time
    if 'repeat' in reminder:
        # Update the record
        reminder['when'], day_delta = next_occurrence(reminder)
        db.reminders.save(reminder)

        _scheduled.add(reminder_id)
        reactor.callLater(day_delta * 86400, _do_reminder, reminder_id, client)
    else:
        _scheduled.discard(reminder_id)
        db.reminders.remove(reminder_id)
github OpenObservatory / ooniprobe-debian / ooni / ui / web / server.py View on Github external
lock.release()

    def notify(self, event=None):
        self.lock.acquire().addCallback(self._notify, event)

    def get(self):
        d = defer.Deferred()
        self.deferred_subscribers.append(d)
        return d

class WebUIAPI(object):
    app = Klein()
    # Maximum number in seconds after which to return a result even if no
    # change happened.
    _long_polling_timeout = 30
    _reactor = reactor
    _enable_xsrf_protection = True

    def __init__(self, config, director, scheduler, _reactor=reactor):
        self._reactor = reactor
        self.director = director
        self.scheduler = scheduler

        self.config = config
        self.measurement_path = FilePath(config.measurements_directory)

        # We use a double submit token to protect against XSRF
        rng = SystemRandom()
        token_space = string.letters+string.digits
        self._xsrf_token = b''.join([rng.choice(token_space)
                                    for _ in range(30)])
github davidfischer-ch / pytoolbox / pytoolbox / network / smpte2022 / bin / TwistedFecGenerator.py View on Github external
def handle_stop_signal(SIGNAL, stack):
        log.info(u'\nGenerator stopped\n')
        reactor.stop()
github nortd / driveboardapp / backend / bottle.py View on Github external
def run(self, handler):
        from twisted.web import server, wsgi
        from twisted.python.threadpool import ThreadPool
        from twisted.internet import reactor
        thread_pool = ThreadPool()
        thread_pool.start()
        reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop)
        factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler))
        reactor.listenTCP(self.port, factory, interface=self.host)
        reactor.run()
github knowitnothing / btcx / demo_1.py View on Github external
btcchina_pool.start(10)

    bitstamp_cli = bitstamp.create_client()
    bitstamp_cli.evt.listen('trade_fetch', plot.bitstamp_trade)
    bitstamp_cli.transactions(timedelta=60*60) # Trades from last hour.
    # Get the last trades each x seconds.
    bitstamp_pool = task.LoopingCall(bitstamp_cli.transactions, timedelta=60)
    bitstamp_pool.start(10, now=False) # x seconds.


    print('Showing GUI..')
    plot.show()
    plot.raise_()

    reactor.addSystemEventTrigger('after', 'shutdown', app.quit)
    reactor.run()
github MaxMotovilov / adstream-js-frameworks / examples / booze / booze.py View on Github external
from twisted.web import server
	from twisted.web.wsgi import WSGIResource
	from twisted.python.threadpool import ThreadPool
	from twisted.python import log
	from twisted.internet import reactor
	from twisted.application import service, strports

	# Create and start a thread pool,
	wsgiThreadPool = ThreadPool(1,1)
	wsgiThreadPool.start()

	# ensuring that it will be stopped when the reactor shuts down
	reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)

	reactor.listenTCP( port, server.Site( WSGIResource(reactor, wsgiThreadPool, wsgi_application) ) )
	log.startLogging( log.FileLogObserver( sys.stderr ) )
	reactor.run()