コード例 #1
0
ファイル: front.py プロジェクト: aaravindanarun/random_bits
def main():
    pika_client = PikaClient()
    database={}
    database['g'] = 'f'
    database['gg'] = 'ff'
    database['ggg'] = 'gff'
    global g_port;
    
    application = tornado.web.Application(
    [(r'/sensor/.*', SensorHandler,dict(database=database)),(r'/.*',MainHandler,dict(database=database))],
#        [(r'/index.html',MainHandler)],
#        [(r'/tom/*',SensorHandler),(r'/index.html',MainHandler)],
#        **{'pika_client': pika_client, 'debug': True}

        #     **{'pika_client': pika_client, 'debug': True}
        #     [(r'/tom/*', Fib)],
             **{'pika_client': pika_client, 'debug': True}
    )
    try:
        port = int(sys.argv[1])  # $ python tornadoweb_pika.py 80
    except:
        port = 8000 
    g_port = port
    application.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_timeout(time.time() + .1, pika_client.connect)
    ioloop.start()
コード例 #2
0
ファイル: wifiWattSrv.py プロジェクト: bwasserm/wifiwatt
def main():
  global tornadoApp
  watermark.printWatermark()

  tornado.options.parse_command_line()

  sockJSRouter = sockjs.tornado.SockJSRouter(SockJSClient, '/socket')

  app = Application(sockJSRouter.urls)
  tornadoApp = app # globals cheating
  ioloop = tornado.ioloop.IOLoop.instance()

  # instance sockJS server
  # app.sockjs = sockjs.tornado.SockJSRouter(SockJSClient, '/socket')
  # for handler in app.sockjs.urls:
  #   print(handler)
  #   print("")
  #   # app.add_handlers(handler[0], handler[1])
  # app.add_handlers(r"*", app.sockjs.urls)

  # instance rabbitMQ server
  app.rabbit = RabbitClient(app, ioloop)
  app.listen(options.port)
  
  ioloop.add_timeout(500, app.rabbit.connect)
  ioloop.start()
コード例 #3
0
ファイル: tweb.py プロジェクト: sethwoodworth/tworld
 def autoreload_handler(self):
     self.twlog.warning('Queueing autoreload shutdown!')
     self.caughtinterrupt = True
     ioloop = tornado.ioloop.IOLoop.instance()
     self.twlog.info('Waiting 1 second for requests to drain...')
     ioloop.add_timeout(datetime.timedelta(seconds=1.0),
                        self.final_autoreload)
コード例 #4
0
    def start_game(self):
        print('starting game')
        self.ended = False

        self.draw()

        self.timers.extend([
            ioloop.add_timeout(
                timedelta(seconds=0.5),
                self.send_later(
                    json.dumps({
                        'state': 'starting',
                        'countdown': 3
                    }))),
            ioloop.add_timeout(
                timedelta(seconds=1),
                self.send_later(
                    json.dumps({
                        'state': 'starting',
                        'countdown': 2
                    }))),
            ioloop.add_timeout(
                timedelta(seconds=1.5),
                self.send_later(
                    json.dumps({
                        'state': 'starting',
                        'countdown': 1
                    }))),
            ioloop.add_timeout(
                timedelta(seconds=2),
                self.send_later(json.dumps({'state': 'started'})))
        ])
コード例 #5
0
ファイル: mediafiles.py プロジェクト: rafi1975/motioneye
    def poll_media_list_process():
        ioloop = tornado.ioloop.IOLoop.instance()
        if _timelapse_process.is_alive(): # not finished yet
            now = datetime.datetime.now()
            delta = now - started[0]
            if delta.seconds < 300: # the subprocess has 5 minutes to complete its job
                ioloop.add_timeout(datetime.timedelta(seconds=0.5), poll_media_list_process)
                read_media_list()

            else: # process did not finish within 2 minutes
                logging.error('timeout waiting for the media listing process to finish')
                
                _timelapse_process.progress = -1

        else: # finished
            read_media_list()
            logging.debug('media listing process has returned %(count)s files' % {'count': len(media_list)})
            
            if not media_list:
                _timelapse_process.progress = -1
                
                return

            pictures = select_pictures(media_list)
            make_movie(pictures)
コード例 #6
0
def main():
    pika_client = PikaClient()
    database={}
    database['g'] = 'f'
    database['gg'] = 'ff'
    database['ggg'] = 'gff'
    global g_port;
    
    application = tornado.web.Application(
    [(r'/sensor/.*', SensorHandler,dict(database=database)),(r'/.*',MainHandler,dict(database=database))],
#        [(r'/index.html',MainHandler)],
#        [(r'/tom/*',SensorHandler),(r'/index.html',MainHandler)],
#        **{'pika_client': pika_client, 'debug': True}

        #     **{'pika_client': pika_client, 'debug': True}
        #     [(r'/tom/*', Fib)],
             **{'pika_client': pika_client, 'debug': True}
    )
    try:
        port = int(sys.argv[1])  # $ python tornadoweb_pika.py 80
    except:
        port = 8000 
    g_port = port
    application.listen(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_timeout(time.time() + .1, pika_client.connect)
    ioloop.start()
コード例 #7
0
ファイル: server.py プロジェクト: thunderace/motioneye
def start_motion():
    import tornado.ioloop
    import config
    import motionctl

    ioloop = tornado.ioloop.IOLoop.instance()
    
    # add a motion running checker
    def checker():
        if ioloop._stopped:
            return
            
        if not motionctl.running() and motionctl.started() and config.get_enabled_local_motion_cameras():
            try:
                logging.error('motion not running, starting it')
                motionctl.start()
            
            except Exception as e:
                logging.error('failed to start motion: %(msg)s' % {
                        'msg': unicode(e)}, exc_info=True)

        ioloop.add_timeout(datetime.timedelta(seconds=settings.MOTION_CHECK_INTERVAL), checker)
    
    motionctl.start()
        
    ioloop.add_timeout(datetime.timedelta(seconds=settings.MOTION_CHECK_INTERVAL), checker)
コード例 #8
0
def start_motion():
    import tornado.ioloop
    import config
    import motionctl

    ioloop = tornado.ioloop.IOLoop.instance()
    
    # add a motion running checker
    def checker():
        if ioloop._stopped:
            return
            
        if not motionctl.running() and motionctl.started() and config.get_enabled_local_motion_cameras():
            try:
                logging.error('motion not running, starting it')
                motionctl.start()
            
            except Exception as e:
                logging.error('failed to start motion: %(msg)s' % {
                        'msg': unicode(e)}, exc_info=True)

        ioloop.add_timeout(datetime.timedelta(seconds=settings.MOTION_CHECK_INTERVAL), checker)
    
    motionctl.start()
        
    ioloop.add_timeout(datetime.timedelta(seconds=settings.MOTION_CHECK_INTERVAL), checker)
コード例 #9
0
    def poll_media_list_process():
        ioloop = tornado.ioloop.IOLoop.instance()
        if _timelapse_process.is_alive():  # not finished yet
            now = datetime.datetime.now()
            delta = now - started[0]
            if delta.seconds < 300:  # the subprocess has 5 minutes to complete its job
                ioloop.add_timeout(datetime.timedelta(seconds=0.5),
                                   poll_media_list_process)
                read_media_list()

            else:  # process did not finish within 2 minutes
                logging.error(
                    'timeout waiting for the media listing process to finish')

                _timelapse_process.progress = -1

        else:  # finished
            read_media_list()
            logging.debug(
                'media listing process has returned %(count)s files' %
                {'count': len(media_list)})

            if not media_list:
                _timelapse_process.progress = -1

                return

            pictures = select_pictures(media_list)
            make_movie(pictures)
コード例 #10
0
def shutdown(server):
    ioloop = tornado.ioloop.IOLoop.instance()
    server.stop()
    
    def finalize():
        ioloop.stop()
        
    ioloop.add_timeout(time.time() + 1.5, finalize)
コード例 #11
0
 def stop_loop():
     now = time.time()
     if now < deadline and (ioloop._callbacks or ioloop._timeouts):
         ioloop.add_timeout(now + 1, stop_loop)
         logger.debug("Waiting for callbacks and timeouts in IOLoop...")
     else:
         ioloop.stop()
         logger.info("Server is shutdown")
コード例 #12
0
ファイル: bindings.py プロジェクト: jelis/chatmotor
    def get(self, injector=None):
        import tornado.ioloop
        import time

        broker_client = injector.get('msg_broker_client')
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.add_timeout(time.time() + 0.01, broker_client.connect)
        return ioloop
コード例 #13
0
ファイル: bindings.py プロジェクト: rahulshukla/chatmotor
    def get(self, injector=None):
        import tornado.ioloop
        import time

        broker_client = injector.get('msg_broker_client')
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.add_timeout(time.time() + 0.01, broker_client.connect)
        return ioloop
コード例 #14
0
def shutdown():
    ioloop = tornado.ioloop.IOLoop.instance()
    LOG.info('Stopping server.')

    def finalize():
        ioloop.stop()
        LOG.info('Stopped.')

    ioloop.add_timeout(time.time() + 1.5, finalize)
コード例 #15
0
ファイル: go.py プロジェクト: mulka/tornado_already_reading
def main():
    parse_command_line()

    ioloop = tornado.ioloop.IOLoop.instance()

    ioloop.add_timeout(timedelta(seconds=1), lambda: tweet_ingester.init_room_stream('follow'))
    ioloop.add_timeout(timedelta(seconds=7), lambda: tweet_ingester.init_room_stream('retweet'))

    ioloop.start()
コード例 #16
0
ファイル: app.py プロジェクト: shizhz/tutu
def main():
    http_server = tornado.httpserver.HTTPServer(Tutu())
    http_server.listen(options.port)

    ioloop = tornado.ioloop.IOLoop.instance()
    if not TEST:
        ioloop.add_timeout(ioloop.time(), registry_marathon_event_handler)

    ioloop.start()
コード例 #17
0
ファイル: server.py プロジェクト: NODCode/nodcode
def main():
    port = int(sys.argv[1])
    config_file = sys.argv[2]

    # queue for waiting answer from rabbit
    queue_answer = 'answer-%s' % port

    # queues for sending create/read messages
    queue_read = 'reading'
    queue_create = 'creation'

    logger_web = Logger('tornado-%s' % port).get()

    config = ConfigParser.ConfigParser()
    config.read(config_file)

    # TODO: check config
    redis_nodes = zip(config.get('rediscluster', 'hosts').split(' '),
                      config.get('rediscluster', 'ports').split(' '))
    rabbit_nodes = zip(config.get('rabbitmq', 'hosts').split(' '),
                       config.get('rabbitmq', 'ports').split(' '))

    startup_nodes = map(lambda node: {'host': node[0],
                                      'port': int(node[1])}, redis_nodes)
    logger_web.info('Redis has config: {0}'.format(startup_nodes))
    session_store = Session(startup_nodes=startup_nodes)

    public_root = os.path.join(os.path.dirname(__file__), 'client')
    application = tornado.web.Application(
        [(r'/', MainHandler, dict(session_store=session_store,
                                  logger=logger_web,
                                  queue_answer=queue_answer,
                                  queue_read=queue_read,
                                  queue_create=queue_create)),
         (r'/(.*)', tornado.web.StaticFileHandler, {'path': public_root})],
        # yeah, it's not secure, but it just for test
        cookie_secret='de973a5e-211f-11e6-bde5-3859f9e0729b'
    )

    logger_pika = Logger('tornado-%s-pika' % port).get()
    pc = PikaClient(logger=logger_pika,
                    queue_answer=queue_answer,
                    queue_read=queue_read,
                    queue_create=queue_create,
                    node_list=rabbit_nodes)
    application.pika = pc

    application.listen(port)
    logger_web.info('Tornado is serving on port {0}.'.format(port))
    ioloop = tornado.ioloop.IOLoop.instance()

    try:
        ioloop.add_timeout(time.time() + .1, pc.connect)
        ioloop.start()
    except:
        pc.stop()
コード例 #18
0
ファイル: init.py プロジェクト: zongmingshu/RobotAIEngine
 def stop_loop():
     ''' 尝试关闭loop
     '''
     now = time.time()
     if now < deadline and (ioloop._callbacks or ioloop._timeouts):
         ioloop.add_timeout(now + 1, stop_loop)
     else:
         # 处理完现有的 callback 和 timeout 后
         ioloop.stop()
         logging.info('Shutdown!')
コード例 #19
0
 def scan(self):
     while self.running:
         if not self.supported_pids:
             # sleep 1s
             current = greenlet.getcurrent()
             ioloop.add_timeout(time.time() + 1, current.switch)
             current.parent.switch()
         for obd2id, pids in self.supported_pids.iteritems():
             for pid in pids:
                 frame = self.query_block(obd2id, 1, pid)
コード例 #20
0
def run():
    application.pika = PikaClient()

    application.listen(TORNADO_PORT)

    ioloop = tornado.ioloop.IOLoop.instance()

    ioloop.add_timeout(IOLOOP_TIMEOUT, application.pika.connect)

    ioloop.start()
コード例 #21
0
ファイル: server.py プロジェクト: Mobisocial/Musubi-iOS-OSS
 def open(self):
     'Websocket Connection opened.'
     
     #Initialize new pika client object for this websocket.
     self.pika_client = PikaClient()
     
     #Assign websocket object to a Pika client object attribute.
     self.pika_client.websocket = self
     
     ioloop.add_timeout(1000, self.pika_client.connect)
コード例 #22
0
    def open(self):
        'Websocket Connection opened.'

        #Initialize new pika client object for this websocket.
        self.pika_client = PikaClient()

        #Assign websocket object to a Pika client object attribute.
        self.pika_client.websocket = self

        ioloop.add_timeout(1000, self.pika_client.connect)
コード例 #23
0
ファイル: canusb.py プロジェクト: Acidburn0zzz/carhack
 def scan(self):
   while self.running:
     if not self.supported_pids:
       # sleep 1s
       current = greenlet.getcurrent()
       ioloop.add_timeout(time.time() + 1, current.switch)
       current.parent.switch()
     for obd2id, pids in self.supported_pids.iteritems():
       for pid in pids:
         frame = self.query_block(obd2id, 1, pid)
コード例 #24
0
ファイル: fakeRaspi.py プロジェクト: bwasserm/wifiwatt
def main():
  tornado.options.parse_command_line()

  app = Application()
  ioloop = tornado.ioloop.IOLoop.instance()

  app.pika = ExamplePublisher(app, ioloop)
  app.listen(options.port)
  
  ioloop.add_timeout(500, app.pika.connect)
  ioloop.start()
コード例 #25
0
ファイル: main.py プロジェクト: sofian86/sandbox
    def open(self, chat_id):
        """Websocket Connection opened."""

        print("WebSocket opened")

        # Initialize new pika client object for this websocket.
        self.pika_client = PikaClient(chat_id)

        # Assign websocket object to a Pika client object attribute.
        self.pika_client.websocket = self

        ioloop.add_timeout(1000, self.pika_client.connect)
コード例 #26
0
ファイル: serve.py プロジェクト: kzahel/tracer
    def handle_message(self, message):
        data = json.loads(message)
        logging.info('recv message from %s %s' % (self.user, data))
        if 'a' in data:
            action = data['a']

        if action == ACTION_TURN:
            data['p'] = self.user.id
            if options.fake_latency:
                ioloop.add_timeout( time.time() + 0.1, functools.partial( self.game.broadcast, data ) )
            else:
                self.game.broadcast( data )
コード例 #27
0
ファイル: obd2.py プロジェクト: stamisass/carhack
    def __init__(self, app, can):
        self.app = app
        self.can = can
        self.can.subscribe(self.read, ids=OBD2_IDS)

        self.read_waiters = defaultdict(set)
        self.read_timeouts = []

        self.supported_pids = []

        start = lambda:greenlet.greenlet(self.init).switch()
        ioloop.add_timeout(time.time() + 2, start)
コード例 #28
0
ファイル: motioneye.py プロジェクト: porolakka/motioneye-jp
    def checker():
        if ioloop._stopped:
            return

        if not motionctl.running() and motionctl.started() and config.has_local_enabled_cameras():
            try:
                logging.error("motion not running, starting it")
                motionctl.start()

            except Exception as e:
                logging.error("failed to start motion: %(msg)s" % {"msg": unicode(e)}, exc_info=True)

        ioloop.add_timeout(datetime.timedelta(seconds=settings.MOTION_CHECK_INTERVAL), checker)
コード例 #29
0
ファイル: tests.py プロジェクト: kouyalong/tornadoblueprint
def test_wraps():
    def exit_callback():
        client = tornado.httpclient.AsyncHTTPClient()
        ret = client.fetch('http://localhost:8000/home/welcome')
        nose.tools.assert_is_not_none(ret)
        tornado.ioloop.IOLoop.current().stop()

    httpserver = tornado.httpserver.HTTPServer(
        blueprint.wraps(tornado.web.Application()))
    httpserver.listen(8000)
    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_timeout(ioloop.time() + 1, exit_callback)
    ioloop.start()
コード例 #30
0
    def open(self):
        'Websocket Connection opened.'

        #Initialize new pika client object for this websocket.
        self.pika_client = PikaClient()

        #Assign websocket object to a Pika client object attribute.
        self.pika_client.websocket = self

        ioloop.add_timeout(1000, self.pika_client.connect)

        chatDB = self.settings['chatDB']
        chatDB.chat.find({'chatID': '1'}).each(self._got_message)
コード例 #31
0
ファイル: canusb.py プロジェクト: Acidburn0zzz/carhack
  def __init__(self, write):
    self.running = True
    self.write = write

    self.read_waiters = defaultdict(set)
    self.read_timeouts = []

    self.supported_pids = dict()

    init = lambda:greenlet.greenlet(self.init).switch()
    ioloop.add_timeout(time.time() + 2, init)

    scan = lambda:greenlet.greenlet(self.scan).switch()
    ioloop.add_timeout(time.time() + 3, scan)
コード例 #32
0
    def __init__(self, write):
        self.running = True
        self.write = write

        self.read_waiters = defaultdict(set)
        self.read_timeouts = []

        self.supported_pids = dict()

        init = lambda: greenlet.greenlet(self.init).switch()
        ioloop.add_timeout(time.time() + 2, init)

        scan = lambda: greenlet.greenlet(self.scan).switch()
        ioloop.add_timeout(time.time() + 3, scan)
コード例 #33
0
ファイル: antares_compiler.py プロジェクト: wenxcs/antares
 def scan_tasks(ioloop):
     try:
       if os.wait3(os.WNOHANG)[0] != 0:
         task_lists.popleft()
         raise ChildProcessError
       ## Still waiting for current task to complete
     except ChildProcessError:
       if task_lists:
         task_step, task_expr = task_lists[0]
         clear_environ(task_expr, task_step)
         os.environ['HTTP_SERVICE'], _ = '', os.environ['HTTP_SERVICE']
         os.spawnlp(os.P_NOWAIT, '/bin/bash', 'bash', '%s/run.sh' % compiler_path)
         os.environ['HTTP_SERVICE'] = _
     ioloop.add_timeout(time.time() + 5, lambda: scan_tasks(ioloop))
コード例 #34
0
def main():
    global db
    global log_db
    # if os.path.isfile("login_token.json") and os.path.isfile("login_user.json"):
    #     in_token = open("login_token.json")
    #     login_token = json.load(in_token)
    #     in_token.close()
    #     RedisHandler.f_hmset(LOGIN_T, login_token)
    #     in_user = open("login_user.json")
    #     SocketHandler.login_user = json.load(in_user)
    #     #util.RedisHandle.f_hmset(LOGIN_U, login_user)
    #     in_user.close()
    #     os.rename("login_token.json", "login_token"+str(long(time()))+".json")
    #     os.rename("login_user.json", "login_user"+str(long(time()))+".json")
    access = logging.getLogger("tornado.access")
    access.addHandler(NullHandler())
    access.propagate = False
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    try:
        util.MemCache.load(str(options.port))
        #util.RedisHandle.f_delete(*[CLIENT_UID_USER,CLIENT_USER_UID,USER_ONLINE_AT,USER_IP_LIST,HTTP_SERVER_INFO])
        ioloop = tornado.ioloop.IOLoop.instance()
        #db_client = motor.MotorReplicaSetClient(hosts_or_uri="127.0.0.1:27017",replicaSet='fbt_repl',io_loop=ioloop)
        #db_client.read_preference = ReadPreference.SECONDARY_ONLY
        #db = db_client.fbt
        #log_db = motor.MotorClient().fbt_log
        #log_db = db_client.fbt_log
        db = motorclient.fbt
        log_db = motorclient.fbt_log
        ResourceStoreManager.set_db(db)
        FBCoinManager.set_db(db)
        UserManager.set_db(db)
        msg_handle.set_db(db)
        LogForUser.set_db(log_db)
        #FBCoinManager.set_update_fb_callback(SocketHandler.update_fb)
        #FBRankManager.initialize() #load rank info from file
        #FBRankTimer.set_io_loop(ioloop)
        #FBRankTimer.run() #backup the weekly and monthly rank

        SocketHandler.set_io_loop(ioloop)
        SocketHandler.init()
        ioloop.add_timeout(
            long(time()) + 3600, lambda: SocketHandler.check_on_line())
        ioloop.start()
    except Exception, e:
        print e
        print "OK. I will exit..."
コード例 #35
0
ファイル: server.py プロジェクト: fabiocerqueira/easydojo
def countdown():
    global countdown_code
    global countdown_time
    global ws_clients
    ioloop = tornado.ioloop.IOLoop.current()
    if countdown_state == 'resume':
        if ws_clients:
            str_time = time.strftime('%M:%S', time.gmtime(countdown_code))
            for s in ws_clients:
                s.write_message(str_time)
        if countdown_code:
            countdown_code -= 1
        else:
            countdown_code = countdown_time
    ioloop.add_timeout(time.time() + 1, countdown)
コード例 #36
0
def main():
    pika_client = PikaClient()
    application = tornado.web.Application(
        [(r'/([0-9]*)', Fib)],
        **{'pika_client': pika_client, 'debug': True}
    )
    try:
        port = int(sys.argv[1])  # $ python tornadoweb_pika.py 80
    except:
        port = 8080
    application.listen(port)
    print "Tornado is serving on port {0}.".format(port)
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_timeout(time.time() + .1, pika_client.connect)
    ioloop.start()
コード例 #37
0
ファイル: server.py プロジェクト: fabiocerqueira/easydojo
def countdown():
    global countdown_code
    global countdown_time
    global ws_clients
    ioloop = tornado.ioloop.IOLoop.current()
    if countdown_state == 'resume':
        if ws_clients:
            str_time = time.strftime('%M:%S', time.gmtime(countdown_code))
            for s in ws_clients:
                s.write_message(str_time)
        if countdown_code:
            countdown_code -= 1
        else:
            countdown_code = countdown_time
    ioloop.add_timeout(time.time() + 1, countdown)
コード例 #38
0
ファイル: fbt_socket.py プロジェクト: BoneLee/FBT
def main():
    global db
    global log_db
    # if os.path.isfile("login_token.json") and os.path.isfile("login_user.json"):
    #     in_token = open("login_token.json")
    #     login_token = json.load(in_token)
    #     in_token.close()
    #     RedisHandler.f_hmset(LOGIN_T, login_token)
    #     in_user = open("login_user.json")
    #     SocketHandler.login_user = json.load(in_user)
    #     #util.RedisHandle.f_hmset(LOGIN_U, login_user)
    #     in_user.close()
    #     os.rename("login_token.json", "login_token"+str(long(time()))+".json")
    #     os.rename("login_user.json", "login_user"+str(long(time()))+".json")
    access = logging.getLogger("tornado.access")
    access.addHandler(NullHandler())
    access.propagate = False
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application(), xheaders=True)
    http_server.listen(options.port)
    try:
        util.MemCache.load(str(options.port))
        #util.RedisHandle.f_delete(*[CLIENT_UID_USER,CLIENT_USER_UID,USER_ONLINE_AT,USER_IP_LIST,HTTP_SERVER_INFO])
        ioloop=tornado.ioloop.IOLoop.instance()
        #db_client = motor.MotorReplicaSetClient(hosts_or_uri="127.0.0.1:27017",replicaSet='fbt_repl',io_loop=ioloop)
        #db_client.read_preference = ReadPreference.SECONDARY_ONLY
        #db = db_client.fbt
        #log_db = motor.MotorClient().fbt_log
        #log_db = db_client.fbt_log
        db = motorclient.fbt
        log_db = motorclient.fbt_log
        ResourceStoreManager.set_db(db)
        FBCoinManager.set_db(db)
        UserManager.set_db(db)
        msg_handle.set_db(db)
        LogForUser.set_db(log_db)
        #FBCoinManager.set_update_fb_callback(SocketHandler.update_fb)
        #FBRankManager.initialize() #load rank info from file
        #FBRankTimer.set_io_loop(ioloop)
        #FBRankTimer.run() #backup the weekly and monthly rank
        
        SocketHandler.set_io_loop(ioloop)
        SocketHandler.init()
        ioloop.add_timeout(long(time()) + 3600, lambda: SocketHandler.check_on_line())
        ioloop.start()
    except Exception, e:
        print e
        print "OK. I will exit..."
コード例 #39
0
 def open(self, ws_url):
     try:
         #tornado.websocket.WebSocketHandler.set_nodelay(True)
         print 'CONNECTED WS: ' + str(self.open_args)
         logger.info('CONNECTED WS: ' + str(self.open_args))
         self.rmq_conn = rmq_conn()
         self.rmq_conn.websocket = self
         rmq_client_id = ws_url.split('-')
         if len(rmq_client_id) == 2 and len(rmq_client_id[0]) == 19 and len(
                 rmq_client_id[1]) == 16:
             self.rmq_conn.rmq_client_id = str(rmq_client_id[1])
             rmq_route = rmq_client_id[0]
             self.rmq_conn.rmq_route = str(rmq_route[3:])
             self.rmq_conn.client_type = rmq_route[0:3]
             self.rmq_conn.queue_name = self.rmq_conn.rmq_route + str(
                 random.randint(1, 66666677)) + 'Q'
             self.id2 = ioloop.add_timeout(0, self.rmq_conn.rmq_connect)
             #self.set_nodelay(True)
         else:
             print 'INVALID URL ( CLOSING CONNECTION ):' + ws_url
             logger.error('INVALID URL ( CLOSING CONNECTION ):' + ws_url)
             self.close()
             return
     except Exception as e:
         print 'WS_ON_CONNECT :' + str(e)
         logger.error('WS_ON_CONNECT :' + str(e))
         self.close()
         return
コード例 #40
0
    def on_open(self, info):
        # type: (ConnectionInfo) -> None
        log_data = dict(extra='[transport=%s]' % (self.session.transport_name,))
        record_request_start_data(log_data)

        ioloop = tornado.ioloop.IOLoop.instance()

        self.authenticated = False
        self.session.user_profile = None
        self.close_info = None # type: CloseErrorInfo
        self.did_close = False

        try:
            self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value
            self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value
        except AttributeError:
            # The request didn't contain the necessary cookie values.  We can't
            # close immediately because sockjs-tornado doesn't expect a close
            # inside on_open(), so do it on the next tick.
            self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values")
            ioloop.add_callback(self.close)
            return

        def auth_timeout():
            # type: () -> None
            self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication")
            self.close()

        self.timeout_handle = ioloop.add_timeout(time.time() + 10, auth_timeout)
        write_log_line(log_data, path='/socket/open', method='SOCKET',
                       remote_ip=info.ip, email='unknown', client_name='?')
コード例 #41
0
ファイル: ws_v0.py プロジェクト: sgowtham441/webshare
 def open(self,ws_url):
     try:
         #tornado.websocket.WebSocketHandler.set_nodelay(True)
         print 'CONNECTED WS: '+str(self.open_args)
         logger.info('CONNECTED WS: '+str(self.open_args))
         self.rmq_conn = rmq_conn()
         self.rmq_conn.websocket = self
         rmq_client_id = ws_url.split('-')
         if len(rmq_client_id) == 2 and len(rmq_client_id[0]) == 19 and len(rmq_client_id[1]) == 16:
             self.rmq_conn.rmq_client_id = str(rmq_client_id[1])
             rmq_route = rmq_client_id[0]
             self.rmq_conn.rmq_route = str(rmq_route[3:])
             self.rmq_conn.client_type = rmq_route[0:3]
             self.rmq_conn.queue_name = self.rmq_conn.rmq_route+str(random.randint(1,66666677))+'Q'
             self.id2 = ioloop.add_timeout(0, self.rmq_conn.rmq_connect)
             #self.set_nodelay(True)
         else:
             print 'INVALID URL ( CLOSING CONNECTION ):'+ws_url
             logger.error('INVALID URL ( CLOSING CONNECTION ):'+ws_url)
             self.close()
             return
     except Exception as e:
         print 'WS_ON_CONNECT :'+str(e)
         logger.error('WS_ON_CONNECT :'+str(e))
         self.close()
         return
コード例 #42
0
def fech_trends_loop():
    PERIOD = 30
    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_timeout(time.time() + PERIOD, fech_trends_loop)
    trends = []
    for idx, trend in enumerate(api.trends_place(JP)[0]['trends'], 1):
        value = {
            "rank": str(idx),
            "name": trend["name"],
            "volume": trend["tweet_volume"],
            "url": trend["url"]
        }
        trends.append(value)
    TwitterTrendWebSocketHandler.trends_cache = trends
    json_str = json.dumps(trends)
    TwitterTrendWebSocketHandler.send_updates(json_str)
コード例 #43
0
ファイル: socket.py プロジェクト: aakash-cr7/zulip
    def on_open(self, info):
        # type: (ConnectionInfo) -> None
        log_data = dict(extra='[transport=%s]' % (self.session.transport_name,))
        record_request_start_data(log_data)

        ioloop = tornado.ioloop.IOLoop.instance()

        self.authenticated = False
        self.session.user_profile = None
        self.close_info = None # type: CloseErrorInfo
        self.did_close = False

        try:
            self.browser_session_id = info.get_cookie(settings.SESSION_COOKIE_NAME).value
            self.csrf_token = info.get_cookie(settings.CSRF_COOKIE_NAME).value
        except AttributeError:
            # The request didn't contain the necessary cookie values.  We can't
            # close immediately because sockjs-tornado doesn't expect a close
            # inside on_open(), so do it on the next tick.
            self.close_info = CloseErrorInfo(403, "Initial cookie lacked required values")
            ioloop.add_callback(self.close)
            return

        def auth_timeout():
            # type: () -> None
            self.close_info = CloseErrorInfo(408, "Timeout while waiting for authentication")
            self.close()

        self.timeout_handle = ioloop.add_timeout(time.time() + 10, auth_timeout)
        write_log_line(log_data, path='/socket/open', method='SOCKET',
                       remote_ip=info.ip, email='unknown', client_name='?')
コード例 #44
0
ファイル: robot.py プロジェクト: zilveer/HTML5-Texas-Hold-em-
    def handle_standup(self, data):
        pika.log.info("Handle stand up [Start]")
        pika.log.info("\t\t %s", data)

        if self.user_id in data:
            if data[self.user_id]["seat_no"] == self.seat:
                self.stake = 0
                if self.asset <= 200:
                    ioloop = tornado.ioloop.IOLoop.instance()
                    ioloop.add_timeout(time.time() + 10, self.refill)
                else:
                    ioloop = tornado.ioloop.IOLoop.instance()
                    ioloop.add_timeout(time.time() + 10, self.list_room)

                self.is_sit_down = False

        pika.log.info("Handle stand up [End]")
コード例 #45
0
ファイル: lightgames.py プロジェクト: smab/playhouse-web
def set_timeout(deadline, callback):
    """
    Runs `callback` at the time `deadline` from Tornado's I/O loop.

    Thin wrapper over Tornado's `IOLoop.add_timeout`.
    """
    ioloop = tornado.ioloop.IOLoop.instance()
    return ioloop.add_timeout(deadline, callback)
コード例 #46
0
 def test_get_client2(self):
     c = ClientPool(max_size=2)
     client1 = yield c.get_connected_client()
     self.assertTrue(isinstance(client1, Client))
     client2 = yield c.get_connected_client()
     self.assertTrue(isinstance(client2, Client))
     ioloop = tornado.ioloop.IOLoop.instance()
     deadline = time.time() + 1
     cb = functools.partial(self._test_get_client2_cb, c, client1)
     self._test_get_client2_cb_called = False
     ioloop.add_timeout(deadline, cb)
     client3 = yield c.get_connected_client()
     self.assertTrue(self._test_get_client2_cb_called)
     self.assertTrue(client1 == client3)
     c.release_client(client2)
     c.release_client(client3)
     c.destroy()
コード例 #47
0
 def _timer_start(self):
     self._timer_stop()
     if self._single:
         ioloop = tornado.ioloop.IOLoop.instance()
         self._timer = ioloop.add_timeout(datetime.timedelta(milliseconds=self.interval), self._on_timer)
     else:
         self._timer = tornado.ioloop.PeriodicCallback(self._on_timer, self.interval)
     self._timer.start()
コード例 #48
0
ファイル: test_pool.py プロジェクト: thefab/tornadis
 def test_get_client2(self):
     c = ClientPool(max_size=2)
     client1 = yield c.get_connected_client()
     self.assertTrue(isinstance(client1, Client))
     client2 = yield c.get_connected_client()
     self.assertTrue(isinstance(client2, Client))
     ioloop = tornado.ioloop.IOLoop.instance()
     deadline = time.time() + 1
     cb = functools.partial(self._test_get_client2_cb, c, client1)
     self._test_get_client2_cb_called = False
     ioloop.add_timeout(deadline, cb)
     client3 = yield c.get_connected_client()
     self.assertTrue(self._test_get_client2_cb_called)
     self.assertTrue(client1 == client3)
     c.release_client(client2)
     c.release_client(client3)
     c.destroy()
コード例 #49
0
ファイル: Pubnub.py プロジェクト: NZWDDY/pubnub-ommshot
        def substabizel():
            ## STOP CONNECTION?
            if not self.subscriptions[channel]['connected']:
                return

            def sub_callback(response):
                ## STOP CONNECTION?
                if not self.subscriptions[channel]['connected']:
                    return

                ## CONNECTED CALLBACK
                if not self.subscriptions[channel]['first'] :
                    self.subscriptions[channel]['first'] = True
                    connectcb()

                ## PROBLEM?
                if not response:
                    def time_callback(_time):
                        if not _time:
                            ioloop.add_timeout(time.time()+1, substabizel)
                            return errorback("Lost Network Connection")
                        else:
                            ioloop.add_timeout(time.time()+1, substabizel)

                    ## ENSURE CONNECTED (Call Time Function)
                    return self.time({ 'callback' : time_callback })

                self.subscriptions[channel]['timetoken'] = response[1]
                substabizel()

                for message in response[0]:
                    callback(message)

            ## CONNECT TO PUBNUB SUBSCRIBE SERVERS
            try :
                self._request( [
                    'subscribe',
                    self.subscribe_key,
                    channel,
                    '0',
                    str(self.subscriptions[channel]['timetoken'])
                ], sub_callback )
            except :
                ioloop.add_timeout(time.time()+1, substabizel)
                return
コード例 #50
0
ファイル: robot.py プロジェクト: hackur/HTML5-Texas-Hold-em-
    def handle_standup(self, data):
        pika.log.info( "Handle stand up [Start]")
        pika.log.info( "\t\t %s", data)

        if self.user_id in data:
            if data[self.user_id]["seat_no"]==self.seat:
                self.stake = 0
                if self.asset <= 200:
                    ioloop    = tornado.ioloop.IOLoop.instance()
                    ioloop.add_timeout(time.time() + 10, self.refill)
                else:
                    ioloop    = tornado.ioloop.IOLoop.instance()
                    ioloop.add_timeout(time.time() + 10, self.list_room)

                self.is_sit_down = False


        pika.log.info( "Handle stand up [End]")
コード例 #51
0
ファイル: mediafiles.py プロジェクト: rafi1975/motioneye
    def poll_process():
        ioloop = tornado.ioloop.IOLoop.instance()
        if process.is_alive(): # not finished yet
            now = datetime.datetime.now()
            delta = now - started
            if delta.seconds < 120:
                ioloop.add_timeout(datetime.timedelta(seconds=0.5), poll_process)
                read_media_list()
            
            else: # process did not finish within 2 minutes
                logging.error('timeout waiting for the media listing process to finish')
                
                callback(None)

        else: # finished
            read_media_list()
            logging.debug('media listing process has returned %(count)s files' % {'count': len(media_list)})
            callback(media_list)
コード例 #52
0
 def _timer_start(self):
     self._timer_stop()
     if self._single:
         ioloop = tornado.ioloop.IOLoop.instance()
         self._timer = ioloop.add_timeout(
             datetime.timedelta(milliseconds=self.interval), self._on_timer)
     else:
         self._timer = tornado.ioloop.PeriodicCallback(
             self._on_timer, self.interval)
     self._timer.start()
コード例 #53
0
ファイル: Pubnub.py プロジェクト: simpx/pubnub-api
        def substabizel():
            ## STOP CONNECTION?
            if not self.subscriptions[channel]['connected']:
                return

            def sub_callback(response):
                ## STOP CONNECTION?
                if not self.subscriptions[channel]['connected']:
                    return

                ## CONNECTED CALLBACK
                if not self.subscriptions[channel]['first']:
                    self.subscriptions[channel]['first'] = True
                    connectcb()

                ## PROBLEM?
                if not response:

                    def time_callback(_time):
                        if not _time:
                            ioloop.add_timeout(time.time() + 1, substabizel)
                            return errorback("Lost Network Connection")
                        else:
                            ioloop.add_timeout(time.time() + 1, substabizel)

                    ## ENSURE CONNECTED (Call Time Function)
                    return self.time({'callback': time_callback})

                self.subscriptions[channel]['timetoken'] = response[1]
                substabizel()

                for message in response[0]:
                    callback(message)

            ## CONNECT TO PUBNUB SUBSCRIBE SERVERS
            try:
                self._request([
                    'subscribe', self.subscribe_key, channel, '0',
                    str(self.subscriptions[channel]['timetoken'])
                ], sub_callback)
            except:
                ioloop.add_timeout(time.time() + 1, substabizel)
                return
コード例 #54
0
ファイル: match_server.py プロジェクト: gtagency/ascendency
 def refresh_timeout(self, callback, timeout=None):
     if self.callback is not None:
         raise MultipleRequest
     if self.replies is None:
         raise InvalidRequest
     if self.timeout is not None:
         ioloop.remove_timeout(self.timeout)
         self.timeout = None
     self.callback = callback
     if timeout is not None:
         self.timeout = ioloop.add_timeout(
             datetime.timedelta(seconds=timeout), self._timeout)
コード例 #55
0
ファイル: Server.py プロジェクト: brunnels/aquapi
    def _Update(self) :

        for deviceName,device in self.application.controller.devices.iteritems() :
            self._UpdateDeviceDescription(deviceName, device)

            for variableName,variable in device.GetVariables().iteritems() :
                self._UpdateVarDescription(deviceName, variableName, variable)
                self._UpdateVarValue(deviceName, variableName, device.Get(variableName))

                                   
        ioloop = tornado.ioloop.IOLoop.instance()
        self.timeout = ioloop.add_timeout(ioloop.time() + .25, self._Update)
コード例 #56
0
ファイル: match_server.py プロジェクト: gtagency/ascendency
 def refresh_timeout(self, callback, timeout=None):
     if self.callback is not None:
         raise MultipleRequest
     if self.replies is None:
         raise InvalidRequest
     if self.timeout is not None:
         ioloop.remove_timeout(self.timeout)
         self.timeout = None
     self.callback = callback
     if timeout is not None:
         self.timeout = ioloop.add_timeout(
             datetime.timedelta(seconds=timeout), self._timeout)
コード例 #57
0
    def draw(self):
        self.background.g = (self.background.g + 5) % 255
        # Draw background
        pixels = [[self.background] * 17 for i in range(11)]

        # Draw positions (boards)
        player1 = self.players[0]
        player2 = self.players[1]

        for y in range(
                player1.position - 2,
                player1.position + 2,
        ):
            if y < 0:
                y = 0
            elif y > 10:
                y = 10
            pixels[y][0] = RGB(50, 255, 0)
            pixels[y][1] = RGB(50, 255, 0)

        for y in range(
                player2.position - 2,
                player2.position + 2,
        ):
            if y < 0:
                y = 0
            elif y > 10:
                y = 10
            pixels[y][15] = RGB(50, 0, 255)
            pixels[y][16] = RGB(50, 0, 255)

        # Draw ball
        for x in range(self.ball[0] - 1, self.ball[0] + 1):
            for y in range(self.ball[1] - 1, self.ball[1] + 1):
                pixels[y][x] = RGB(255, 255, 255)

        if ser:
            print('starting to send data')
            if ser.in_waiting:
                in_data = ser.read(ser.in_waiting)
                print("SERIAL:", in_data)
            for (i, line) in enumerate(pixels):
                out_data = b'GO{}{}'.format(chr(i), ''.join(map(str, line)))
                print('sending', out_data)
                ser.write(out_data)
                print('done sending.')

                if ser.in_waiting:
                    in_data = ser.read(ser.in_waiting)
                    print("SERIAL:", in_data)

        self.draw_timeout = ioloop.add_timeout(timedelta(microseconds=50000),
                                               self.draw)
コード例 #58
0
def main(conf):
    user = conf['user']
    password = conf['password']
    host = conf['host']
    database = conf['database']
    serviceid = conf['serviceid']
    useragent = conf['useragent']

    ioloop = tornado.ioloop.IOLoop.instance()

    logger = setup_logging()
    conn_ctx = SqlConnectionCtx(user, password, host, database, logger)

    populate_db = Populate_db(ioloop, serviceid, useragent, logger, conn_ctx)
    cb = populate_db.select_update_tick
    ioloop.add_timeout(datetime.timedelta(seconds=1), cb)

    delete_inactive = DeleteInactive(ioloop, logger, conn_ctx)
    cb = delete_inactive.delete_tick
    ioloop.add_timeout(datetime.timedelta(seconds=1), cb)

    summary_tbl_update = SummaryTableUpdate(ioloop, logger, conn_ctx)
    cb = summary_tbl_update.avg_player_rating_tick
    ioloop.add_timeout(datetime.timedelta(seconds=1), cb)

    try:
        ioloop.start()
    except KeyboardInterrupt:
        ioloop.stop()

    conn_ctx.close()