Пример #1
0
def run(parser, options, args):
    """launch an object

    In:
      - ``parser`` -- the ``optparse.OptParser`` object used to parse the configuration file
      - ``options`` -- options in the command lines
      - ``args`` -- arguments in the command lines

    The unique argument is the path of the object to launch. The path syntax is described
    into the module ``nagare.admin.reference``. For example, ``/tmp/counter.py:Counter``
    is the path to the class ``Counter`` of the module ``tmp.counter.py``

    """
    if len(args) != 2:
        parser.error('Bad number of arguments')

    if 'nagare_reloaded' not in os.environ:
        return reloader.restart_with_monitor()

    # With the ``serve-module`` command, the automatic reloader is always activated
    reloader.install(excluded_directories=(pkg_resources.get_default_cache(),))

    # Load the object
    if os.path.sep in args[0]:
        path = 'file ' + args[0]
    else:
        path = 'python ' + args[0]
    app = reference.load_object(path)[0]

    # Wrap it into a WSGIApp
    app = wsgi.create_WSGIApp(app)

    # Always use the standalone publisher (Python HTTP server)
    publishers = dict([(entry.name, entry) for entry in pkg_resources.iter_entry_points('nagare.publishers')])
    publisher = publishers['standalone'].load()()

    wsgi_pipe = debugged_app(app) if options.debug else app
    publisher.register_application(args[0], args[1], app, wsgi_pipe)
    app.set_config('', {'application': {'redirect_after_post': False, 'name': args[1], 'always_html': True}}, None)
    app.set_publisher(publisher)

    # Always use the standalone session manager (in memory sessions)
    sessions_managers = dict([(entry.name, entry) for entry in pkg_resources.iter_entry_points('nagare.sessions')])
    sessions_manager = sessions_managers['standalone'].load()()
    app.set_sessions_manager(sessions_manager)

    # Set the application logger level to DEBUG
    log.configure({'logger': {'level': 'DEBUG'}}, args[1])
    log.activate()
    log.set_logger('nagare.application.' + args[1])

    # The static contents of the framework are served by the standalone server
    publisher.register_static('nagare', lambda path, r=pkg_resources.Requirement.parse('nagare'): get_file_from_package(r, path))

    # Launch the object
    publisher.serve(None, dict(host=options.host, port=options.port), None)
Пример #2
0
def run(parser, options, args):
    """Launch one or more applications

    In:
      - ``parser`` -- the ``optparse.OptParser`` object used to parse the configuration file
      - ``options`` -- options in the command lines
      - ``args`` -- arguments in the command lines

    The arguments are a list of names of registered applications
    or paths to application configuration files.
    """
    # If no argument are given, display the list of the registered applications
    if not args:
        print 'Available applications:'

        # The applications are registered under the ``nagare.applications`` entry point
        applications = pkg_resources.iter_entry_points('nagare.applications')
        for name in sorted(application.name for application in applications):
            print ' -', name
        return

    # Read the (optional) publisher configuration file
    pconf = read_publisher_options(parser, options)
    if pconf['reloader']['activated']:
        if 'nagare_reloaded' not in os.environ:
            return reloader.restart_with_monitor()

        filenames = pconf['reloader'].get('files', [])
        if isinstance(filenames, basestring):
            filenames = [filenames]
        filenames = filter(os.path.isfile, filenames)
        if options.conf:
            filenames.append(options.conf)

        watcher = reloader.install(pconf['reloader']['interval'], filenames, (pkg_resources.get_default_cache(),))
    else:
        watcher = None

    # Load the publisher
    publishers = {entry.name: entry for entry in pkg_resources.iter_entry_points('nagare.publishers')}
    t = pconf['publisher']['type']
    publisher = publishers[t].load()()

    # If no port is given, set the port number according to the used publisher
    if pconf['publisher']['port'] == -1:
        pconf['publisher']['port'] = publisher.default_port

    configs = []

    # Merge all the ``[logging]`` section of all the applications
    for cfgfile in args:
        # Read the configuration file of the application
        conffile, app, project_name, aconf = util.read_application(cfgfile, parser.error)
        if conffile is None:
            parser.error('Configuration file not found for application "%s"' % cfgfile)
        configs.append((conffile, app, project_name, aconf))

        log.configure(aconf['logging'].dict(), aconf['application']['app'])

    # Configure the logging service
    log.activate()

    # Configure each application and register it to the publisher
    for cfgfile, app, project_name, aconf in configs:
        # log.set_logger('nagare.application.'+aconf['application']['name'])
        if watcher:
            watcher.watch_file(aconf.filename)

        app_url = aconf['application']['name']

        static_path = aconf['application']['static']
        if os.path.isdir(static_path):
            # Register the function to serve the static contents of the application
            static_url = publisher.register_static(
                app_url,
                lambda path, static_path=static_path: get_file_from_root(static_path, path)
            )
        else:
            static_path = static_url = None

        data_path = aconf['application']['data']
        if not os.path.isdir(data_path):
            data_path = None

        # Load the sessions manager factory
        sessions_managers = {entry.name: entry for entry in pkg_resources.iter_entry_points('nagare.sessions')}
        conf = pconf['sessions'].dict()
        conf.update(aconf['sessions'].dict())
        t = conf.pop('type')

        sessions_manager = sessions_managers[t].load()()
        sessions_manager.set_config(options.conf, conf, parser.error)

        app, metadatas = util.activate_WSGIApp(
            app,
            cfgfile, aconf, parser.error,
            project_name,
            static_path, static_url,
            data_path,
            publisher,
            sessions_manager
        )

        # Register the application to the publisher
        publisher.register_application(
            aconf['application']['app'],
            app_url,
            app,
            create_wsgi_pipe(app, options, cfgfile, aconf, parser.error)
        )

    # Register the function to serve the static contents of the framework
    nagare = pkg_resources.Requirement.parse('nagare')
    nagare_location = pkg_resources.resource_filename(nagare, 'nagare')
    publisher.register_static(
        'nagare',
        lambda path, root=os.path.join(nagare_location, 'static'): get_file_from_root(root, path)
    )

    # Launch all the applications
    publisher.serve(options.conf, pconf['publisher'], parser.error)
Пример #3
0
def run(parser, options, args):
    """Launch one or more applications

    In:
      - ``parser`` -- the ``optparse.OptParser`` object used to parse the configuration file
      - ``options`` -- options in the command lines
      - ``args`` -- arguments in the command lines

    The arguments are a list of names of registered applications
    or paths to application configuration files.
    """
    # If no argument are given, display the list of the registered applications
    if len(args) == 0:
        print 'Available applications:'

        # The applications are registered under the ``nagare.applications`` entry point
        applications = pkg_resources.iter_entry_points('nagare.applications')
        for name in sorted([application.name for application in applications]):
            print ' -', name
        return

    # Read the (optional) publisher configuration file
    pconf = read_publisher_options(parser, options)
    if pconf['reloader']['activated']:
        if 'nagare_reloaded' not in os.environ:
            return reloader.restart_with_monitor()

        filenames = pconf['reloader'].get('files', [])
        if isinstance(filenames, basestring):
            filenames = [filenames]
        filenames = filter(os.path.isfile, filenames)
        if options.conf:
            filenames.append(options.conf)

        watcher = reloader.install(pconf['reloader']['interval'], filenames, (pkg_resources.get_default_cache(),))
    else:
        watcher = None

    # Load the publisher
    publishers = dict([(entry.name, entry) for entry in pkg_resources.iter_entry_points('nagare.publishers')])
    t = pconf['publisher']['type']
    publisher = publishers[t].load()()

    # If no port is given, set the port number according to the used publisher
    if pconf['publisher']['port'] == -1:
        pconf['publisher']['port'] = publisher.default_port

    configs = []

    # Merge all the ``[logging]`` section of all the applications
    for cfgfile in args:
        # Read the configuration file of the application
        (cfgfile, app, dist, aconf) = util.read_application(cfgfile, parser.error)
        configs.append((cfgfile, app, dist, aconf))

        log.configure(aconf['logging'].dict(), aconf['application']['name'])

    # Configure the logging service
    log.activate()

    # Configure each application and register it to the publisher
    for (cfgfile, app, dist, aconf) in configs:
        #log.set_logger('nagare.application.'+aconf['application']['name'])

        if watcher:
            watcher.watch_file(aconf.filename)

        requirement = None if not dist else pkg_resources.Requirement.parse(dist.project_name)

        data_path = None if not requirement else pkg_resources.resource_filename(requirement, '/data')

        # Create the function to get the static contents of the application
        static_path = aconf['application'].get('static')
        get_file = None
        if static_path is not None and os.path.isdir(static_path):
            # If a ``static`` parameter exists, under the ``[application]`` section,
            # serve the static contents from this root
            get_file = lambda path, static_path=static_path: get_file_from_root(static_path, path)
        else:
            # Else, serve the static from the ``static`` directory
            # of the application package
            if requirement:
                get_file = lambda path, requirement=requirement: get_file_from_package(requirement, path)
                static_path = pkg_resources.resource_filename(requirement, '/static')

        # Register the function to serve the static contents of the application
        static_url = publisher.register_static(aconf['application']['name'], get_file)

        # Load the sessions manager factory
        sessions_managers = dict([(entry.name, entry) for entry in pkg_resources.iter_entry_points('nagare.sessions')])
        conf = pconf['sessions'].dict()
        conf.update(aconf['sessions'].dict())
        t = conf.pop('type')

        sessions_manager = sessions_managers[t].load()()
        sessions_manager.set_config(options.conf, conf, parser.error)

        (app, metadatas) = util.activate_WSGIApp(
                                                    app,
                                                    cfgfile, aconf, parser.error,
                                                    '' if not dist else dist.project_name,
                                                    static_path, static_url,
                                                    data_path,
                                                    publisher,
                                                    sessions_manager
                                                )

        # Register the application to the publisher
        publisher.register_application(
                                       aconf['application']['path'],
                                       aconf['application']['name'],
                                       app,
                                       create_wsgi_pipe(app, options, cfgfile, aconf, parser.error)
                                      )

    # Register the function to serve the static contents of the framework
    publisher.register_static(
                                'nagare',
                                lambda path, r=pkg_resources.Requirement.parse('nagare'): get_file_from_package(r, path)
                             )

    # Launch all the applications
    publisher.serve(options.conf, pconf['publisher'], parser.error)