Exemplo n.º 1
0
def main():
    server = make_app()
    server.listen(options.port, options.address)
    print('listening on ' + str(options.address) + ':' + str(options.port))
    autoreload.start()
    autoreload.watch(config_path.web)
    IOLoop.instance().start()
Exemplo n.º 2
0
 def add_optional_autoreload_files(file_list: List[str]) -> None:
     for filen in file_list:
         if os.path.isdir(filen):
             log.warning("Cannot watch directory " + filen)
             continue
         log.info("Watching: " + filen)
         watch(filen)
Exemplo n.º 3
0
    def run(self, args):
        settings = self.get_settings()

        for name in map(basename, glob(join('controllers', '*.py'))):
            autoreload.watch(name)
            Module.load(self.get_controller_import_path(name))

        from shrine.routes import make_application

        MESSAGE = "{} running at http://localhost:{}\n".format(
            settings.PRODUCT_NAME,
            settings.PORT,
        )

        application = make_application()
        application.listen(settings.PORT)
        self.log.bold_green(MESSAGE)

        from shrine.log import logger
        logger.setLevel(logging.WARNING)

        try:
            autoreload.start()
            IOLoop.instance().start()
        except KeyboardInterrupt:
            self.log.bold_red_on_black("\rInterrupted by the User (Control-C)\n")
Exemplo n.º 4
0
def static_watcher():
  for dir, sub, files in os.walk(sys.path[0]):
    if dir[0:3] == './.':  # ignore dirname == '.\w'
      continue
    for f in files:
      if f[0] != '.':  # ignore filename == '.\w'
        autoreload.watch(os.path.abspath(os.path.join(dir, f)))
def start_thememapper():
    global nav
    global mapper
    #initialize the necessary classes
    mapper = Mapper(get_settings())
    nav = Navigation()
    # Adds the ability to set config file and port through commandline
    p = optparse.OptionParser()
    p.add_option('--port', '-p', default=mapper.port,help='port thememapper should run at')
    p.add_option('--diazo', '-d', default=False,action="store_true",dest="diazo",help='force diazo server to run')
    p.add_option('--diazo_port', '-f', default=mapper.diazo_port,help='port diazo should run at')
    options = p.parse_args()[0]
    mapper.port = options.port
    mapper.diazo_port = options.diazo_port
    #start thememapper
    print "Starting thememapper on http://0.0.0.0:" + mapper.port
    HTTPServer(WSGIContainer(app)).listen(mapper.port)
    if options.diazo or mapper.diazo_run == 'True':
        try: 
            from thememapper.diazo import server
            print "Starting diazo on http://0.0.0.0:" + mapper.diazo_port
            HTTPServer(server.get_application(mapper)).listen(mapper.diazo_port)
        except ImportError: 
            print "You will need to install thememapper.diazo before being able to use this function." 
    ioloop = IOLoop.instance()
    autoreload.watch(os.path.join(os.path.dirname(__file__), 'settings.properties'))
    autoreload.add_reload_hook(reload)
    autoreload.start(ioloop)
    ioloop.start()
Exemplo n.º 6
0
 def add_optional_autoreload_files(file_list):
     for filen in file_list:
         if os.path.isdir(filen):
             log.warning("Cannot watch directory " + filen)
             continue
         log.info("Watching: " + filen)
         watch(filen)
Exemplo n.º 7
0
 def enable_autoreload(self, watch_dirs=list()):
     for current_dir in watch_dirs:
         if not os.path.isdir(current_dir):
             continue
         for (path, dirs, files) in os.walk(current_dir):
             for item in files:
                 autoreload.watch(os.path.join(path, item))
     autoreload.start(self.__io_loop)
Exemplo n.º 8
0
def _add_watch_path(path: pathlib.Path) -> None:
    if _is_exclude(path.name):
        return
    elif path.is_dir():
        for f in path.iterdir():
            _add_watch_path(f)
    elif path.is_file():
        autoreload.watch(str(path))
Exemplo n.º 9
0
 def enable_autoreload(self, watch_dirs=list()):
     for current_dir in watch_dirs:
         if not os.path.isdir(current_dir):
             continue
         for (path, dirs, files) in os.walk(current_dir):
             for item in files:
                 autoreload.watch(os.path.join(path, item))
     autoreload.start(self.__io_loop)
Exemplo n.º 10
0
def static_watcher(path):
  global _base_path
  _base_path = os.path.abspath(path)
  for dir, sub, files in os.walk(path):
    if dir[0:3] != './.':  # ignore dirname == '.\w'
      for f in files:
        if f[0] != '.':  # ignore filename == '.\w'
          autoreload.watch(os.path.abspath(os.path.join(dir, f)))
Exemplo n.º 11
0
def _add_watch_path(path: pathlib.Path):
    if _is_exclude(path.name):
        return
    elif path.is_dir():
        for f in path.iterdir():
            _add_watch_path(f)
    elif path.is_file():
        autoreload.watch(str(path))
Exemplo n.º 12
0
def main():
    server.git = git.bake(_cwd=server.settings.repo)
    if options.listen_localhost_only:
        server.listen(options.port, 'localhost')
    else:
        server.listen(options.port)
    autoreload.start()
    autoreload.watch(config_path.web)
    IOLoop.instance().start()
Exemplo n.º 13
0
        def find_autoreload_targets(app_path: str) -> None:
            path = os.path.abspath(app_path)
            if not os.path.isdir(path):
                return

            for path, subdirs, files in os.walk(path):
                for name in files:
                    if (fnmatch(name, '*.html') or fnmatch(name, '*.css')
                            or fnmatch(name, '*.yaml')):
                        log.info("Watching: " + os.path.join(path, name))
                        watch(os.path.join(path, name))
Exemplo n.º 14
0
def legacy_bootstrap(config):
    # Compat with legacy load_plugins
    config.plugins = {}

    autoreload.watch(config.temboard.configfile)

    # Run temboard as a background daemon.
    if config.temboard.daemonize:
        daemonize(config.temboard.pidfile, config)

    return config
Exemplo n.º 15
0
 def load_react_assets():
     try:
         fn = options.react_assets_file
         with open(fn) as f:
             watch(fn)
             assets = json.load(f)
     except IOError:
         assets = None
     except KeyError:
         assets = None
     return assets
Exemplo n.º 16
0
        def find_autoreload_targets(app_path):
            path = os.path.abspath(app_path)
            if not os.path.isdir(path):
                return

            for path, subdirs, files in os.walk(path):
                for name in files:
                    if (fnmatch(name, '*.html') or
                        fnmatch(name, '*.css') or
                        fnmatch(name, '*.yaml')):
                        log.info("Watching: " + os.path.join(path, name))
                        watch(os.path.join(path, name))
Exemplo n.º 17
0
def main(vixen):
    html_file = join(dirname(__file__), 'html', 'vixen_ui.html')
    template = Template(html_file=html_file, base_url='/', async=True)
    ioloop = IOLoop.instance()
    app = WebApp(
        template=template, context={'vixen':vixen}, port=8000,
        autoreload=True
    )
    autoreload.watch(html_file)
    app.listen(8000)
    url = 'http://localhost:8000'
    print "Point your browser to", url
    ioloop.start()
Exemplo n.º 18
0
def main():
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)

    from tornado import autoreload
    autoreload.watch("templates/home.html")
    autoreload.watch("templates/users.html")
    autoreload.watch("templates/changepassword.html")
    autoreload.watch("templates/register.html")
    autoreload.watch("templates/register_stepone.html")
    autoreload.start()
    tornado.ioloop.IOLoop.instance().start()
Exemplo n.º 19
0
    def _load_inclusion(self, inclusion):
        source_location = inclusion.attribute('src')

        if source_location[0] != '/':
            source_location = os.path.join(self._config_base_path, source_location)

        pre_config = load_from_file(source_location)

        self._configure(pre_config, source_location)

        watch(source_location)

        self._logger.info('Included the configuration from %s' % source_location)
Exemplo n.º 20
0
    def __init__(self, configuration_location, **settings):
        BaseApplication.__init__(self, **settings)

        self._config_main_path = os.path.join(self._base_path, configuration_location)
        self._config_base_path = os.path.dirname(self._config_main_path)

        self._config = load_from_file(self._config_main_path)

        # Initialize the routing map
        self._routing_map = RoutingMap()

        # Default properties
        self._scope = settings['scope'] if 'scope' in settings else None
        self._port  = 8000

        # Register the default services.
        self._register_default_services()

        # Add the main configuration to the watch list.
        watch(self._config_main_path)

        # Configure the included files first.
        for inclusion in self._config.children('include'):
            source_location = inclusion.attribute('src')

            if source_location[0] != '/':
                source_location = os.path.join(self._config_base_path, source_location)

            pre_config = load_from_file(source_location)

            self._configure(pre_config, source_location)

            watch(source_location)

            self._logger.info('Included the configuration from %s' % source_location)

        self._configure(self._config)

        # Override the properties with the parameters.
        if 'port' in settings:
            self._port = settings['port']
            self._logger.info('Changed the listening port: %s' % self._port)

        # Update the routing map
        AppServices.get('routing_map').update(self._routing_map)

        # Normal procedure
        self._update_routes(self._routing_map.export())
        self.listen(self._port)
        self._activate()
Exemplo n.º 21
0
    def _load_new_style_configuration(self, configuration):
        # Load the data directly from a JSON file.
        for inclusion in configuration.children('use'):
            source_location = inclusion.attribute('src')

            if source_location[0] != '/':
                source_location = os.path.join(self._config_base_path, source_location)

            with open(source_location) as f:
                decoded_config = json.load(f)

                self._override_sub_config_tree(self._settings, decoded_config)

                watch(source_location)
Exemplo n.º 22
0
def initalize_webpack():
    from tornado import autoreload

    try:
        fn = 'webpack-assets.json'
        with open(fn) as f:
            autoreload.watch(fn)

            assets = json.load(f)
            define('ASSETS', assets)
    except IOError:
        pass
    except KeyError:
        pass
Exemplo n.º 23
0
def legacy_bootstrap(config):
    # Compat with legacy load_plugins
    config.plugins = {}

    logging.config.dictConfig(
        generate_logging_config(systemd='SYSTEMD' in os.environ,
                                **config.logging))
    logger.info("Starting main process.")
    autoreload.watch(config.temboard.configfile)

    # Run temboard as a background daemon.
    if config.temboard.daemonize:
        daemonize(config.temboard.pidfile, config)

    return config
Exemplo n.º 24
0
    def __init__(self, configuration_location, **settings):
        BaseApplication.__init__(self, **settings)

        self._service_assembler = ImaginationAssembler(ImaginationTransformer(AppServices))
        self._config_main_path = os.path.join(self._base_path, configuration_location)
        self._config_base_path = os.path.dirname(self._config_main_path)

        self._config = load_from_file(self._config_main_path)

        # Initialize the routing map
        self._routing_map = RoutingMap()

        # Default properties
        self._scope = settings['scope'] if 'scope' in settings else None
        self._port  = 8000

        # Register the default services.
        self._register_default_services()

        # Add the main configuration to the watch list.
        watch(self._config_main_path)

        # Configure with the configuration files
        self._service_assembler.activate_passive_loading()

        for inclusion in self._config.children('include'):
            self._load_inclusion(inclusion)

        self._configure(self._config)

        self._prepare_db_connections()
        self._prepare_session_manager()

        self._service_assembler.deactivate_passive_loading()

        # Override the properties with the parameters.
        if 'port' in settings:
            self._port = settings['port']
            self._logger.info('Changed the listening port: %s' % self._port)

        # Update the routing map
        AppServices.get('routing_map').update(self._routing_map)

        # Normal procedure
        self._update_routes(self._routing_map.export())
        self.listen(self._port)
        self._activate()
Exemplo n.º 25
0
    def __init__(self, world):

        self.world = world
        self._id = itertools.count(1)
        self._entities = {}
        self._components = collections.defaultdict(set)

        if os.path.exists(ARCHETYPES):
            from tornado import autoreload
            autoreload.watch(ARCHETYPES)

            with open(ARCHETYPES) as f:
                self._archetypes = {}

                archetypes = yaml.load(f.read())

                for name in venom.utils.topsort({name: archetype.get('extend') for name, archetype in archetypes.items()}):
                    archetype = archetypes[name]

                    components = {}

                    if 'extend' in archetype:
                        components = self._archetypes[archetype['extend']].copy()

                    if 'components' in archetype:
                        for component, kwargs in archetype['components'].items():
                            pieces = component.split('.')
                            module = importlib.import_module('.'.join(pieces[:-1]))

                            try:
                                cls = getattr(module, pieces[-1])

                                if cls not in components:
                                    components[cls] = kwargs
                                else:
                                    components[cls] = components[cls].copy()
                                    components[cls].update(kwargs)
                            except Exception:
                                logger.error('Unknown component "%s"' % component)
                                exit(0)

                    self._archetypes[name] = components
Exemplo n.º 26
0
    def run(self) -> None:
        self.settings.setup_elasticsearch_connection()

        # The following is a simpler `bokeh serve src/nasty_analysis/visualization`.
        # Code for that is in `bokeh.commands.subcommands.serve.Serve.invoke`.
        # Also Bokeh provides this example:
        # https://github.com/bokeh/bokeh/blob/2.0.2/examples/howto/server_embed/standalone_embed.py

        address = self.settings.analysis.serve.address
        port = self.settings.analysis.serve.port
        num_procs = self.settings.analysis.num_procs
        autoreload = False

        if self.develop:
            num_procs = 1
            autoreload = True

            watch(str(self.settings.find_settings_file()))

            for file in Path(nasty_analysis.__file__).parent.glob("**/*.js"):
                watch(str(file))

        application = ParameterPassingApplication(
            DirectoryHandler(filename=Path(serve.__file__).parent),
            server_context_params={"settings": self.settings},
        )
        with report_server_init_errors(address=address, port=port):
            server = Server(
                {"/": application},
                address=address,
                port=port,
                allow_websocket_origin=[f"{address}:{port}"],
                num_procs=num_procs,
                autoreload=autoreload,
            )
            server.start()

            if self.show:
                server.io_loop.add_callback(server.show, "/")
            server.run_until_shutdown()
Exemplo n.º 27
0
    def run(self):
        sys.path.insert(0, self.projectPath)
        os.chdir(self.projectPath)
        print(self.projectPath)

        if self.apps_ports:
            for x in self.projectConfig['BACKEND']:
                current_port = self.projectConfig['BACKEND'][x]['port']
                handlers_app = importlib.import_module(
                    "backapps.{0}.handlers".format(x))
                if isinstance(handlers_app.HANDLER, (list, tuple)):
                    app = web.Application(handlers_app.HANDLER,
                                          **handlers_app.SETTINGS)
                    app_http_server = httpserver.HTTPServer(app)
                    app_http_server.listen(int(current_port))
                else:
                    app = handlers_app.HANDLER
                    app_http_server = httpserver.HTTPServer(app)
                    app_http_server.listen(int(current_port))

            for x in self.projectConfig['FRONTEND']:
                current_port = self.projectConfig['FRONTEND'][x]['port']
                handlers_app = importlib.import_module(
                    "frontapps.{0}.handlers".format(x))
                if isinstance(handlers_app.HANDLER, (list, tuple)):
                    app = web.Application(handlers_app.HANDLER,
                                          **handlers_app.SETTINGS)
                    app_http_server = httpserver.HTTPServer(app)
                    app_http_server.listen(int(current_port))
                else:
                    app = handlers_app.HANDLER
                    app_http_server = httpserver.HTTPServer(app)
                    app_http_server.listen(int(current_port))
        autoreload.watch(os.path.join(self.projectPath, "config.json"))
        ioloop.IOLoop.current().start()
        print("start stopped")
        ioloop.IOLoop.current().add_callback(
            lambda: ioloop.IOLoop.current().close(True))
        print("close? Don't know")
Exemplo n.º 28
0
def main():
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    main_loop= tornado.ioloop.IOLoop.instance()
    #tornado.ioloop.PeriodicCallback(test2, 5000).start()
    tornado.ioloop.PeriodicCallback(updateEvents, PERIOD).start()
    #main_loop.add_timeout(datetime.timedelta(seconds=5), test)
    #remove in prod
    autoreload.start(main_loop)
    dirstowatch=['/vagrant/smartevents/static','/vagrant/smartevents/templates']
    for directory in dirstowatch:
		for dir, _, files in os.walk(directory):
			[autoreload.watch(dir + '/' +f) for f in files if not f.startswith('.')]
    main_loop.start()
Exemplo n.º 29
0
def main():
    tornado.options.parse_command_line()
    app = Application()
    app.listen(options.port)
    main_loop = tornado.ioloop.IOLoop.instance()
    #tornado.ioloop.PeriodicCallback(test2, 5000).start()
    tornado.ioloop.PeriodicCallback(updateEvents, PERIOD).start()
    #main_loop.add_timeout(datetime.timedelta(seconds=5), test)
    #remove in prod
    autoreload.start(main_loop)
    dirstowatch = [
        '/vagrant/smartevents/static', '/vagrant/smartevents/templates'
    ]
    for directory in dirstowatch:
        for dir, _, files in os.walk(directory):
            [
                autoreload.watch(dir + '/' + f) for f in files
                if not f.startswith('.')
            ]
    main_loop.start()
Exemplo n.º 30
0
from messanger.handlers.socket import MessagesSocketHandler
from messanger.handlers.api import GetContacts, GetChat

application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/messages", MessagesSocketHandler),
    (r"/api/account/(.+)/contacts", GetContacts),
    (r"/api/chat/(.+)/(.+)", GetChat),
    (r"/chat/(.+)/", ChatHandler),
],
                                      static_path='static',
                                      debug=True)

if __name__ == "__main__":
    assets = None
    try:
        fn = '../webpack-assets.json'
        with open(fn) as f:
            watch(fn)
            assets = json.load(f)
    except IOError as e:
        print("IOError: ", e)
        pass
    except KeyError as e:
        print("KeyError: ", e)
        pass

    define('ASSETS', assets)
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()
    def __init__(self):
        settings = dict(
            static_path=os.path.join(
                os.path.dirname(__file__),
                "static"),  # tell where to find static dir
            template_path=os.path.join(os.path.dirname(__file__), 'templates'),
            debug=True,
            cookie_secret="61yUTzRANAGaYdkL5gEmChenxiYh7EQnp2XdTP1o/Vo=",
            login_url="/login",
        )
        handlers = [(r'/', MainHandler), (r'/text', TextHandler),
                    (r"/login", LoginHandler), (r"/logout", LogoutHandler),
                    (r"/(apple-touch-icon\.png)", web.StaticFileHandler,
                     dict(path=settings['static_path']))]

        conn = pymongo.MongoClient('localhost', 27017)
        self.db = conn.page_text_db
        web.Application.__init__(self, handlers, **settings)


if __name__ == '__main__':
    # temp_dir = tempfile.mkdtemp(dir=os.path.join(os.path.dirname(__file__), "static"))
    options.parse_command_line()
    http_server = httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    # TODO remove in prod
    autoreload.start()
    autoreload.watch('template.html es_method.py search_results.html')

    ioloop.IOLoop.instance().start()
Exemplo n.º 32
0
    def __init__(self, config, watch, web_root, cache_index, debug=False):
        autoreload.watch(config)
        autoreload.watch(watch)
        autoreload.add_reload_hook(self.before_reload_done)

        self.log('config ' + config)
        self.log('watch ' + watch)

        self.load_config(config)
        self.load_config(watch)

        if not os.path.exists(os.path.dirname(cache_index)):
            os.makedirs(os.path.dirname(cache_index))

        self.settings['web_root'] = web_root
        self.cache_index = cache_index
        self.debug = debug
        if self.debug:
            self.log("debug is enabled")
            self.log("config used: " + config)
            self.log("web root: " + web_root)
            self.log("cache index: " + cache_index)

        self.cache = self.load_cache()

        if self.settings['css_inlined'] != '':
            self.settings['css_files'].append(self.settings['css_inlined'])

        for f in self.settings['css_files']:
            self.log('watch css ' + f)
            autoreload.watch(self.get_file_path(f))

        self.settings['js_files'].append(self.settings['js_loader'])

        for f in self.settings['js_files']:
            self.log('watch js [' + f['name'] + '] ' + f['file'])
            if f['name'] != 'loader':
                autoreload.watch(self.get_file_path(f['file']))
            else:
                autoreload.watch(f['file'])

        if 'preload_templates' in self.settings:
            loader = template.Loader(self.settings['templates_dir'])

            for f in self.settings['preload_templates']:
                self.log('watch template ' + f)
                autoreload.watch(self.settings['templates_dir'] + f)
                self.templates.append({'file': f, 'template': loader.load(f)})

        self.recompile()

        self.cache_css_inlined = self.get_inlined_css()
        self.cache_css_js_loader = self.get_loader()
Exemplo n.º 33
0
        "thank you",
        "agree",
        "disagree",
        "not constructive",
        "troll",
        "spam",
    ]

    # start
    if args.prod:
        # run on Tornado instead, since running raw Flask in prod is not recommended
        print("starting tornado!")
        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.log import enable_pretty_logging
        from tornado import autoreload

        enable_pretty_logging()
        http_server = HTTPServer(WSGIContainer(app))
        http_server.listen(args.port)
        ioloop = IOLoop.instance()
        # Auto-reload after modifying templates
        autoreload.start()
        autoreload.watch(Config.db_serve_path)
        ioloop.start()
    else:
        print("starting flask!")
        app.debug = False
        app.run(port=args.port, host="0.0.0.0")
Exemplo n.º 34
0
def main():
    server.git = git.bake(_cwd=server.settings.repo)
    server.listen(options.port, 'localhost')
    autoreload.start()
    autoreload.watch(config_path.web)
    IOLoop.instance().start()
Exemplo n.º 35
0
    if sys.platform.startswith('win'):
        base_url = ''

    html_file = get_html_file()
    html = get_html(html_file)
    template = VueTemplate(html=html, base_url=base_url, async=async)
    silence_tornado_access_log()
    ioloop = IOLoop.instance()
    if port is None:
        if dev:
            port = 8000
        else:
            from jigna.utils.web import get_free_port
            port = get_free_port()

    app = WebApp(template=template,
                 context=context,
                 port=port,
                 async=async,
                 autoreload=True)
    autoreload.watch(html_file)
    app.listen(port)
    url = 'http://localhost:%d' % port
    if dev:
        print("Point your browser to", url)
    else:
        webbrowser.open(url)
    if not test:
        # When running tests, don't start the ioloop.
        ioloop.start()
Exemplo n.º 36
0
 def watch(self, file=None):
     if file is not None:
         autoreload.watch(file)
Exemplo n.º 37
0
 def watch(self,file = None):
     if file is not None:
         autoreload.watch(file)
Exemplo n.º 38
0
    print(users)


@sio.event
def disconnect(sid):
    print('disconnect ', sid)
    sio.leave_room(sid, 'chat_users')


class SendMessageHandler(tornado.web.RequestHandler):
    async def get(self):
        data = {'data': 'bla'}
        await sio.emit('ping', data, room='chat_users')
        self.write("Hello, world")


def make_app():
    return tornado.web.Application([
        # test page
        (r"/send", SendMessageHandler),
        (r"/websocket/", socketio.get_tornado_handler(sio)),
    ])


if __name__ == "__main__":
    print('Starting server on 8888 port')
    autoreload.start()
    autoreload.watch('tornado_server.py')
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
Exemplo n.º 39
0
def main():
    server = make_app()
    server.listen(options.port, options.address)
    autoreload.start()
    autoreload.watch(config_path.web)
    IOLoop.instance().start()
Exemplo n.º 40
0
    def run(self, *args, **kwargs):
        """Run bot."""

        self.logger.info(cactus_art)
        self._init_database(self.database)
        self.load_config(filename=self.config_file)
        self.load_stats(filename=self.stats_file)

        while self.config.get("autorestart") or not self.started:
            try:
                self.bot_data = self.login(**self.config["auth"])
                self.logger.info("Authenticated as: {}.".format(
                    self.bot_data["username"]))

                self.started = True

                self.channel = self.config["channel"]
                self.channel_data = self.get_channel(self.channel)

                self._init_commands()

                self.connect(self.channel_data["id"],
                             self.bot_data["id"],
                             silent=self.silent)

                self.connect_to_liveloading(self.channel_data["id"],
                                            self.channel_data["userId"])

                if str(self.debug).lower() in ("true", "debug"):
                    add_reload_hook(
                        partial(
                            self.send_message,
                            "Restarting, thanks to debug mode. :spaceship"))
                    watch(self.config_file)
                    start(check_time=5000)

                IOLoop.instance().start()

            except KeyboardInterrupt:
                print()
                self.logger.info("Removing thorns... done.")
                try:
                    self.send_message("CactusBot deactivated! :cactus")
                except Exception:
                    pass
                finally:
                    exit()

            except Exception:
                self.logger.critical("Oh no, I crashed!")

                try:
                    self.send_message("Oh no, I crashed! :127")
                except Exception:
                    pass

                self.logger.error('\n\n' + format_exc())

                if self.config.get("autorestart"):
                    self.logger.info("Restarting in 10 seconds...")
                    try:
                        sleep(10)
                    except KeyboardInterrupt:
                        self.logger.info("CactusBot deactivated.")
                        exit()
                else:
                    self.logger.info("CactusBot deactivated.")
                    exit()
Exemplo n.º 41
0
    # обработчик закрытия соединения клиентом
    def on_close(self):
        print('close connection')
        # удаление соединения из глобального словаря
        del ws_clients[self.client_id]
        send_cliens_to_all()


# конфигурируем приложение роутингом
def make_app():
    return tornado.web.Application([
        # главная страница
        (r"/", MainHandler),
        # отдача статики
        (r'/static/(.*)', tornado.web.StaticFileHandler, {
            'path': 'static'
        }),
        # запросы по веб-сокету
        (r"/websocket", WebsocketHandler),
    ])


if __name__ == "__main__":
    print('Starting server on 8888 port')
    autoreload.start()
    autoreload.watch('.')
    autoreload.watch('index.html')
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()
Exemplo n.º 42
0
def create_app(): 
    try:
        from plsys.wsgi import application
    except ImportError, e:
        print e
        return None
    return application

app = create_app()
if app is None:
    print "Cannot import plsys"
    sys.exit()

port = 8000 #if DEPLOYMENT_LEVEL == 'local' else 80

http_server = HTTPServer(WSGIContainer(app))
http_server.listen(port)
ioloop = IOLoop.instance()

autoreload.start(ioloop)
watchlist = []
for dirpath,_,filenames in os.walk(BASE_DIR):
    for f in filenames:
        if f.endswith('.py'):
            watchlist.append(os.path.abspath(os.path.join(dirpath, f)))
    
for file in watchlist:
    autoreload.watch(file)

ioloop.start()
Exemplo n.º 43
0
def watcher(fn, watchset=set()):
    if fn not in watchset:
        autoreload.watch(fn)
        logging.debug("Autoreload: {}".format(fn))
        watchset.add(fn)
Exemplo n.º 44
0
def addwatchfiles(*paths):
    for p in paths:
        autoreload.watch(os.path.abspath(p))
Exemplo n.º 45
0
def watch_directory(directory):
    """Adds a given directory to the autoreload watch list."""
    for filename in os.listdir(directory):
        watch(os.path.join(directory, filename))
Exemplo n.º 46
0
 def intialize_watcher(self):
     self.watched_dirs = ["static/css", "static/js"]
     if self.settings.get('debug'):
         for wdir in self.watched_dirs:
             for filename in os.listdir(wdir):
                 autoreload.watch(os.path.abspath(os.path.join(wdir, filename)))
Exemplo n.º 47
0
 def seek_and_destroy(self):
     for name in map(basename, glob(join('controllers', '*.py'))):
         module_cache.append(
             Module.load(self.get_controller_import_path(name)))
         autoreload.watch(name)
Exemplo n.º 48
0
        "thank you",
        "agree",
        "disagree",
        "not constructive",
        "troll",
        "spam",
    ]

    # start
    if args.prod:
        # run on Tornado instead, since running raw Flask in prod is not recommended
        print("starting tornado!")
        from tornado.wsgi import WSGIContainer
        from tornado.httpserver import HTTPServer
        from tornado.ioloop import IOLoop
        from tornado.log import enable_pretty_logging
        from tornado import autoreload

        enable_pretty_logging()
        http_server = HTTPServer(WSGIContainer(app))
        http_server.listen(args.port)
        ioloop = IOLoop.instance()
        # Auto-reload after modifying templates
        autoreload.start()
        autoreload.watch(Config.db_serve_path)
        ioloop.start()
    else:
        print("starting flask!")
        app.debug = False
        app.run(port=args.port, host="0.0.0.0")
Exemplo n.º 49
0
    def run(self, *args, **kwargs):
        """Run bot."""

        self.logger.info(cactus_art)
        self._init_database(self.database)
        self.load_config(filename=self.config_file)
        self.load_stats(filename=self.stats_file)

        while self.config.get("autorestart") or not self.started:
            try:
                self.bot_data = self.login(**self.config["auth"])
                self.logger.info("Authenticated as: {}.".format(
                    self.bot_data["username"]))

                self.started = True

                self.channel = self.config["channel"]
                self.channel_data = self.get_channel(self.channel)

                self._init_commands()

                self.connect(
                    self.channel_data["id"],
                    self.bot_data["id"],
                    silent=self.silent)

                self.connect_to_liveloading(
                    self.channel_data["id"],
                    self.channel_data["userId"])

                if str(self.debug).lower() in ("true", "debug"):
                    add_reload_hook(partial(
                        self.send_message,
                        "Restarting, thanks to debug mode. :spaceship"
                    ))
                    watch(self.config_file)
                    start(check_time=5000)

                IOLoop.instance().start()

            except KeyboardInterrupt:
                print()
                self.logger.info("Removing thorns... done.")
                try:
                    self.send_message("CactusBot deactivated! :cactus")
                except Exception:
                    pass
                finally:
                    exit()

            except Exception:
                self.logger.critical("Oh no, I crashed!")

                try:
                    self.send_message("Oh no, I crashed! :127")
                except Exception:
                    pass

                self.logger.error('\n\n' + format_exc())

                if self.config.get("autorestart"):
                    self.logger.info("Restarting in 10 seconds...")
                    try:
                        sleep(10)
                    except KeyboardInterrupt:
                        self.logger.info("CactusBot deactivated.")
                        exit()
                else:
                    self.logger.info("CactusBot deactivated.")
                    exit()
Exemplo n.º 50
0
# entry point to start our app
# python imports
import os

# external imports
from tornado import autoreload
from tornado.ioloop import IOLoop

# local imports
from services.app import make_app

# Main function
if __name__ == '__main__':
    # Define application
    config_name = os.getenv('APP_SETTINGS')
    app = make_app(debug=True)
    app.listen(eval(os.getenv('TORNADO_PORT')))
    autoreload.start()
    autoreload.watch(
        os.path.join(os.path.dirname(__file__), os.getenv('MODELS_PATH')))
    IOLoop.instance().start()
Exemplo n.º 51
0
    # and cache it in file
    print('writing search_dict.p as cache')
    utils.safe_pickle_dump(SEARCH_DICT, 'search_dict.p')
  else:
    print('loading cached index for faster search...')
    SEARCH_DICT = pickle.load(open('search_dict.p', 'rb'))

  # start
  if args.prod:
    # run on Tornado instead, since running raw Flask in prod is not recommended
    print('starting tornado!')
    from tornado import autoreload
    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop
    from tornado.log import enable_pretty_logging

    enable_pretty_logging()
    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(args.port)
    ioloop = IOLoop.instance()
    #autoreload.watch("templates/main.html")
    autoreload.watch("db.p")
    autoreload.start() 
    ioloop.start()
    autoreload.wait()
  else:
    print('starting flask!')
    app.debug = True
    app.run(port=args.port)
Exemplo n.º 52
0
    ])


'''

app.listen(args.listen_port, args.listen_interface, ssl_options={ 
        "certfile": os.path.join(lib_dir, "mydomain.crt"),
        "keyfile": os.path.join(lib_dir, "mydomain.key"),
    })

'''
from backend.local import IS_SSL_SERVER
if __name__ == "__main__":
    print('Starting server on 8888 port')
    autoreload.start()
    autoreload.watch('socket_server.py')
    app = make_app()
    if IS_SSL_SERVER:
        app.listen(8888,
                   ssl_options={
                       "certfile": '/home/webmaster/cert1.pem',
                       "keyfile": '/home/webmaster/privkey1.pem',
                   })
    else:
        app.listen(8888)

    loop = IOLoop.current()
    loop.add_callback(setup)
    #loop.instance().spawn_callback(small_loop)
    loop.start()
Exemplo n.º 53
0
def main():
    server = make_app()
    server.listen(options.port, options.address)
    autoreload.start()
    autoreload.watch(config_path.web)
    IOLoop.instance().start()
Exemplo n.º 54
0
	def get(self):
		self.render('index.html', data=None	)


class StateLiteracy(tornado.web.RequestHandler):
	def get(self):
		data = pd.read_csv('state-literacy.csv')
		self.render('index.html', data=data.to_html())

class GenderLiteracy(tornado.web.RequestHandler):
	def get(self):
		data = pd.read_csv('gender-literacy.csv')
		self.render('index.html', data=data.to_html())


if __name__ == '__main__':
	tornado.options.parse_command_line()

	for d in os.listdir(os.getcwd()):
		autoreload.watch(os.path.abspath(os.path.abspath(d)))

	app = tornado.web.Application(handlers=[(r'/', MainHandler),
											(r'/state', StateLiteracy),
											(r'/gender', GenderLiteracy)],
								  autoreload=True,
								  templates_path=os.getcwd(),
								  static_path=os.getcwd())

	http_server = tornado.httpserver.HTTPServer(app)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()
Exemplo n.º 55
0
        del data['monster_table'][0]
        del data['flair_posts'][0]
        del data['ignores'][0]
        del data['deletes'][0]
        del data['revisits'][0]
        self.send(json.dumps(data))
    def on_close(self):
        mdb.close()

DBRouter = SockJSRouter(DBConnection, '/tamabot/db')
GraphRouter = SockJSRouter(GraphConnection, '/tamabot/graph')

settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static")
}

app = web.Application([
    (r'/tamabot/', MainHandler),
    (r'/tamabot/(pure\.css)', web.StaticFileHandler, dict(path=settings['static_path'])),
    (r'/tamabot/(style\.css)', web.StaticFileHandler, dict(path=settings['static_path'])),
    (r'/tamabot/(tamabot\.png)', web.StaticFileHandler, dict(path=settings['static_path'])),
    (r'/tamabot/(tamabot2\.png)', web.StaticFileHandler, dict(path=settings['static_path'])),
] + DBRouter.urls + GraphRouter.urls, **settings)

server = httpserver.HTTPServer(app)
server.listen(8008)

for dir, _, files in os.walk('tamabot/static'):
    [autoreload.watch(dir + '/' + f) for f in files if not f.startswith('.')]
ioloop.IOLoop.instance().start()
Exemplo n.º 56
0
import json
from tornado.options import options, define
from tornado.autoreload import watch
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader("templates"))


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        template = env.get_template("index.html")
        self.write(template.render({"assets": options.ASSETS}))


application = tornado.web.Application([(r"/", MainHandler)], static_path="static", debug=True)

if __name__ == "__main__":
    try:
        fn = "webpack-assets.json"
        with open(fn) as f:
            watch(fn)
            assets = json.load(f)
    except IOError:
        pass
    except KeyError:
        pass

    define("ASSETS", assets)
    application.listen(8888)
    tornado.ioloop.IOLoop.current().start()
Exemplo n.º 57
0
def watcher(fn, watchset=set()):
    if fn not in watchset:
        autoreload.watch(fn)
        logging.debug("Autoreload: {}".format(fn))
        watchset.add(fn)
Exemplo n.º 58
0
        super().__init__(app_handlers, **app_settings)

    def log_request(self, request):
        """Override default to avoid logging requests"""
        pass


if __name__ == "__main__":
    boat = BoatPi(app_settings["boatpi_ws"], 5)
    boatLogger = MongoLogger()

    if app_settings["env"] == "dev":
        boatLogger.clear_logs()

        log.info("Starting applications", mode="single")
        Application().listen(app_settings["port"])

        autoreload.start()
        autoreload.watch(r'assets/')
        autoreload.watch(r'templates/')
        autoreload.watch(r'templates/modules/')
    else:
        log.info("Starting applications", mode="forked", cpu_count=cpu_count())
        server = HTTPServer(Application())
        server.bind(app_settings["port"])
        server.start(0)  # multi process mode (one process per cpu)

    ioloop = IOLoop.instance()
    ioloop.start()