def main():
    try:
        tornado.options.parse_command_line()
        application = tornado.web.Application([
            (r'/', OverviewHandler),
            (r'/mogrify', MogrifyHandler),
            (r'/query', SingleQueryHandler),
            (r'/hstore', HstoreQueryHandler),
            (r'/json', JsonQueryHandler),
            (r'/transaction', TransactionHandler),
            (r'/multi_query', MultiQueryHandler),
            (r'/connection', ConnectionQueryHandler),
        ], debug=True)

        ioloop = tornado.ioloop.IOLoop.instance()

        application.db = asyncpg.Pool(
            dsn=dsn,
            size=1,
            max_size=3,
            ioloop=ioloop,
            setsession=("SET TIME ZONE UTC",),
            raise_connect_errors=False,
        )

        # this is a one way to run ioloop in sync
        future = application.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()

        if enable_hstore:
            future = application.db.register_hstore()
            # This is the other way to run ioloop in sync
            ioloop.run_sync(lambda: future)

        if application.db.server_version >= 90200:
            future = application.db.register_json()
            # This is the other way to run ioloop in sync
            ioloop.run_sync(lambda: future)

        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888, 'localhost')
        ioloop.start()
    except KeyboardInterrupt:
        print('Exit')
Example #2
0
def main():
    tornado.options.parse_command_line()
    
    settings = {
        "template_path"     : config.TEMPLATE_PATH,
        "static_path"       : config.STATIC_PATH,
        "debug"             : config.DEBUG,
        "compress_response" : config.COMPRESS_RESPONSE,
        "cookie_secret"     : config.COOKIE_SECRET,
        "xsrf_cookies"      : config.XSRF_COOKIES,
        "login_url"         : config.LOGIN_URL
        }

    ioloop = tornado.ioloop.IOLoop.instance()
    
    app = tornado.web.Application(
            urls.handler_urls,
            **settings)

    app.db = momoko.Pool(
                dsn='dbname={} user={} password={} host={} port={}'.format(
                    config.DATABASE_NAME,
                    config.DATABASE_USER,
                    config.DATABASE_PASSWORD,
                    config.DATABASE_HOST,
                    config.DATABASE_PORT),
                cursor_factory=psycopg2.extras.RealDictCursor,
                size=1,
                ioloop=ioloop)
    future = app.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    ioloop.start()
Example #3
0
def main():
    try:
        tornado.options.parse_command_line()
        handlers = [
            (r'/', MainHandler)
        ]
        settings = dict(
                debug=True,
                template_path=os.path.join(os.path.dirname(__file__), "templates"),
                static_path=os.path.join(os.path.dirname(__file__), "static")
        )
        app = tornado.web.Application(handlers, **settings)

        ioloop = tornado.ioloop.IOLoop.instance()

        app.db = momoko.Pool(
                dsn=dsn,
                size=1,
                max_size=3,
                ioloop=ioloop,
                setsession=("SET TIME ZONE UTC",),
                raise_connect_errors=False
        )

        future = app.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()

        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        ioloop.start()
    except KeyboardInterrupt:
        print('Exit.')
Example #4
0
def main():
    app = LetSpotify()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    ioloop = tornado.ioloop.IOLoop.instance()

    app.db = momoko.Pool(
        dsn=settings['dsn'],
        size=5,
        raise_connect_errors=False,
        reconnect_interval=50,
        ioloop=ioloop,
    )

    future = app.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()
    future.result()  # raises exception on connection error

    Service.users = Users(app.db)
    Service.facebook = FacebookAPI(app.db)
    Service.rooms = Rooms(app.db)
    Service.login_token = LoginToken(app.db)

    ioloop.start()
Example #5
0
def main():
    options.parse_command_line()

    application = tornado.web.Application([
        (r'/psql/select', PSQLSelectHandler),
    ],
                                          debug=False)

    ioloop = tornado.ioloop.IOLoop.instance()

    application.db = momoko.Pool(
        dsn=options.dsn,
        size=1,
        max_size=3,
        ioloop=ioloop,
    )

    # this is a one way to run ioloop in sync
    future = application.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port, 'localhost')
    ioloop.start()
Example #6
0
    def __init__(self):
        handlers = [
            (r"/", AllLists),
            (r"/create/", CreateLists),
        ]
        settings = dict(
            todo_title=u"ToDo",
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            cookie_secret=base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes),
            login_url="/auth/login",
            debug=True,
        )

        super(Application, self).__init__(handlers, **settings)

        ioloop = tornado.ioloop.IOLoop.instance()
        self.db = momoko.Pool(
            dsn='dbname=todo user={0} password={1} '
                'host=localhost port=5432'.format(USERNAME, PASSWORD),
            size=1,
            ioloop=ioloop,
            cursor_factory=psycopg2.extras.RealDictCursor
        )

        future = self.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()
        future.result()
Example #7
0
 def __init__(self):
     self.handlers = routs
     ioloop = tornado.ioloop.IOLoop.instance()
     self.settings = dict(
         debug=config.debug,
         template_path=config.template_path,
         static_path=config.static_path,
         cookie_secret=config.cookie_secret,
         login_url=config.login_url
     )
     super(Application, self).__init__(self.handlers, **self.settings)
     self.db_async = momoko.Pool(
         dsn=config.get_db_url(options.db_name,
                               options.db_user_name,
                               options.db_host,
                               options.db_port,
                               options.db_password),
         size=1,
         ioloop=ioloop,
         cursor_factory=DictCursor
     )
     future = self.db_async.connect()
     ioloop.add_future(future, lambda x: ioloop.stop())
     ioloop.start()
     future.result()
Example #8
0
def run():
    configure_logging()

    handlers = [
        tornado.web.url(r'/', IndexHandler, name='index'),
        tornado.web.url(r'/api/v1/stream/(.*)', StreamHandler, name='api/stream'),
        tornado.web.url(r'/api/v1/update/(.*)', UpdateHandler, name='api/update'),
    ]

    base_dir = os.path.dirname(__file__)
    static_path = os.path.join(base_dir, 'static')
    template_path = os.path.join(base_dir, 'templates')

    app = tornado.web.Application(handlers,
                                  static_path=static_path,
                                  template_path=template_path,
                                  debug=True)

    app.listeners = Listeners()

    dsn = 'host=localhost port=6875 dbname=materialize'
    app.mzql = momoko.Pool(dsn=dsn)

    # Connect Momoko before starting Tornado's event loop
    # This let's Momoko create an initial connection to the database
    future = app.mzql.connect()
    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()

    port = 8875
    log.info('Port %d ready to rumble!', port)
    app.listen(port)
    ioloop.start()
Example #9
0
def main():
    try:
        tornado.options.parse_command_line()
        handlers = [(r'/', MainHandler)]
        settings = dict(debug=True,
                        template_path=os.path.join(os.path.dirname(__file__),
                                                   "templates"),
                        static_path=os.path.join(os.path.dirname(__file__),
                                                 "static"))
        app = tornado.web.Application(handlers, **settings)

        ioloop = tornado.ioloop.IOLoop.instance()

        app.db = momoko.Pool(dsn=dsn,
                             size=1,
                             max_size=3,
                             ioloop=ioloop,
                             setsession=("SET TIME ZONE UTC", ),
                             raise_connect_errors=False)

        future = app.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()

        http_server = tornado.httpserver.HTTPServer(app)
        http_server.listen(options.port)
        ioloop.start()
    except KeyboardInterrupt:
        print('Exit.')
        def _async_init_cb():
            def _run_server_cb(future):
                if future.exception() is not None:
                    log.exception('failed to start: %s', future.exception())
                    sys.exit(1)

                run_server(tornado_app)

            ioloop.add_future(tornado_app.init_async(), _run_server_cb)
Example #11
0
        def _async_init_cb():
            def _run_server_cb(future):
                if future.exception() is not None:
                    log.exception('failed to start: %s', future.exception())
                    sys.exit(1)

                run_server(tornado_app)

            ioloop.add_future(
                tornado_app.init_async(), _run_server_cb
            )
Example #12
0
def main():
    debug = int(os.environ.get("AS_DEV", "0"))
    logging.basicConfig(
        format=f"%(asctime)s captain:  %(levelname)s: %(message)s",
        level=logging.DEBUG if debug else logging.INFO,
    )

    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_callback(signal.signal, signal.SIGTERM, handle_sigterm)
    ioloop.add_future(asyncio.ensure_future(async_main()), lambda _: None)

    logging.debug("Entering the IOLoop...")
    ioloop.start()
Example #13
0
def init_db(app, ioloop):
    """Init the app db connection to the postgres database"""
    app.db = momoko.Pool(
        dsn=('dbname=postgres user={user} password={password} '
             'host={host} port={port}').format(**DBARGS),
        size=1,
        ioloop=ioloop,
        cursor_factory=psycopg2.extras.DictCursor
    )

    # this is a one way to run ioloop in sync
    future = app.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()
    future.result()  # raises exception on connection error
Example #14
0
def main():
    init_log()
    try:
        tornado.options.parse_command_line()
        application = tornado.web.Application(
            [(r'/', OverviewHander), (r'/get-tick-data', TickDataHandler),
             (r'/get-new-stock', NewStockHandler),
             (r'/get-new-high', NewHighHandler), (r'/query', QueryHandler),
             (r'/connection', ConnectionHandler)],
            debug=True)

        ioloop = tornado.ioloop.IOLoop.instance()
        application.db = momoko.Pool(
            dsn=dsn,
            size=1,
            max_size=3,
            ioloop=ioloop,
            setsession=("SET TIME ZONE UTC", ),
            raise_connect_errors=False,
        )

        # this is a one way to run ioloop in sync
        future = application.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()

        if enable_hstore:
            future = application.db.register_hstore()
            # This is the other way to run ioloop in sync
            ioloop.run_sync(lambda: future)

        if application.db.server_version >= 90200:
            future = application.db.register_json()
            # This is the other way to run ioloop in sync
            ioloop.run_sync(lambda: future)
        # create http server
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(6888, 'localhost')
        # create json rpc server
        rpc_server = RPCServer()
        rpc_server.listen(8001)

        ioloop.start()

    except KeyboardInterrupt:
        print('Exit')
Example #15
0
def main():
    try:
        tornado.options.parse_command_line()
        application = tornado.web.Application([
            (r'/', OverviewHandler),
            (r'/mogrify', MogrifyHandler),
            (r'/query', SingleQueryHandler),
            (r'/hstore', HstoreQueryHandler),
            (r'/json', JsonQueryHandler),
            (r'/transaction', TransactionHandler),
            (r'/multi_query', MultiQueryHandler),
            (r'/connection', ConnectionQueryHandler),
        ],
                                              debug=True)

        ioloop = tornado.ioloop.IOLoop.instance()

        application.db = momoko.Pool(
            dsn=dsn,
            size=1,
            max_size=3,
            ioloop=ioloop,
            setsession=("SET TIME ZONE UTC", ),
            raise_connect_errors=False,
        )

        # this is a one way to run ioloop in sync
        future = application.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()

        if enable_hstore:
            future = application.db.register_hstore()
            # This is the other way to run ioloop in sync
            ioloop.run_sync(lambda: future)

        if application.db.server_version >= 90200:
            future = application.db.register_json()
            # This is the other way to run ioloop in sync
            ioloop.run_sync(lambda: future)

        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(8888, 'localhost')
        ioloop.start()
    except KeyboardInterrupt:
        print('Exit')
Example #16
0
        def _async_init_cb():
            try:
                init_futures = app.default_init_futures + list(app.init_async())

                if init_futures:
                    def await_init(future):
                        if future.exception() is not None:
                            log.error('failed to initialize application, init_async returned: %s', future.exception())
                            sys.exit(1)

                        run_server(app)

                    ioloop.add_future(gen.multi(init_futures), await_init)
                else:
                    run_server(app)

            except Exception:
                log.exception('failed to initialize application')
                sys.exit(1)
Example #17
0
def main():
    kr_addr = os.environ.get("AS_WEB_ADDR", "0.0.0.0")
    kr_port = int(os.environ.get("AS_WEB_PORT", 5000))

    debug = int(os.environ.get("AS_DEV", "0"))
    cfg.start_logging("web", debug)
    master_root, master_lang = cfg.get_master_version()
    logging.info(f"Master: {master_root}")

    ioloop = tornado.ioloop.IOLoop.current()
    ioloop.add_future(
        asyncio.ensure_future(
            async_main(captain.application(master_root, master_lang, debug),
                       kr_addr, kr_port)),
        lambda _: None,
    )

    logging.debug("Entering the IOLoop...")
    ioloop.start()
Example #18
0
def main():
    tornado.options.parse_command_line()
    ioloop = tornado.ioloop.IOLoop.instance()

    application.db = momoko.Pool(
        dsn='dbname=health user=postgres password=dangerous123 '
            'host=localhost port=5432',
        size=1,
        ioloop=ioloop,
    )

    future = application.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()
    future.result()

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port)

    tornado.ioloop.IOLoop.instance().start()
Example #19
0
 def __init__(self):
     self.handlers = routs
     ioloop = tornado.ioloop.IOLoop.instance()
     self.settings = dict(
         debug=config.DEBUG,
         template_path=config.TEMPLATE_PATH,
         static_path=config.STATIC_PATH,
         cookie_secret='ss1sx!sdazxcccv2bfsdf232ggjhjjhjkjhk@!~s=d453',
         login_url='/admin/login'
     )
     super(Application, self).__init__(self.handlers, **self.settings)
     self.db_async = momoko.Pool(
         dsn=config.get_db_url(),
         size=1,
         ioloop=ioloop,
         cursor_factory=DictCursor
     )
     future = self.db_async.connect()
     ioloop.add_future(future, lambda x: ioloop.stop())
     ioloop.start()
     future.result()
Example #20
0
    def __getattr__(self, item):
        if item in self.dbs and self._motorclient is None:
            if mode == 'test':
                self._motorclient = motor.MotorClient(host=self.localhost,
                                                      port=self.port)
                self._motorclient_realtime = self._motorclient
            else:
                self._motorclient = motor.MotorReplicaSetClient(
                    ','.join(mongo_machines),
                    replicaSet=REPLICASET_NAME,
                    readPreference=ReadPreference.NEAREST)

                self._motorclient_realtime = motor.MotorReplicaSetClient(
                    ','.join(mongo_machines),
                    replicaSet=REPLICASET_NAME,
                    readPreference=ReadPreference.PRIMARY)

                ioloop=tornado.ioloop.IOLoop.instance()
                @tornado.gen.coroutine
                def auth_db():
                    yield self._motorclient.open()
                    yield self._motorclient_realtime.open()
                    #print "+++++++++authing++++++++++"
                    yield self._motorclient.fbt_log.authenticate(FBT_USER, FBT_PASSWD)
                    yield self._motorclient_realtime.fbt.authenticate(FBT_USER, FBT_PASSWD)
                    yield self._motorclient.fbt.authenticate(FBT_USER, FBT_PASSWD)
                    yield self._motorclient.fbt_reward.authenticate(FBT_USER, FBT_PASSWD)
                    #print "+++++++++authing OK++++++++++"+str(ok)
                    #ioloop.run_sync(f)
                    #ioloop.add_timeout(time() + 1, lambda: ioloop.run_sync(f))
                ioloop.add_future(auth_db(), lambda future: True)

            self.dbs['fbt'] = self._motorclient.fbt
            self.dbs['reward'] = self._motorclient.fbt_reward
            self.dbs['fbt_realtime'] = self._motorclient_realtime.fbt
            #self.dbs['fbt_test'] = self._motorclient_realtime.fbt_test
            self.dbs['fbt_log'] = self._motorclient.fbt_log
            self.module.__dict__.update(self.dbs)

        return getattr(self.module, item)
Example #21
0
        def _async_init_cb():
            try:
                init_futures = app.default_init_futures + list(
                    app.init_async())

                if init_futures:

                    def await_init(future):
                        if future.exception() is not None:
                            log.error(
                                'failed to initialize application, init_async returned: %s',
                                future.exception())
                            sys.exit(1)

                        run_server(app)

                    ioloop.add_future(gen.multi(init_futures), await_init)
                else:
                    run_server(app)

            except Exception:
                log.exception('failed to initialize application')
                sys.exit(1)
Example #22
0
def start():

    app = tornado.web.Application(
        [
            (r'^/$', pages.Index),
            (r'^/comment/list/$', pages.CommentList),
            (r'^/comment/add/$', pages.CommentAdd),
            (r'^/comment/edit/$', pages.CommentEdit),
            (r'^/comment/delete/$', pages.CommentDelete),
            (r'^/comment/log/$', pages.CommentLog),
            (r'^/comment/download/$', pages.CommentDownload),
        ], **{
            'debug': config.DEBUG,
            'static_path': os.path.join(config.ROOT, 'static'),
            'template_path': os.path.join(config.ROOT, 'templates'),
        })

    ioloop = tornado.ioloop.IOLoop.instance()

    # Postgres

    app.pg = momoko.Pool(
        dsn=config.PG_DSN,
        size=1,
        max_size=config.PG_POOL_SIZE,
        cursor_factory=psycopg2.extras.NamedTupleCursor,
        ioloop=ioloop,
    )

    future = app.pg.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()

    # Server

    app.listen(config.PORT)
    ioloop.start()
Example #23
0
def main():
    options.parse_command_line()

    application = tornado.web.Application([
        (r'/psql/select', PSQLSelectHandler),
    ], debug=False)

    ioloop = tornado.ioloop.IOLoop.instance()

    application.db = momoko.Pool(
        dsn=options.dsn,
        size=1,
        max_size=3,
        ioloop=ioloop,
    )

    # this is a one way to run ioloop in sync
    future = application.db.connect()
    ioloop.add_future(future, lambda f: ioloop.stop())
    ioloop.start()

    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(options.port, 'localhost')
    ioloop.start()
Example #24
0
		static_path=os.path.join(os.path.dirname(__file__), "static"),
		debug=True
		)

application = tornado.web.Application([
	tornado.web.url(r"/", MainHandler),
	tornado.web.url(r"/CodeChef", CodeChef),
	tornado.web.url(r"/Codeforces", CodeForces),
	tornado.web.url(r"/hackerrank", HackerRank),
	tornado.web.url(r"/query/(.*)", Query), 
	tornado.web.url(r"/db", DBHandler), ## To see the saved data
	tornado.web.url(r"/db/(.*)", DBQuery) ## To add or delete any data
	], **settings)

if __name__=="__main__":
	ioloop = tornado.ioloop.IOLoop.instance()
	application.db = momoko.Pool(
		dsn='dbname=testdb user=admin password='' host='' port=5432' ,
		size=1,
		ioloop=ioloop
		)
	future = application.db.connect()
	ioloop.add_future(future, lambda f: ioloop.stop())
	ioloop.start()
	future.result()

	server = tornado.httpserver.HTTPServer(application)
	server.listen(8888)
	print "Listening on http://127.0.0.1:8888"
	ioloop.start()
Example #25
0
def report_error(**kwargs):
    """
    Report an error to Rollbar

    assumes ROLLBAR_TOKEN is in the environment
    also looks for ENVIRONMENT, which defaults to development.

    :exc_info: if given, will be used instead of sys.exc_info()
    :request: a HTTPServerRequest or HTTPRequest
    """

    token = os.environ.get('ROLLBAR_TOKEN')
    env = os.environ.get('ENVIRONMENT', 'development')

    if token is None:
        logger.error("no rollbar token, skipping error reporting")
        return

    exc_info = kwargs.pop('exc_info', None)
    if exc_info is None:
        exc_info = sys.exc_info()

    cls, exc, trace = exc_info

    raw_frames = traceback.extract_tb(trace)
    frames = [{'filename': f[0], 'lineno': f[1], 'method': f[2], 'code': f[3]} for f in raw_frames]

    payload = {
        'access_token': token,
        'data': {
            'environment': env,
            'body': {
                'trace': {
                    'frames': frames,
                    'exception': {
                        'class': cls.__name__,
                        'message': str(exc)
                    },
                },
            },

        }
    }

    if hasattr(exc, 'response'):
        response = exc.response
        payload['data']['custom'] = {
            'request': _parse_request(response.request),
            'response': {
                'code': response.code,
                'headers': response.headers,
                'body': str(response.body, 'utf8'),
                'url': response.effective_url,
            }
        }

    if 'request' in kwargs:
        payload['data']['request'] = _parse_request(kwargs['request'])

    logger.error("Reporting error")
    client = AsyncHTTPClient()
    f = client.fetch(ROLLBAR_URL,
                     method='POST',
                     headers={'Content-type': 'application/json'},
                     body=json.dumps(payload))


    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.add_future(f, _handle)
Example #26
0
    def __init__(self):
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            xsrf_cookies=True,
            cookie_secret="cookie_secret_code",
            login_url="/login",
            autoescape=None,
            jinja2=Environment(loader=FileSystemLoader(
                os.path.join(os.path.dirname(__file__), "templates")),
                               trim_blocks=True),
            reserved=[
                "user", "home", "setting", "forgot", "login", "logout",
                "register", "admin"
            ],
        )

        handlers = [
            (r"/", index.IndexHandler),
            (r"/login", user.LoginHandler),
            (r"/logout", user.LogoutHandler),
            (r"/nodes_list", node.NodeListHandler),
            (r"/nodes_nearby", node.GetNodesNearbyHandler),
            (r"/get_nodes", node.GetNodesHandler),
            (r"/node/(.*)", node.NodeDetailHandler),
            (r"/get_pkts", node_pkt.GetPktsHandler),
            (r"/get_latest_pkt", node_pkt.GetLatestPktInfoHandler),
            (r"/get_history", node_pkt.GetHistoryHandler),
            (r"/lora/push", node_pkt_push.NodePktPushHandler),
            (r"/(favicon\.ico)", tornado.web.StaticFileHandler,
             dict(path=settings["static_path"])),
            (r"/(sitemap.*$)", tornado.web.StaticFileHandler,
             dict(path=settings["static_path"])),
            (r"/(bdsitemap\.txt)", tornado.web.StaticFileHandler,
             dict(path=settings["static_path"])),
        ]

        tornado.web.Application.__init__(self, handlers, **settings)

        ioloop = tornado.ioloop.IOLoop.instance()

        self.db = momoko.Pool(
            dsn=
            'dbname=lora user=postgres password=cisco123 host=9.9.9.14 port=5432',
            size=1,
            ioloop=ioloop)

        future = self.db.connect()
        ioloop.add_future(future, lambda f: ioloop.stop())
        ioloop.start()
        future.result()

        self.cluster = Cluster(['9.9.9.5'])
        self.session = self.cluster.connect('lora')
        self.cass_conn = TornadoCassandra(self.session, ioloop=ioloop)

        # Have one global model for db query
        self.user_model = UserModel(self.db)
        self.node_model = NodeModel(self.db)
        self.node_pkt_model = NodePktModel(self.cass_conn)

        # Have one global session controller
        self.session_manager = SessionManager(settings["cookie_secret"],
                                              ["127.0.0.1:11211"], 0)

        # Have one global memcache controller
        self.mc = memcache.Client(["127.0.0.1:11211"])
Example #27
0
 def _async_init_cb():
     try:
         ioloop.add_future(tornado_app.init_async(), _run_server_cb)
     except Exception:
         log.exception('failed to initialize application')
         sys.exit(1)
Example #28
0
def test_future():
    future = Future()
    threading.Thread(target=long_task, args=(future,)).start()
    ioloop.add_future(future, after_task_done)
Example #29
0
def delay_task(func, callback=None, *args, **kw):
    asynfutu = executor.submit(func, *args, **kw)
    if callback:
        tonafutu = to_tornado_future(asynfutu)
        ioloop = tornado.ioloop.IOLoop.current()
        ioloop.add_future(tonafutu, callback)