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')
def callback(f): ioloop.stop() try: f.result() except Exception: logging.error( "Error in stream: {0}".format(traceback.format_exc()))
def teardown(*_): """Teardown raspberry gpio and tornado ioloop""" app_log.info('radio shutting down') ioloop = tornado.ioloop.IOLoop.current() ioloop.stop() GPIO.teardown() sys.exit(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()
def do_stuff(): #result = yield gen.Task( users.put, 'blah 2', dict( kyle = 102 ) ) result = yield gen.Task( db.query, "select * from users where version=\"24979\" limit 2") logging.info('got result %s: %s, %s, %s' % (result.code, result.attributes, result.meta, result.results)) if 'NextToken' in result.meta: result = yield gen.Task( db.query, "select * from users where version=\"24979\" limit 2", result.meta['NextToken']) logging.info( 'got result %s: %s, %s, %s' % (result.code, result.attributes, result.meta, result.results)) #result = yield gen.Task( db.query, "select" ) return result = yield gen.Task(users.delete, 'blah2', {'kyle': [1, 59, 84, 85, 88, 89, 90]}) #yield gen.Task( asyncsleep, 5 ) #result = yield gen.Task( users.get, 'blah2' ) logging.info('got result %s: %s, %s' % (result.code, result.attributes, result.meta)) result = yield gen.Task(users.get_metadata) logging.info('got result %s: %s, %s' % (result.code, result.attributes, result.meta)) ioloop.stop()
def shutdown(*args): """Signal handler callback that shuts down the ioloop""" app_log.info('server shutting down') app.shutdown() ioloop.stop() app_log.info('exit') sys.exit(0)
def stop(self): # FIXME: THIS ISN"T WORKING! should catch sigkill/sigterm and shutdown properly super(HTTPServer, self).stop() logger.debug("Tornado: Stop") ioloop = tornado.ioloop.IOLoop.instance() ioloop.stop() if hasattr(self, '_web_app'): del self._web_app
def bye_handler(signal, frame): import tornado.ioloop logging.info('interrupt signal received, shutting down...') # shut down the IO loop if it has been started ioloop = tornado.ioloop.IOLoop.instance() ioloop.stop()
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")
def on_shutdown(): #监听ctrl+c 以保证在退出时保存fetched logging.info("save fetched") with open("ed_fetched", "w") as f: for u in fetcher.fetch_finished: f.write(u + '\n') ioloop.stop()
def run_loop(ioloop): while True: try: ioloop.start() except KeyboardInterrupt: ioloop.stop() drop_to_shell() print('Resuming I/O loop')
def main(): try: app.listen(8000) listen('agent_state_changes') print('server is running in port 8000') ioloop.start() except KeyboardInterrupt as e: print('stopping server') ioloop.stop()
def _listen(self, sid): pid = os.getpid() pid_file = open( "%s/backend_%s.pid" % ( config.get_directory("pid_dir"), config.station_id_friendly[sid].lower(), ), "w", ) pid_file.write(str(pid)) pid_file.close() db.connect() cache.connect() zeromq.init_pub() log.init( "%s/rw_%s.log" % ( config.get_directory("log_dir"), config.station_id_friendly[sid].lower(), ), config.get("log_level"), ) memory_trace.setup(config.station_id_friendly[sid].lower()) if config.test_mode: playlist.remove_all_locks(sid) # (r"/refresh/([0-9]+)", RefreshScheduleRequest) app = tornado.web.Application( [ (r"/advance/([0-9]+)", AdvanceScheduleRequest), ], debug=(config.test_mode or config.get("developer_mode")), ) port = int(config.get("backend_port")) + sid server = tornado.httpserver.HTTPServer(app) server.listen(port, address="127.0.0.1") for station_id in config.station_ids: playlist.prepare_cooldown_algorithm(station_id) schedule.load() log.debug( "start", "Backend server started, station %s port %s, ready to go." % (config.station_id_friendly[sid], port), ) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() finally: ioloop.stop() server.stop() db.close() log.info("stop", "Backend has been shutdown.") log.close()
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!')
def test_login(): username = sys.argv[1] password = sys.argv[2] session = Session() session.endpoint = '/gui/srp' session.srp_direct = options.server_address session.enable_direct() result = yield gen.Task(session.login, username, password) logging.info('got session %s' % result) result = yield gen.Task(session.get_token) logging.info('got token %s %s' % (result, session.token)) # check result.. old_style = True btappstr = 'testbtapp' #torrent = 'http://www.clearbits.net/get/503-control-alt-deus---made-of-fire.torrent' hash = ''.join([ random.choice(list('abcdef') + map(str, range(10))) for _ in range(40) ]) torrent = 'magnet:?xt=urn:btih:%s' % hash cid = None count = 0 while count < 10: count += 1 #url_args = {'list':1} url_args = None #args = {} args = {'list': 1} if cid: args['cid'] = cid response = yield gen.Task(session.request, 'GET', url_params=url_args, body_params=args) #logging.info('got response %s' % response) if 'torrentc' in response.body: cid = response.body['torrentc'] logging.info('list req response %s' % [response.body]) yield gen.Task(asyncsleep, 1) assert response.code == 200 logging.info('woot!') ioloop.stop()
def main(): # pragma nocover """ parse command line, make and start """ parse_command_line() app = make_app() app.listen(options.port) log.info('listening on port: %s', options.port) if options.debug: log.warning('running in debug mode') ioloop = tornado.ioloop.IOLoop.current() try: ioloop.start() except (KeyboardInterrupt, SystemExit): # graceful shutdown ioloop.stop()
def main(): _auth_handlers = { "simple": SimpleLoginHandler, "openid": OpenIdLoginHandler, "github": GithubLoginHandler } parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) # yapf: disable parser.add_argument('-p', '--port', type=int, default=4000, help='listen port') parser.add_argument('-d', '--debug', action='store_true', help='open debug log, and open hot reload') parser.add_argument('--auth', type=str, default='simple', choices=_auth_handlers.keys(), help='authentication method') parser.add_argument("--no-xheaders", action="store_true", help="disable support for X-Real-Ip/X-Forwarded-For") parser.add_argument( '--auth-conf-file', type=argparse.FileType('r'), help='authentication config file') # yapf: enable args = parser.parse_args() print(args) enable_pretty_logging() db.setup() ioloop = tornado.ioloop.IOLoop.current() # TODO(ssx): for debug use # async def dbtest(): # items = await db.table("devices").get_all( # limit=2, rsql_hook=lambda q: q.order_by(r.desc("createdAt"))) # for item in items: # pprint(item) # ioloop.spawn_callback(dbtest) login_handler = _auth_handlers[args.auth] app = make_app(login_handler, debug=args.debug) server = HTTPServer(app, xheaders=not args.no_xheaders) server.listen(args.port) logger.info("listen on port http://%s:%d", machine_ip(), args.port) try: ioloop.start() except KeyboardInterrupt: ioloop.stop()
def main(): try: config = ConfigParser.SafeConfigParser({"accountId":None,"deviceId":None,"dmtp_url":'dmtp://54.84.59.135:21000'}) config.read("/home/pi/attack_on_titan/src/settings.cfg") print config.get("dmtp","dmtp_url") print config.get("dmtp","accountId") print config.get("dmtp","deviceId") logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) ioloop = tornado.ioloop.IOLoop() client = SimpleAsyncDmtpClient(ioloop) def on_response(response): print(response) if response.error: print("errror sending packet") else: print("tag in range sent") @gen.coroutine def on_message(body,consumer,basic_deliver): try: print("received packet") dmtp_packet = pickle.loads(body) dmtp_request = DMTPRequest(\ config.get("dmtp","dmtp_url"),\ config.get("dmtp","accountId"),\ config.get("dmtp","deviceId"),\ packets=[dmtp_packet]) #yield DMTPResponse Object response = yield client.fetch(dmtp_request) print('sent data and got here') if not(response.code == 200): consumer.reject_message(basic_deliver.delivery_tag) raise Exception("Error sending data") consumer.acknowledge_message(basic_deliver.delivery_tag) return except: import sys print sys.exc_info() consumer = Consumer('amqp://*****:*****@localhost:5672/%2F',ioloop,None,on_ack_message=on_message,durable=True) consumer.QUEUE = 'dmtp' consumer.EXCHANGE = 'upstream' consumer.run() ioloop.start() except KeyboardInterrupt: consumer.stop() ioloop.stop()
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 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()
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()
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()
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()
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 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()
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()
def main(debug, static_dir, template_dir, listen): application = make_app(debug, static_dir, template_dir) application.listen(address=listen.address, port=listen.port) url = "http://{0}:{1}".format(listen.address, listen.port) print('Starting server at {0}'.format(url)) # open a URL, if possible on new tab webbrowser.open(url, new=2) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() except KeyboardInterrupt: ioloop.stop() ioloop.close()
def test_login(): username = sys.argv[1] password = sys.argv[2] session = Session() session.endpoint = '/gui/srp' session.srp_direct = options.server_address session.enable_direct() result = yield gen.Task( session.login, username, password ) logging.info('got session %s' % result) result = yield gen.Task( session.get_token ) logging.info('got token %s %s' % (result, session.token)) # check result.. old_style = True btappstr = 'testbtapp' #torrent = 'http://www.clearbits.net/get/503-control-alt-deus---made-of-fire.torrent' hash = ''.join([random.choice( list('abcdef') + map(str,range(10)) ) for _ in range(40)]) torrent = 'magnet:?xt=urn:btih:%s' % hash cid = None count = 0 while count < 10: count += 1 #url_args = {'list':1} url_args = None #args = {} args = { 'list': 1 } if cid: args['cid'] = cid response = yield gen.Task( session.request, 'GET', url_params=url_args, body_params=args ) #logging.info('got response %s' % response) if 'torrentc' in response.body: cid = response.body['torrentc'] logging.info('list req response %s' % [response.body]) yield gen.Task(asyncsleep,1) assert response.code == 200 logging.info('woot!') ioloop.stop()
def main(): try: if len(sys.argv) > 1: if sys.argv[1] == "config": ioloop.run_sync(config) elif sys.argv[1].endswith("help") or sys.argv[1] == "-h": print(helptext) else: print("I don't understand that. Here's the help text:") print(helptext) else: run() except KeyboardInterrupt: ioloop.stop() print("Stopping...") except Closed: ioloop.stop() print("Connection was closed")
def start(args, cfg): application = Application(cfg, args.debug) if args.debug: args.level = logging.DEBUG # setup logging level if specify if args.level is not None: logging.root.setLevel(args.level) # listen to port port = cfg['server']['port'] try: application.listen(port) app_log.info('listening port %s', port) except OSError: app_log.error('unable to listen port %s', port) return ioloop = tornado.ioloop.IOLoop.instance() # prevent block for IO allowed ctrl-c to pass # http://stackoverflow.com/a/9578595 def set_ping(timeout): ioloop.add_timeout(timeout, lambda: set_ping(timeout)) set_ping(timedelta(seconds=0.5)) # start main loop try: ioloop.start() except KeyboardInterrupt: app_log.info('Keyboard interrupt') except SystemExit: pass except Exception: app_log.exception('Error') raise ioloop.stop() app_log.info('Closed') return True
def do_stuff(): # result = yield gen.Task( users.put, 'blah 2', dict( kyle = 102 ) ) result = yield gen.Task(db.query, 'select * from users where version="24979" limit 2') logging.info("got result %s: %s, %s, %s" % (result.code, result.attributes, result.meta, result.results)) if "NextToken" in result.meta: result = yield gen.Task(db.query, 'select * from users where version="24979" limit 2', result.meta["NextToken"]) logging.info("got result %s: %s, %s, %s" % (result.code, result.attributes, result.meta, result.results)) # result = yield gen.Task( db.query, "select" ) return result = yield gen.Task(users.delete, "blah2", {"kyle": [1, 59, 84, 85, 88, 89, 90]}) # yield gen.Task( asyncsleep, 5 ) # result = yield gen.Task( users.get, 'blah2' ) logging.info("got result %s: %s, %s" % (result.code, result.attributes, result.meta)) result = yield gen.Task(users.get_metadata) logging.info("got result %s: %s, %s" % (result.code, result.attributes, result.meta)) ioloop.stop()
def main(): parse_command_line() logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) # Get a handle to the instance of IOLoop ioloop = tornado.ioloop.IOLoop.instance() application = TornadoWebServer() # Create the connection with rabbitmq pc = PikaClient() application.pika = pc # Start the HTTP Server http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8080) # Start the IOLoop try: ioloop.start() except KeyboardInterrupt: ioloop.stop()
def _listen(self, sid): pid = os.getpid() pid_file = open("%s/backend_%s.pid" % (config.get_directory("pid_dir"), config.station_id_friendly[sid].lower()), 'w') pid_file.write(str(pid)) pid_file.close() db.connect() cache.connect() zeromq.init_pub() log.init("%s/rw_%s.log" % (config.get_directory("log_dir"), config.station_id_friendly[sid].lower()), config.get("log_level")) memory_trace.setup(config.station_id_friendly[sid].lower()) if config.test_mode: playlist.remove_all_locks(sid) # (r"/refresh/([0-9]+)", RefreshScheduleRequest) app = tornado.web.Application([ (r"/advance/([0-9]+)", AdvanceScheduleRequest), ], debug=(config.test_mode or config.get("developer_mode"))) port = int(config.get("backend_port")) + sid server = tornado.httpserver.HTTPServer(app) server.listen(port, address='127.0.0.1') for station_id in config.station_ids: playlist.prepare_cooldown_algorithm(station_id) schedule.load() log.debug("start", "Backend server started, station %s port %s, ready to go." % (config.station_id_friendly[sid], port)) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() finally: ioloop.stop() server.stop() db.close() log.info("stop", "Backend has been shutdown.") log.close()
def start() : application = Application(drop=options.drop) http_server = tornado.httpserver.HTTPServer(application) try : http_server.listen(app_config.port) except : traceback.print_exc() os._exit(1) # since it otherwise hangs Settings.logging.info("Started news_crowdsourcer in %s mode." % app_config.environment) ioloop = tornado.ioloop.IOLoop.instance() try : ioloop.start() except : ioloop.add_callback(lambda : ioloop.stop())
def run_proxy(port: int, certs: Dict[str, Any] = DEFAULT_CERTS) -> None: """ Run proxy on the specified port using the provided certs. Example usage: python -m dummyserver.https_proxy You'll need to ensure you have access to certain packages such as trustme, tornado, urllib3. """ upstream_ca_certs = certs.get("ca_certs") app = tornado.web.Application([(r".*", ProxyHandler)], upstream_ca_certs=upstream_ca_certs) ssl_opts = ssl_options_to_context(**certs) http_server = tornado.httpserver.HTTPServer(app, ssl_options=ssl_opts) http_server.listen(port) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() except KeyboardInterrupt: ioloop.stop()
def worker(): # setup logging, on start it have to do here since all fd will close by daemonocle setup_logging(cfg) application = Application(cfg, args.debug) if args.debug: args.level = logging.DEBUG # setup logging level if specify if args.level is not None: logging.root.setLevel(args.level) # listen to port port = cfg['server']['port'] try: application.listen(port) app_log.info('listening port %s', port) except OSError: app_log.error('unable to listen port %s', port) return # start main loop ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() except KeyboardInterrupt: app_log.info('Keyboard interrupt') except SystemExit: pass except Exception: app_log.exception('Error') raise ioloop.stop() app_log.info('Closed')
def main(): trader_list = [ {'name': 'Tom', 'krw': 10000000, 'algo': 'random', 'currency': 'xrp'}, {'name': 'Ian', 'krw': 10000000, 'algo': 'type1', 'currency': 'xrp'}, {'name': 'JDY', 'krw': 10000000, 'algo': 'type2', 'currency': 'xrp'}, {'name': 'YKK', 'krw': 10000000, 'algo': 'type3', 'currency': 'xrp'}] traders = [Trader(x) for x in trader_list] for trader in traders: trader.think() price = price_gen(1000, 24*360*1000) queue = deque() # Collect for one day for _ in range(360*24): queue.append(int(next(price))) for i in price: queue.append(int(next(price))) queue.popleft() analytics = { 'price': queue[-1], 'change': { 'day': queue[-1] - queue[0], 'pc_day': percent(queue[0], queue[-1]), 'hour': queue[-1] - queue[-360], 'pc_hour' : percent(queue[-360], queue[-1]), '5min': queue[-1] - queue[-30], 'pc_5min': percent(queue[-30], queue[-1]) } } for trader in traders: trader.make_decesion(analytics) for trader in traders: trader.log('completed') ioloop.stop()
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
def start(): application = Application( environment=options.environment, db_name=options.db_name, drop=options.drop, make_payments=options.make_payments ) http_server = tornado.httpserver.HTTPServer(application) try: http_server.listen(options.port) except: traceback.print_exc() os._exit(1) # since it otherwise hangs Settings.logging.info("Started news_crowdsourcer in %s mode." % options.environment) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop.start() except: ioloop.add_callback(lambda: ioloop.stop())
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')
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')
def main(): tornado.options.parse_command_line() rewrites = json.load(open(options.rewrite_json)) for userid, params in rewrites.items(): params['url'] = urlparse.urlparse(params.get('url')) ## ┏━┓┏━╸╺┳╸╺┳╸╻┏┓╻┏━╸┏━┓ ## ┗━┓┣╸ ┃ ┃ ┃┃┗┫┃╺┓┗━┓ ## ┗━┛┗━╸ ╹ ╹ ╹╹ ╹┗━┛┗━┛ handlers = [ tornado.web.url(r'/Microsoft-Server-ActiveSync.*', MicrosoftServerActiveSyncHandler), tornado.web.url(r'/__stub__$', StubHandler), ] settings = dict(rewrites=rewrites, compress_response=False, xsrf_cookies=False, **options.as_dict()) tornado.log.gen_log.debug(pprint.pformat(settings)) ## ┏━┓┏━┓┏━┓╻ ╻┏━╸┏━┓╺┳╸╻┏━┓┏┓╻ ## ┣━┫┣━┛┣━┛┃ ┃┃ ┣━┫ ┃ ┃┃ ┃┃┗┫ ## ╹ ╹╹ ╹ ┗━╸╹┗━╸╹ ╹ ╹ ╹┗━┛╹ ╹ application = tornado.web.Application(handlers=handlers, **settings) http_server = tornado.httpserver.HTTPServer(application, xheaders=True) http_server.listen(options.listen_port, address=options.listen_host) ioloop = tornado.ioloop.IOLoop.instance() try: ioloop_status = ioloop.start() except KeyboardInterrupt: ioloop_status = ioloop.stop() return ioloop_status
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()
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()
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()
def shutdown(): ioloop.stop() print("Server is stopped") sys.stdout.flush() cls.started = False
def close_proxy(self): ioloop = tornado.ioloop.IOLoop.instance() logging.info('stop proxy server') ioloop.stop()
def signal_handler(signum, frame): logging.info("Received signal %i, shutting down.", signum) shutdown() if len(sockets) == 0: ioloop.stop()
def stop_ioloop(): ioloop.stop() ioloop.close()
def stop(self): ioloop.stop() def start(self): ioloop.start()
def __kill_server(): print 'stopping server...' server.stop() ioloop = tornado.ioloop.IOLoop.instance() ioloop.stop() ioloop._stopped = False
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) try: s.connect((address, 9999)) except socket.error, e: print "Error: %s" % e.strerror exit() engines[engine](s) app = App() app.listen(8888) ioloop = tornado.ioloop.IOLoop.instance() try: print "Listening on http://0.0.0.0:8888" ioloop.start() except KeyboardInterrupt: ioloop.stop() print "\nClean exit." def run(): if len(sys.argv) == 1: addr = "127.0.0.1" engine = 2 elif len(sys.argv) == 2: addr = sys.argv[1] engine = 2 elif len(sys.argv) >= 3: addr = sys.argv[1] try: engine = int(sys.argv[2])
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()
def gracefulExit(self, signal, frame): ioloop.stop()