Exemplo n.º 1
0
def build_command(context, basedir, settings_name):
    """
    Build project pages
    """
    # Set required environment variables to load settings
    if PROJECT_DIR_ENVVAR not in os.environ \
       or not os.environ[PROJECT_DIR_ENVVAR]:
        os.environ[PROJECT_DIR_ENVVAR] = basedir
    if SETTINGS_NAME_ENVVAR not in os.environ \
       or not os.environ[SETTINGS_NAME_ENVVAR]:
        os.environ[SETTINGS_NAME_ENVVAR] = settings_name

    # Load current project settings
    from optimus.conf.registry import settings

    # Debug output
    display_settings(settings, ('DEBUG', 'PROJECT_DIR', 'SOURCES_DIR',
                                'TEMPLATES_DIR', 'LOCALES_DIR'))

    initialize(settings)

    # Init webassets and builder
    assets_env = register_assets(settings)
    builder = PageBuilder(settings, assets_env=assets_env)
    pages_map = import_pages_module(settings.PAGES_MAP, basedir=basedir)

    # Proceed to page building from registered pages
    builder.build_bulk(pages_map.PAGES)
Exemplo n.º 2
0
def po(args):
    """
    Manage catalog for all knowed languages
    """
    starttime = datetime.datetime.now()
    # Init, load and builds
    root_logger = init_logging(args.loglevel.upper(), logfile=args.logfile)

    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings
    from optimus.utils import display_settings

    display_settings(settings, ('DEBUG', 'PROJECT_DIR', 'SOURCES_DIR',
                                'TEMPLATES_DIR', 'LOCALES_DIR'))

    i18n = I18NManager(root_logger, settings)

    # NOTE: Should we do this automatically to prevent error on missing files
    #       OR should we only do checking before and abort on the first missing file ?
    if args.init or args.update or args.compile:
        i18n.init_locales_dir()
        i18n.extract(force=args.update)
        i18n.init_catalogs()

    if args.update:
        i18n.update_catalogs()

    if args.compile:
        i18n.compile_catalogs()

    endtime = datetime.datetime.now()
    root_logger.info('Done in %s', str(endtime - starttime))
Exemplo n.º 3
0
def po_command(context, init, update, compile, basedir, settings_name):
    """
    Manage project translation catalogs for all registred languages
    """
    # Set required environment variables to load settings
    if PROJECT_DIR_ENVVAR not in os.environ \
       or not os.environ[PROJECT_DIR_ENVVAR]:
        os.environ[PROJECT_DIR_ENVVAR] = basedir
    if SETTINGS_NAME_ENVVAR not in os.environ \
       or not os.environ[SETTINGS_NAME_ENVVAR]:
        os.environ[SETTINGS_NAME_ENVVAR] = settings_name

    # Load current project settings
    from optimus.conf.registry import settings

    # Debug output
    display_settings(settings, ('DEBUG', 'PROJECT_DIR', 'SOURCES_DIR',
                                'TEMPLATES_DIR', 'LOCALES_DIR'))

    # Proceed to operations
    i18n = I18NManager(settings)

    if init or update or compile:
        i18n.init_locales_dir()
        i18n.build_pot(force=update)
        i18n.init_catalogs()

    if update:
        i18n.update_catalogs()

    if compile:
        i18n.compile_catalogs()
Exemplo n.º 4
0
def build(args):
    """
    Build elements for a project
    """
    starttime = datetime.datetime.now()
    # Init, load and builds
    root_logger = init_logging(args.loglevel.upper(), logfile=args.logfile)
    
    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings, import_project_module
    from optimus.builder.assets import register_assets
    from optimus.builder.pages import PageBuilder
    from optimus.utils import initialize, display_settings
    
    display_settings(settings, ('DEBUG', 'PROJECT_DIR','SOURCES_DIR','TEMPLATES_DIR','PUBLISH_DIR','STATIC_DIR','STATIC_URL'))
    
    if hasattr(settings, 'PAGES_MAP'):
        root_logger.info('Loading external pages map')
        pages_map = import_project_module(settings.PAGES_MAP)
        setattr(settings, 'PAGES', pages_map.PAGES)

    initialize(settings)
    # Assets
    assets_env = register_assets()
    # Pages
    pages_env = PageBuilder(assets_env=assets_env)
    pages_env.build_bulk(settings.PAGES)
    
    endtime = datetime.datetime.now()
    root_logger.info('Done in %s', str(endtime-starttime))
Exemplo n.º 5
0
def build_command(context, basedir, settings_name):
    """
    Build project pages
    """
    # Set project before to be able to load its modules
    setup_project(basedir, settings_name)

    # Load current project settings and page map
    settings = import_settings_module(settings_name, basedir=basedir)
    # In test environment, force the module reload to avoid previous test cache to be
    # used (since the module have the same path).
    if context.obj["test_env"]:
        settings = importlib.reload(settings)

    settings = load_settings(settings)

    views = import_pages_module(settings.PAGES_MAP, basedir=basedir)
    if context.obj["test_env"]:
        views = importlib.reload(views)

    # Debug output
    display_settings(
        settings,
        ("DEBUG", "PROJECT_DIR", "SOURCES_DIR", "TEMPLATES_DIR",
         "LOCALES_DIR"),
    )

    builder_interface(settings, views)
Exemplo n.º 6
0
def build(args):
    """
    Build elements for a project
    """
    starttime = datetime.datetime.now()
    # Init, load and builds
    root_logger = init_logging(args.loglevel.upper(), logfile=args.logfile)
    
    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings, import_pages_module
    from optimus.builder.assets import register_assets
    from optimus.builder.pages import PageBuilder
    from optimus.utils import initialize, display_settings
    
    display_settings(settings, ('DEBUG', 'PROJECT_DIR','SOURCES_DIR','TEMPLATES_DIR','PUBLISH_DIR','STATIC_DIR','STATIC_URL'))
    
    if hasattr(settings, 'PAGES_MAP'):
        root_logger.info('Loading external pages map')
        pages_map = import_pages_module(settings.PAGES_MAP)
        setattr(settings, 'PAGES', pages_map.PAGES)

    initialize(settings)
    # Assets
    assets_env = register_assets()
    # Pages
    pages_env = PageBuilder(assets_env=assets_env)
    pages_env.build_bulk(settings.PAGES)
    
    endtime = datetime.datetime.now()
    root_logger.info('Done in %s', str(endtime-starttime))
Exemplo n.º 7
0
def po(args):
    """
    Manage catalog for all knowed languages
    """
    starttime = datetime.datetime.now()
    # Init, load and builds
    root_logger = init_logging(args.loglevel.upper(), logfile=args.logfile)
    
    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings
    from optimus.utils import display_settings
    
    display_settings(settings, ('DEBUG', 'PROJECT_DIR','SOURCES_DIR','TEMPLATES_DIR','LOCALES_DIR'))
    
    i18n = I18NManager(root_logger, settings)
    
    # NOTE: Should we do this automatically to prevent error on missing files
    #       OR should we only do checking before and abort on the first missing file ?
    if args.init or args.update or args.compile:
        i18n.init_locales_dir()
        i18n.extract(force=args.update)
        i18n.init_catalogs()
    
    if args.update:
        i18n.update_catalogs()
    
    if args.compile:
        i18n.compile_catalogs()
    
    endtime = datetime.datetime.now()
    root_logger.info('Done in %s', str(endtime-starttime))
Exemplo n.º 8
0
    def runserver(args):
        """
        Launch the project watcher to automatically re-build knowed elements on changes
        """
        root_logger = init_logging(args.loglevel.upper(), printout=not(args.silent), logfile=args.logfile)

        # Only load optimus stuff after the settings module name has been retrieved
        os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
        from optimus.conf import settings
        from optimus.utils import display_settings

        display_settings(settings, ('DEBUG', 'PROJECT_DIR','PUBLISH_DIR','STATIC_DIR','STATIC_URL'))

        # Parse given hostname
        address, port = ("127.0.0.1", "80")
        _splits = args.hostname.split(':')
        if len(_splits)>2:
            raise CommandError("Error: Invalid hostname format, too many ':'")
        elif len(_splits)==2:
            address, port = _splits
            if not port or not address:
                raise CommandError("Error: Invalid hostname format, address or port is empty")
        else:
            port = _splits[0]

        try:
            int(port)
        except ValueError:
            raise CommandError("Error: Invalid port given: {0}".format(port))

        if not os.path.exists(settings.PUBLISH_DIR):
            raise CommandError("Error: Publish directory does not exist yet, you should build it before")

        # Run server with publish directory served with tools.staticdir
        print("Running HTTP server on address {address} with port {port}".format(address=address, port=port))

        cherrypy.config.update({
            'server.socket_host': address,
            'server.socket_port': int(port),
            'engine.autoreload_on': False,
        })

        conf = {
            '/': {
                'tools.staticdir.index': 'index.html',
                'tools.staticdir.on': True,
                'tools.staticdir.dir': settings.PUBLISH_DIR,
            },
        }
        cherrypy.quickstart(None, '/', config=conf)
Exemplo n.º 9
0
def runserver(args):
    """
    Launch the project watcher to automatically re-build knowed elements on changes
    """
    root_logger = init_logging(args.loglevel.upper(), printout=not(args.silent), logfile=args.logfile)
    
    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings, import_project_module
    from optimus.utils import display_settings
    
    display_settings(settings, ('DEBUG', 'PROJECT_DIR','PUBLISH_DIR','STATIC_DIR','STATIC_URL'))
    
    # Parse given hostname
    address, port = ("127.0.0.1", "80")
    _splits = args.hostname.split(':')
    if len(_splits)>2:
        raise CommandError("Error: Invalid hostname format, too many ':'")
    elif len(_splits)==2:
        address, port = _splits
        if not port or not address:
            raise CommandError("Error: Invalid hostname format, address or port is empty")
    else:
        port = _splits[0]
    
    try:
        int(port)
    except ValueError:
        raise CommandError("Error: Invalid port given: {0}".format(port))
    
    if not os.path.exists(settings.PUBLISH_DIR):
        raise CommandError("Error: Publish directory does not exist yet, you should build it before")
    
    # Run server with publish directory served with tools.staticdir
    print "Running http server on address {address} with port {port}".format(address=address, port=port)
    
    cherrypy.config.update({
        'server.socket_host': address,
        'server.socket_port': int(port),
        'engine.autoreload_on': False,
    })
    
    conf = {
        '/': {
            'tools.staticdir.index': 'index.html',
            'tools.staticdir.on': True,
            'tools.staticdir.dir': settings.PUBLISH_DIR,
        },
    }
    cherrypy.quickstart(None, '/', config=conf)
Exemplo n.º 10
0
def watch_command(context, basedir, settings_name):
    """
    Watch for changes in project sources to automatically build project
    ressources
    """
    logger = logging.getLogger("optimus")

    # Set project before to be able to load its modules
    setup_project(basedir, settings_name)

    # Load current project settings and page map
    settings = import_settings_module(settings_name, basedir=basedir)
    # In test environment, force the module reload to avoid previous test cache to be
    # used (since the module have the same path).
    if context.obj["test_env"]:
        settings = importlib.reload(settings)

    settings = load_settings(settings)

    views = import_pages_module(settings.PAGES_MAP, basedir=basedir)
    if context.obj["test_env"]:
        views = importlib.reload(views)

    # Debug output
    display_settings(
        settings,
        ("DEBUG", "PROJECT_DIR", "SOURCES_DIR", "TEMPLATES_DIR", "LOCALES_DIR"),
    )

    logger.debug("Trigger pages build to start")
    build_env = builder_interface(settings, views)

    # Init and configure observer with events
    observer = watcher_interface(settings, views, build_env)

    logger.warning("Starting to watch sources, use CTRL+C to stop it")
    # Do not start observer during tests since we cannot manage interruption and
    # watcher threads
    if not context.obj["test_env"]:
        observer.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            logger.warning("Stopping watcher..")
            observer.stop()
        observer.join()
Exemplo n.º 11
0
def runserver_command(context, basedir, settings_name, index, hostname):
    """
    Launch a simple HTTP server rooted on the project build directory

    Default behavior is to bind server on IP address '127.0.0.1' and port
    '80'. You may give another host to bind to as argument 'HOSTNAME'.

    'HOSTNAME' can be either a simple address like '0.0.0.0' or an address and
    port like '0.0.0.0:8001'. If no custom port is given, '80' is used as
    default.
    """
    logger = logging.getLogger("optimus")

    # Set project before to be able to load its modules
    setup_project(basedir, settings_name)

    # Load current project settings and page map
    settings = import_settings_module(settings_name, basedir=basedir)
    # In test environment, force the module reload to avoid previous test cache to be
    # used (since the module have the same path).
    if context.obj["test_env"]:
        settings = importlib.reload(settings)

    settings = load_settings(settings)

    # Debug output
    display_settings(
        settings,
        ("DEBUG", "PROJECT_DIR", "SOURCES_DIR", "TEMPLATES_DIR",
         "LOCALES_DIR"),
    )

    try:
        server_env = server_interface(settings, hostname, index=index)
    except ServerConfigurationError as e:
        logger.error(e)
        raise click.Abort()

    # Don't start cherrypy server during tests
    if not context.obj["test_env"]:
        server_env["cherrypy"].quickstart(
            None,
            server_env["mount_on"],
            config=server_env["app_conf"],
        )
Exemplo n.º 12
0
def test_basic(caplog):
    """
    Basic initialize without ressources to sync
    """
    conf = DummySettings()
    conf.STRING = 'ok'
    conf.INTEGER = 42
    conf.SEQ = [1, 'hello', 42]
    conf.MAP = {'hello': 'world'}
    conf.LOOSE = 'meh'

    display_settings(conf, ['STRING', 'INTEGER', 'SEQ', 'MAP', 'NOPE'])

    # Check base setting directories

    assert caplog.record_tuples == [
        (
            'optimus',
            10,
            " - Settings.STRING = ok"
        ),
        (
            'optimus',
            10,
            " - Settings.INTEGER = 42"
        ),
        (
            'optimus',
            10,
            " - Settings.SEQ = [1, 'hello', 42]"
        ),
        (
            'optimus',
            10,
            " - Settings.MAP = {'hello': 'world'}"
        ),
        (
            'optimus',
            10,
            " - Settings.NOPE = NOT SET"
        ),
    ]
Exemplo n.º 13
0
def test_basic(caplog):
    """
    Basic initialize without ressources to sync
    """
    conf = DummySettings()
    conf.STRING = "ok"
    conf.INTEGER = 42
    conf.SEQ = [1, "hello", 42]
    conf.MAP = {"hello": "world"}
    conf.LOOSE = "meh"

    display_settings(conf, ["STRING", "INTEGER", "SEQ", "MAP", "NOPE"])

    # Check base setting directories

    assert caplog.record_tuples == [
        ("optimus", 10, " - Settings.STRING = ok"),
        ("optimus", 10, " - Settings.INTEGER = 42"),
        ("optimus", 10, " - Settings.SEQ = [1, 'hello', 42]"),
        ("optimus", 10, " - Settings.MAP = {'hello': 'world'}"),
        ("optimus", 10, " - Settings.NOPE = NOT SET"),
    ]
Exemplo n.º 14
0
Arquivo: po.py Projeto: simbha/Optimus
def po(args, init=False, update=False, compile=False):
    """
    Manage catalog for all knowed languages
    """
    starttime = datetime.datetime.now()
    # Init, load and builds
    root_logger = init_logging(args.loglevel.upper(), logfile=args.logfile)
    
    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings, import_project_module
    from optimus.utils import display_settings
    
    display_settings(settings, ('DEBUG', 'PROJECT_DIR','SOURCES_DIR','TEMPLATES_DIR','LOCALES_DIR'))
    
    i18n = I18NManager(root_logger, settings)
    
    # TODO: * Copy the actual locale directory to a temporary directory
    #       * If process is success, remove previous backup dir if exists then promote the temp backup dir as the current backup
    #       * If process goes wrong, just remove the temp backup dir
    #       -> Always keeping only one backup dir and allways for a successful process
    if args.backup:
        pass
        
    # NOTE: Should we do this automatically to prevent error on missing files
    #       OR should we only do checking before and abort on the first missing file ?
    if args.init or args.update or args.compile:
        i18n.init_locales_dir()
        i18n.extract(force=args.update)
        i18n.init_catalogs()
    
    if args.update:
        i18n.update_catalogs()
    
    if args.compile:
        i18n.compile_catalogs()
    
    endtime = datetime.datetime.now()
    root_logger.info('Done in %s', str(endtime-starttime))
Exemplo n.º 15
0
def po_command(context, init, update, compile_opt, basedir, settings_name):
    """
    Manage project translation catalogs for all registred languages
    """
    # Set project before to be able to load its modules
    setup_project(basedir, settings_name)

    # Load current project settings and page map
    settings = import_settings_module(settings_name, basedir=basedir)
    # In test environment, force the module reload to avoid previous test cache to be
    # used (since the module have the same path).
    if context.obj["test_env"]:
        settings = importlib.reload(settings)

    settings = load_settings(settings)

    # Debug output
    display_settings(
        settings,
        ("DEBUG", "PROJECT_DIR", "SOURCES_DIR", "TEMPLATES_DIR",
         "LOCALES_DIR"),
    )

    po_interface(settings, init=init, update=update, compile_opt=compile_opt)
Exemplo n.º 16
0
def watch(args):
    """
    Launch the project watcher to automatically re-build knowed elements on changes
    """
    root_logger = init_logging(args.loglevel.upper(), printout=not(args.silent), logfile=args.logfile)
    
    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings, import_project_module
    from optimus.watchers import TemplatesWatchEventHandler, AssetsWatchEventHandler
    from optimus.builder.assets import register_assets
    from optimus.builder.pages import PageBuilder
    from optimus.utils import initialize, display_settings
    
    display_settings(settings, ('DEBUG', 'PROJECT_DIR','SOURCES_DIR','TEMPLATES_DIR','PUBLISH_DIR','STATIC_DIR','STATIC_URL'))
    
    if hasattr(settings, 'PAGES_MAP'):
        root_logger.info('Loading external pages map')
        pages_map = import_project_module(settings.PAGES_MAP)
        setattr(settings, 'PAGES', pages_map.PAGES)
    
    # Init environments
    assets_env = register_assets()
    pages_env = PageBuilder(assets_env=assets_env)
    
    # add a first build to avoid error on unbuilded project
    if not os.path.exists(settings.PUBLISH_DIR):
        root_logger.info('Seems you never do a first build so do it now')
        pages_env.build_bulk(settings.PAGES)
    
    pages_env.scan_bulk(settings.PAGES)
    
    observer = Observer()
    
    # Templates watcher settings
    watcher_templates_patterns = {
        'patterns': ['*.html'],
        'ignore_patterns': None,
        'ignore_directories': False,
        'case_sensitive': False,
    }
    watcher_templates_patterns.update(settings.WATCHER_TEMPLATES_PATTERNS)
    # Assets watcher settings
    watcher_assets_patterns = {
        'patterns': ['*.css', '*.js', '*.json'],
        'ignore_patterns': None,
        'ignore_directories': False,
        'case_sensitive': False,
    }
    watcher_assets_patterns.update(settings.WATCHER_ASSETS_PATTERNS)
    
    # Init templates and assets event watchers
    templates_event_handler = TemplatesWatchEventHandler(settings, root_logger, assets_env, pages_env, **watcher_templates_patterns)
    if assets_env is not None:
        assets_event_handler = AssetsWatchEventHandler(settings, root_logger, assets_env, pages_env, **watcher_assets_patterns)
    # Registering event watchers and start to watch
    observer.schedule(templates_event_handler, settings.TEMPLATES_DIR, recursive=True)
    if assets_env is not None:
        observer.schedule(assets_event_handler, settings.SOURCES_DIR, recursive=True)
        
    root_logger.warning('Launching the watcher, use CTRL+C to stop it')
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
Exemplo n.º 17
0
def watch_command(context, basedir, settings_name):
    """
    Watch for changes in project sources to automatically build project
    ressources
    """
    logger = logging.getLogger("optimus")

    # Set required environment variables to load settings
    if PROJECT_DIR_ENVVAR not in os.environ \
       or not os.environ[PROJECT_DIR_ENVVAR]:
        os.environ[PROJECT_DIR_ENVVAR] = basedir
    if SETTINGS_NAME_ENVVAR not in os.environ or \
       not os.environ[SETTINGS_NAME_ENVVAR]:
        os.environ[SETTINGS_NAME_ENVVAR] = settings_name

    # Load current project settings
    from optimus.conf.registry import settings

    # Debug output
    display_settings(settings, ('DEBUG', 'PROJECT_DIR', 'SOURCES_DIR',
                                'TEMPLATES_DIR', 'LOCALES_DIR'))

    initialize(settings)

    # Init webassets and builder
    assets_env = register_assets(settings)
    builder = PageBuilder(settings, assets_env=assets_env)
    pages_map = import_pages_module(settings.PAGES_MAP, basedir=basedir)

    # Proceed to page building from registered pages
    logger.debug('Trigger pages build to start')
    builder.build_bulk(pages_map.PAGES)

    builder.scan_bulk(pages_map.PAGES)

    observer = Observer()

    # Init templates and assets event watchers
    templates_event_handler = TemplatesWatchEventHandler(
        settings,
        builder,
        **settings.WATCHER_TEMPLATES_PATTERNS
    )

    if assets_env is not None:
        assets_event_handler = AssetsWatchEventHandler(
            settings,
            assets_env,
            builder,
            **settings.WATCHER_ASSETS_PATTERNS
        )

    # Registering event watchers and start to watch
    observer.schedule(
        templates_event_handler,
        settings.TEMPLATES_DIR,
        recursive=True
    )
    if assets_env is not None:
        observer.schedule(
            assets_event_handler,
            settings.SOURCES_DIR,
            recursive=True
        )

    logger.warning('Starting to watch sources, use CTRL+C to stop it')
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        logger.warning('Stopping watcher..')
        observer.stop()
    observer.join()
Exemplo n.º 18
0
def runserver_command(context, basedir, settings_name, index, hostname):
    """
    Launch a simple HTTP server rooted on the project build directory

    Default behavior is to bind server on IP address '127.0.0.1' and port
    '80'. You may give another host to bind to as argument 'HOSTNAME'.

    'HOSTNAME' can be either a simple address like '0.0.0.0' or an address and
    port like '0.0.0.0:8001'. If no custom port is given, '80' is used as
    default.
    """
    logger = logging.getLogger("optimus")

    if not CHERRYPY_AVAILABLE:
        logger.error(("Unable to import CherryPy, you need to install it "
                      "with 'pip install cherrypy'"))
        raise click.Abort()

    # Set required environment variables to load settings
    if PROJECT_DIR_ENVVAR not in os.environ \
       or not os.environ[PROJECT_DIR_ENVVAR]:
        os.environ[PROJECT_DIR_ENVVAR] = basedir
    if SETTINGS_NAME_ENVVAR not in os.environ \
       or not os.environ[SETTINGS_NAME_ENVVAR]:
        os.environ[SETTINGS_NAME_ENVVAR] = settings_name

    # Load current project settings
    from optimus.conf.registry import settings

    # Debug output
    display_settings(settings, ('DEBUG', 'PROJECT_DIR', 'SOURCES_DIR',
                                'TEMPLATES_DIR', 'LOCALES_DIR'))

    # Get hostname to bind to
    try:
        address, port = get_host_parts(hostname)
    except InvalidHostname as e:
        logger.error(e)
        raise click.Abort()

    # Check project publish directory exists
    if not os.path.exists(settings.PUBLISH_DIR):
        logger.error(("Publish directory does not exist yet, you need to "
                      "build it before"))
        raise click.Abort()

    # Run server with publish directory served with tools.staticdir
    logger.info(("Running HTTP server on "
                 "address {address} with port {port}").format(
                    address=address,
                    port=port,
               ))

    # Configure webapp server
    cherrypy.config.update({
        'server.socket_host': address,
        'server.socket_port': port,
        'engine.autoreload_on': False,
    })

    # Configure webapp static
    conf = {
        '/': {
            'tools.staticdir.index': index,
            'tools.staticdir.on': True,
            'tools.staticdir.dir': settings.PUBLISH_DIR,
        },
    }

    cherrypy.quickstart(None, '/', config=conf)
Exemplo n.º 19
0
def watch(args):
    """
    Launch the project watcher to automatically re-build knowed elements on changes
    """
    root_logger = init_logging(args.loglevel.upper(),
                               printout=not (args.silent),
                               logfile=args.logfile)

    # Only load optimus stuff after the settings module name has been retrieved
    os.environ['OPTIMUS_SETTINGS_MODULE'] = args.settings
    from optimus.conf import settings, import_pages_module
    from optimus.watchers import TemplatesWatchEventHandler, AssetsWatchEventHandler
    from optimus.builder.assets import register_assets
    from optimus.builder.pages import PageBuilder
    from optimus.utils import initialize, display_settings

    display_settings(settings,
                     ('DEBUG', 'PROJECT_DIR', 'SOURCES_DIR', 'TEMPLATES_DIR',
                      'PUBLISH_DIR', 'STATIC_DIR', 'STATIC_URL'))

    if hasattr(settings, 'PAGES_MAP'):
        root_logger.info('Loading external pages map')
        pages_map = import_pages_module(settings.PAGES_MAP)
        setattr(settings, 'PAGES', pages_map.PAGES)

    # Init environments
    assets_env = register_assets()
    pages_env = PageBuilder(assets_env=assets_env)

    # add a first build to avoid error on unbuilded project
    if not os.path.exists(settings.PUBLISH_DIR):
        root_logger.info('Seems you never do a first build so do it now')
        pages_env.build_bulk(settings.PAGES)

    pages_env.scan_bulk(settings.PAGES)

    observer = Observer()

    # Templates watcher settings
    watcher_templates_patterns = {
        'patterns': ['*.html'],
        'ignore_patterns': None,
        'ignore_directories': False,
        'case_sensitive': False,
    }
    watcher_templates_patterns.update(settings.WATCHER_TEMPLATES_PATTERNS)
    # Assets watcher settings
    watcher_assets_patterns = {
        'patterns': ['*.css', '*.js', '*.json'],
        'ignore_patterns': None,
        'ignore_directories': False,
        'case_sensitive': False,
    }
    watcher_assets_patterns.update(settings.WATCHER_ASSETS_PATTERNS)

    # Init templates and assets event watchers
    templates_event_handler = TemplatesWatchEventHandler(
        settings, root_logger, assets_env, pages_env,
        **watcher_templates_patterns)
    if assets_env is not None:
        assets_event_handler = AssetsWatchEventHandler(
            settings, root_logger, assets_env, pages_env,
            **watcher_assets_patterns)
    # Registering event watchers and start to watch
    observer.schedule(templates_event_handler,
                      settings.TEMPLATES_DIR,
                      recursive=True)
    if assets_env is not None:
        observer.schedule(assets_event_handler,
                          settings.SOURCES_DIR,
                          recursive=True)

    root_logger.warning('Launching the watcher, use CTRL+C to stop it')
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        root_logger.warning('Stopping watcher..')
        observer.stop()
    observer.join()