Exemplo n.º 1
0
    def __init__(self, import_name, app=None, db=None, *args, **kwargs):
        """ Create an new flask-json-resource API.
        """
        self.resources = []
        self.blueprint = Blueprint('json_resource', import_name)

        resources.Schema.register_schema_dir(
            os.path.join(self.blueprint.root_path, 'schemas'))

        prefix, package_path = find_package(import_name)

        if prefix is None:
            global_schemas_dir = os.path.join(package_path, 'schemas')
        else:
            global_schemas_dir = os.path.join(prefix, 'var/schemas')

        resources.Schema.register_schema_dir(global_schemas_dir)

        self.register()(resources.Schema)

        class Resource(FlaskResourceMixin, json_resource.Resource):
            default_views = (views.ResourceView, views.ResourceCreateView)

        class Collection(FlaskResourceMixin, json_resource.Collection):
            default_views = (views.CollectionView, )

        self.Resource = Resource
        self.Collection = Collection

        if app:
            self.init_app(app, db)
Exemplo n.º 2
0
def get_path(path='', internal=False):
    if os.path.isabs(path):
        return path

    prefix, package_path = find_package(__name__)
    if prefix is not None and not internal:
        return os.path.join(prefix, path)
    elif package_path is not None:
        return os.path.join(package_path, path)
    raise ValueError
Exemplo n.º 3
0
def get_path(path='', internal=False):
    if os.path.isabs(path):
        return path

    prefix, package_path = find_package(__name__)
    if prefix is not None and not internal:
        return os.path.join(prefix, path)
    elif package_path is not None:
        return os.path.join(package_path, path)
    raise ValueError
Exemplo n.º 4
0
def init(enable_geoip=True):
    global geoip
    prefix, package_path = find_package(__name__)
    config_locations = []
    if prefix is not None:
        config_locations.append(os.path.join(prefix, 'local', 'etc', 'rfk-config.cfg'))
        config_locations.append(os.path.join(prefix, 'etc', 'rfk-config.cfg'))
        config_locations.append(os.path.join(prefix, 'rfk-config.cfg'))
    if package_path is not None:
        config_locations.append(os.path.join(package_path, 'rfk', 'rfk-config.cfg'))
    succ_read = CONFIG.read(config_locations)
    if len(succ_read) == 0:
        raise NoConfigException()

    if enable_geoip:
        geoip = geoip2.database.Reader(CONFIG.get('site', 'geoipdb'))
Exemplo n.º 5
0
def create_app(configfile_override=None, logfile=None):

    # Rely on ROS to find this package

    # TODO : put that at a lower level (pyros_setup / pyros_utils / pyros_config ?)
    prefix, package_path = helpers.find_package(
        __package__)  # find ROS pkg with same name as this python package
    if prefix is None:  # not a python installed package (following flask detection logic)
        # we are probably installed with ROS
        try:
            import rospkg
            r = rospkg.RosPack()
            try:
                ros_path = r.get_path(
                    __package__
                )  # find rospkg with same name as this python package
                if ros_path.endswith(os.path.join(
                        'share', __package__)):  # ROS installed package
                    instance_path = os.path.join(
                        os.environ.get(
                            'ROS_HOME', os.path.join(os.environ['HOME'],
                                                     '.ros')),
                        'rostful')  # using ROS_HOME/rostful as instance path
                    # instance_path = ros_path  # using the ROS share path for configuration  # BAD IDEA : might not be writeable
                else:
                    package_path = ros_path  # fixing detected package_path in ROS devel case (to access config template file)
                    instance_path = os.path.join(
                        ros_path,
                        'instance')  # getting instance folder from source

            except rospkg.ResourceNotFound:  # the package was not found by rospack
                # lets rely on flask detection : this is a develop package
                instance_path = os.path.join(package_path, 'instance')

        except ImportError:  # ROS is not setup
            # lets rely on flask detection : this is a develop package
            instance_path = os.path.join(package_path, 'instance')
    else:
        # python installed package -> use rostful-instance from prefix/
        instance_path = os.path.join(prefix, 'var', __package__ + '-instance')

    app = Flask(__package__,
                static_folder=os.path.join(
                    os.path.dirname(os.path.abspath(__file__)), 'static'),
                template_folder=os.path.join(
                    os.path.dirname(os.path.abspath(__file__)), 'templates'),
                instance_path=instance_path,
                instance_relative_config=True)
    # TODO : When running from ros in devel mode, instance path in inside devel/lib/python2.7/dist-packages/
    # TODO : because ROS import our package from there => FIX IT !
    # Note : we do need instance relative config to be able to run from installed package...

    ### LOGGER SETUP ###

    # default log should show us all infos
    app.logger.setLevel(logging.DEBUG)

    # Setup logfile early
    if not logfile:
        logfile = os.path.join(app.instance_path, 'rostful.log')

    # adding file logging for everything to help debugging
    logdir = os.path.dirname(logfile)
    if not os.path.exists(logdir):
        try:
            os.makedirs(logdir)
        except OSError as exception:  # preventing race condition just in case
            if exception.errno != errno.EEXIST:
                raise

    # Adding a debug file logger
    file_handler = logging.handlers.RotatingFileHandler(logfile,
                                                        maxBytes=100 * 131072,
                                                        backupCount=10)
    file_handler.setLevel(logging.DEBUG)

    # create a formatter to have useful extra fields
    formatter = logging.Formatter(
        '[%(levelname)s] [%(asctime)s] [%(name)s] : %(message)s', )
    file_handler.setFormatter(formatter)

    app.logger.addHandler(file_handler)

    ### CONFIG SETUP ###

    # Config Workflow
    # 1. load hardcoded (in source) defaults, minimum expected to not break / crash.
    # 2. load config from default location (overriding hardcoded defaults).
    #    if not there, create it (at runtime, with the hardcoded default values)
    # 3. load user provided config from command arg if any, if missing file then except (user provided arg is wrong).
    #    if intent is to use file from default location, then no config arg should be provided.

    if not configfile_override:
        try:

            # Attempting to set up default user configuration
            config_filepath = os.path.join(app.instance_path, 'rostful.cfg')
            app.logger.info("Loading config from {0}".format(
                os.path.join(app.instance_path, 'rostful.cfg')))

            app.config.from_pyfile(config_filepath)

        except IOError as e:
            # If failed we create it from current default in package
            app.logger.warning(
                "Cannot find rostful.cfg file to setup rostful. Creating it from default template..."
            )

            cfg_template_path = os.path.join(package_path, __package__,
                                             'config_template.py')

            with app.open_resource(cfg_template_path, 'r') as default_cfg_file:
                # Create instance config file name, to make it easy to modify when deploying
                filename = config_filepath
                if not os.path.isfile(filename):
                    # this will create the directories if needed
                    try:
                        os.makedirs(os.path.dirname(filename))
                    except OSError as exception:  # preventing race condition just in case
                        if exception.errno != errno.EEXIST:
                            raise
                with open(config_filepath, 'w') as instance_cfg_file:
                    for line in default_cfg_file:
                        instance_cfg_file.write(line)

            app.logger.warning(
                "Configuration file created at {0}".format(config_filepath))

    else:
        config_filepath = configfile_override
        app.config.from_pyfile(config_filepath)

    # config can influence routes, so this needs to be done afterwards
    setup_app_routes(app)

    return app
Exemplo n.º 6
0
def create_app(configfile_override=None, logfile=None):

    # Rely on ROS to find this package

    # TODO : put that at a lower level (pyros_setup / pyros_utils / pyros_config ?)
    prefix, package_path = helpers.find_package(__package__)  # find ROS pkg with same name as this python package
    if prefix is None:  # not a python installed package (following flask detection logic)
        # we are probably installed with ROS
        try:
            import rospkg
            r = rospkg.RosPack()
            try:
                ros_path = r.get_path(__package__)  # find rospkg with same name as this python package
                if ros_path.endswith(os.path.join('share', __package__)):  # ROS installed package
                    instance_path = os.path.join(os.environ.get('ROS_HOME', os.path.join(os.environ['HOME'], '.ros')), 'rostful')  # using ROS_HOME/rostful as instance path
                    # instance_path = ros_path  # using the ROS share path for configuration  # BAD IDEA : might not be writeable
                else:
                    package_path = ros_path  # fixing detected package_path in ROS devel case (to access config template file)
                    instance_path = os.path.join(ros_path, 'instance')  # getting instance folder from source

            except rospkg.ResourceNotFound:  # the package was not found by rospack
                # lets rely on flask detection : this is a develop package
                instance_path = os.path.join(package_path, 'instance')

        except ImportError:  # ROS is not setup
            # lets rely on flask detection : this is a develop package
            instance_path = os.path.join(package_path, 'instance')
    else:
        # python installed package -> use rostful-instance from prefix/
        instance_path = os.path.join(prefix, 'var', __package__ + '-instance')

    app = Flask(
        __package__,
        static_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static'),
        template_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates'),
        instance_path=instance_path,
        instance_relative_config=True
    )
    # TODO : When running from ros in devel mode, instance path in inside devel/lib/python2.7/dist-packages/
    # TODO : because ROS import our package from there => FIX IT !
    # Note : we do need instance relative config to be able to run from installed package...

    ### LOGGER SETUP ###

    # default log should show us all infos
    app.logger.setLevel(logging.DEBUG)

    # Setup logfile early
    if not logfile:
        logfile = os.path.join(app.instance_path, 'rostful.log')

    # adding file logging for everything to help debugging
    logdir = os.path.dirname(logfile)
    if not os.path.exists(logdir):
        try:
            os.makedirs(logdir)
        except OSError as exception:  # preventing race condition just in case
            if exception.errno != errno.EEXIST:
                raise

    # Adding a debug file logger
    file_handler = logging.handlers.RotatingFileHandler(
        logfile,
        maxBytes=100 * 131072,
        backupCount=10)
    file_handler.setLevel(logging.DEBUG)

    # create a formatter to have useful extra fields
    formatter = logging.Formatter('[%(levelname)s] [%(asctime)s] [%(name)s] : %(message)s', )
    file_handler.setFormatter(formatter)

    app.logger.addHandler(file_handler)

    ### CONFIG SETUP ###

    # Config Workflow
    # 1. load hardcoded (in source) defaults, minimum expected to not break / crash.
    # 2. load config from default location (overriding hardcoded defaults).
    #    if not there, create it (at runtime, with the hardcoded default values)
    # 3. load user provided config from command arg if any, if missing file then except (user provided arg is wrong).
    #    if intent is to use file from default location, then no config arg should be provided.

    if not configfile_override:
        try:

            # Attempting to set up default user configuration
            config_filepath = os.path.join(app.instance_path, 'rostful.cfg')
            app.logger.info(
                "Loading config from {0}".format(os.path.join(app.instance_path, 'rostful.cfg')))

            app.config.from_pyfile(config_filepath)

        except IOError as e:
            # If failed we create it from current default in package
            app.logger.warning("Cannot find rostful.cfg file to setup rostful. Creating it from default template...")

            cfg_template_path = os.path.join(package_path, __package__, 'config_template.py')

            with app.open_resource(cfg_template_path, 'r') as default_cfg_file:
                # Create instance config file name, to make it easy to modify when deploying
                filename = config_filepath
                if not os.path.isfile(filename):
                    # this will create the directories if needed
                    try:
                        os.makedirs(os.path.dirname(filename))
                    except OSError as exception:  # preventing race condition just in case
                        if exception.errno != errno.EEXIST:
                            raise
                with open(config_filepath, 'w') as instance_cfg_file:
                    for line in default_cfg_file:
                        instance_cfg_file.write(line)

            app.logger.warning("Configuration file created at {0}".format(config_filepath))

    else:
        config_filepath = configfile_override
        app.config.from_pyfile(config_filepath)

    # config can influence routes, so this needs to be done afterwards
    setup_app_routes(app)

    return app