def add_msg_count(self): CLIENTS[self.api_key]['usage']['messages'] += 1 MyRouter = tornadio2.TornadioRouter(WSConnection) if __name__ == '__main__': try: port = sys.argv[1] print 'starting server on port %s' % port io_loop = ioloop.IOLoop.instance() # add redis monitor loop redis_loop = ioloop.PeriodicCallback(redis_monitor, 1000, io_loop=io_loop) redis_loop.start() # add usage monitor loop usage_loop = ioloop.PeriodicCallback(usage_update, 30000, io_loop=io_loop) usage_loop.start() application = tornado.web.Application( MyRouter.urls, socket_io_port=port, ) socketio_server = tornadio2.server.SocketServer(application,
print("startWatching!!") ids = message['d'].split() for id in ids: print(id) game = games.get(id, None) if game: self.write_json(start_game_message(game)) app = web.Application([ (r'/', IndexHandler), (r'/socket', SocketHandler), (r'/(cg_base.css)', web.StaticFileHandler, { 'path': './' }), (r'/(cg_theme.css)', web.StaticFileHandler, { 'path': './' }), ]) if __name__ == '__main__': import sys if len(sys.argv) > 1: pollpgn = ioloop.PeriodicCallback(update_pgns, 1000) else: print("Polling files!") pollpgn = ioloop.PeriodicCallback(poll_files, 500) pollpgn.start() app.listen(8888) ioloop.IOLoop.instance().start()
#servidor_tornado_camera_3.py
def add_handlers(handlers, extension_app): """Add the appropriate handlers to the web app. """ # Normalize directories. for name in LabConfig.class_trait_names(): if not name.endswith('_dir'): continue value = getattr(extension_app, name) setattr(extension_app, name, value.replace(os.sep, '/')) # Normalize urls # Local urls should have a leading slash but no trailing slash for name in LabConfig.class_trait_names(): if not name.endswith('_url'): continue value = getattr(extension_app, name) if is_url(value): continue if not value.startswith('/'): value = '/' + value if value.endswith('/'): value = value[:-1] setattr(extension_app, name, value) url_pattern = MASTER_URL_PATTERN.format( extension_app.app_url.replace('/', '')) handlers.append((url_pattern, LabHandler)) # Cache all or none of the files depending on the `cache_files` setting. no_cache_paths = [] if extension_app.cache_files else ['/'] # Handle federated lab extensions. labextensions_path = extension_app.extra_labextensions_path + extension_app.labextensions_path labextensions_url = ujoin(extension_app.labextensions_url, "(.*)") handlers.append((labextensions_url, FileFindHandler, { 'path': labextensions_path, 'no_cache_paths': no_cache_paths })) # Handle local settings. if extension_app.schemas_dir: settings_config = { 'app_settings_dir': extension_app.app_settings_dir, 'schemas_dir': extension_app.schemas_dir, 'settings_dir': extension_app.user_settings_dir, 'labextensions_path': labextensions_path } # Handle requests for the list of settings. Make slash optional. settings_path = ujoin(extension_app.settings_url, '?') handlers.append((settings_path, SettingsHandler, settings_config)) # Handle requests for an individual set of settings. setting_path = ujoin(extension_app.settings_url, '(?P<schema_name>.+)') handlers.append((setting_path, SettingsHandler, settings_config)) # Handle saved workspaces. if extension_app.workspaces_dir: workspaces_config = {'path': extension_app.workspaces_dir} # Handle requests for the list of workspaces. Make slash optional. workspaces_api_path = ujoin(extension_app.workspaces_api_url, '?') handlers.append( (workspaces_api_path, WorkspacesHandler, workspaces_config)) # Handle requests for an individually named workspace. workspace_api_path = ujoin(extension_app.workspaces_api_url, '(?P<space_name>.+)') handlers.append( (workspace_api_path, WorkspacesHandler, workspaces_config)) # Handle local listings. settings_config = extension_app.settings.get('config', {}).get('LabServerApp', {}) blocked_extensions_uris = settings_config.get('blocked_extensions_uris', '') allowed_extensions_uris = settings_config.get('allowed_extensions_uris', '') if (blocked_extensions_uris) and (allowed_extensions_uris): print( 'Simultaneous blocked_extensions_uris and allowed_extensions_uris is not supported. Please define only one of those.' ) import sys sys.exit(-1) ListingsHandler.listings_refresh_seconds = settings_config.get( 'listings_refresh_seconds', 60 * 60) ListingsHandler.listings_request_opts = settings_config.get( 'listings_request_options', {}) listings_url = ujoin(extension_app.listings_url) listings_path = ujoin(listings_url, '(.*)') if blocked_extensions_uris: ListingsHandler.blocked_extensions_uris = set( blocked_extensions_uris.split(',')) if allowed_extensions_uris: ListingsHandler.allowed_extensions_uris = set( allowed_extensions_uris.split(',')) fetch_listings(None) if len(ListingsHandler.blocked_extensions_uris) > 0 or len( ListingsHandler.allowed_extensions_uris) > 0: from tornado import ioloop ListingsHandler.pc = ioloop.PeriodicCallback( lambda: fetch_listings(None), callback_time=ListingsHandler.listings_refresh_seconds * 1000, jitter=0.1) ListingsHandler.pc.start() handlers.append((listings_path, ListingsHandler, {})) # Handle local themes. if extension_app.themes_dir: themes_url = extension_app.themes_url themes_path = ujoin(themes_url, '(.*)') handlers.append((themes_path, ThemesHandler, { 'themes_url': themes_url, 'path': extension_app.themes_dir, 'labextensions_path': labextensions_path, 'no_cache_paths': no_cache_paths })) # Handle translations. if extension_app.translations_api_url: # Handle requests for the list of language packs available. # Make slash optional. translations_path = ujoin(extension_app.translations_api_url, '?') handlers.append((translations_path, TranslationsHandler, { 'lab_config': extension_app })) # Handle requests for an individual language pack. translations_lang_path = ujoin(extension_app.translations_api_url, '(?P<locale>.*)') handlers.append((translations_lang_path, TranslationsHandler, { 'lab_config': extension_app })) # Let the lab handler act as the fallthrough option instead of a 404. fallthrough_url = ujoin(extension_app.app_url, r'.*') handlers.append((fallthrough_url, NotFoundHandler))
usertitle = [] def ontimeReadUserTitle(): tmp = sqlutil.ReadDataFromDB('usertitle') tmp = list(tmp) tmp.sort(key=lambda x: x['exp']) global usertitle usertitle = tmp txt = json.dumps(usertitle, encoding='utf-8', ensure_ascii=False, indent=2) print(txt) logger.info(txt) ioloop.PeriodicCallback(ontimeReadUserTitle, 1000 * 60 * 30).start() ontimeReadUserTitle() def getusertitle(exp): global usertitle if exp < usertitle[0]['exp']: #return '' return 0 if exp >= usertitle[-1]['exp']: #return usertitle[-1]['title'] return len(usertitle) for i in range(1, len(usertitle)): if exp < usertitle[i]['exp']: #return usertitle[i - 1]['title'] return i + 1
raise Exception("Reset error") except Exception as err: self._respond_error(err) app = web.Application( handlers=[ (r"/ingest/(?P<user_id>.*)/?", IngestHandler), (r"/generate/(?P<user_id>.*)/?", GenerateHandler), (r"/symbols/?", SymbolsHandler), (r"/reset/(?P<user_id>.*)/?", ResetHandler), ], compress_response=True, log_function=_tornado_logger ) if __name__ == "__main__": workers = [Worker() for _ in range(5)] [w.start() for w in workers] loop = ioloop.IOLoop.instance() server = httpserver.HTTPServer(request_callback=app, io_loop=loop) server.listen(address="0.0.0.0", port=5000) cb = ioloop.PeriodicCallback(_check_closed, 1000, io_loop=loop) cb.start() loop.start() [w.join() for w in workers]
return print("I've started retrieving the altitude") altitude = yield self.retrieve_altitude() print("I've finished retrieving the altitude") response = {'altitude': altitude} self.set_status(status.HTTP_200_OK) self.write(response) self.finish() @run_on_executor(executor="_thread_pool") def retrieve_altitude(self): return drone.altimeter.get_altitude() class Application(web.Application): def __init__(self, **kwargs): handlers = [ (r"/hexacopters/([0-9]+)", AsyncHexacopterHandler), (r"/leds/([0-9]+)", AsyncLedHandler), (r"/altimeters/([0-9]+)", AsyncAltimeterHandler), ] super(Application, self).__init__(handlers, **kwargs) if __name__ == "__main__": application = Application() application.listen(8888) tornado_ioloop = ioloop.IOLoop.instance() ioloop.PeriodicCallback(lambda: None, 500, tornado_ioloop).start() tornado_ioloop.start()