Example #1
0
def create_app(config: dict = {}, mail_client=None):
    app = Flask(__name__, static_folder='static')

    if config:
        app.config.update(config)
    else:
        app.config.from_envvar('ALSERVICE_CONFIG')

    MakoTemplates(app)
    app._mako_lookup = TemplateLookup(directories=[pkg_resources.resource_filename('alservice.service', 'templates')],
                                      input_encoding='utf-8', output_encoding='utf-8',
                                      imports=['from flask_babel import gettext as _'])

    app.al = init_account_linking(app, mail_client)

    babel = Babel(app)
    babel.localeselector(get_locale)
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = pkg_resources.resource_filename('alservice.service',
                                                                                  'data/i18n/locales')

    from .views import account_linking_views
    app.register_blueprint(account_linking_views)

    setup_logging(app.config.get('LOGGING_LEVEL', 'INFO'))

    logger = logging.getLogger(__name__)
    logger.info('Running ALservice version %s', pkg_resources.get_distribution('ALservice').version)

    return app
Example #2
0
def init_app(app, **kwargs):
    """Initialize the Flask app located in the module sipa.
    This initializes the Flask app by:
    * calling the internal init_app() procedures of each module
    * registering the Blueprints
    * registering the Jinja global variables
    :return: None
    """
    load_config_file(app, config=kwargs.pop('config', None))
    app.wsgi_app = ProxyFix(app.wsgi_app, app.config['NUM_PROXIES'])
    init_logging(app)
    init_env_and_config(app)
    logger.debug('Initializing app')
    login_manager.init_app(app)
    babel = Babel()
    babel.init_app(app)
    babel.localeselector(select_locale)
    app.before_request(save_user_locale_setting)
    app.session_interface = SeparateLocaleCookieSessionInterface()
    cf_pages = CategorizedFlatPages()
    cf_pages.init_app(app)
    backends = build_backends_ext()
    backends.init_app(app)
    QRcode(app)

    app.url_map.converters['int'] = IntegerConverter

    from sipa.blueprints import bp_features, bp_usersuite, \
        bp_pages, bp_documents, bp_news, bp_generic, bp_hooks

    logger.debug('Registering blueprints')
    app.register_blueprint(bp_generic)
    app.register_blueprint(bp_features)
    app.register_blueprint(bp_usersuite)
    app.register_blueprint(bp_pages)
    app.register_blueprint(bp_documents)
    app.register_blueprint(bp_news)
    app.register_blueprint(bp_hooks)

    logger.debug('Registering Jinja globals')
    form_label_width = 3
    form_input_width = 7
    app.jinja_env.globals.update(
        cf_pages=cf_pages,
        get_locale=get_locale,
        get_weekday=get_weekday,
        possible_locales=possible_locales,
        get_attribute_endpoint=get_attribute_endpoint,
        should_display_traffic_data=should_display_traffic_data,
        traffic_chart=provide_render_function(generate_traffic_chart),
        current_datasource=backends.current_datasource,
        form_label_width_class="col-sm-{}".format(form_label_width),
        form_input_width_class="col-sm-{}".format(form_input_width),
        form_input_offset_class="col-sm-offset-{}".format(form_label_width),
        url_self=url_self,
    )
    logger.debug("Jinja globals have been set",
                 extra={'data': {'jinja_globals': app.jinja_env.globals}})

    backends.init_backends()
Example #3
0
def create_app(config: dict = None):
    app = Flask(__name__, static_url_path='', instance_relative_config=True)

    if config:
        app.config.update(config)
    else:
        app.config.from_envvar("CMSERVICE_CONFIG")

    mako = MakoTemplates()
    mako.init_app(app)
    app._mako_lookup = TemplateLookup(directories=[pkg_resources.resource_filename('cmservice.service', 'templates')],
                                      input_encoding='utf-8', output_encoding='utf-8',
                                      imports=['from flask_babel import gettext as _'])

    app.cm = init_consent_manager(app)

    babel = Babel(app)
    babel.localeselector(get_locale)
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = pkg_resources.resource_filename('cmservice.service',
                                                                                  'data/i18n/locales')

    from .views import consent_views
    app.register_blueprint(consent_views)

    setup_logging(app.config.get('LOGGING_LEVEL', 'INFO'))

    logger = logging.getLogger(__name__)
    logger.info("Running CMservice version %s", pkg_resources.get_distribution("CMservice").version)
    return app
Example #4
0
def create_app(config=None):
    app = Flask(__name__.split('.')[0])
    app_config = {  # Defaults
        'GALLERY_ROOT': os.path.abspath(os.path.join(
            os.path.dirname(__file__), '..', 'gallery'
        )),
        'REDIS_URL': 'redis://localhost:6379/0',
    }

    if config is not None:
        app_config.update({key.upper(): value
                           for key, value in config.items()})
        if 'DEBUG' in app_config:
            if app_config['DEBUG'] in ('0', 'n', 'no', 'False', 'false'):
                app_config.update({'DEBUG': False})
            else:
                app_config.update({'DEBUG': True})

    app.config.update(app_config)

    app.add_url_rule('/galleries/<path:path>', view_func=send_pic, methods=['GET'])

    babel = Babel(app)
    babel.localeselector(get_locale)
    app.jinja_env.filters['date'] = format_date
    app.jinja_env.filters['datetime'] = format_datetime

    GalleryView.register(app)
    return app
Example #5
0
def setup_app(config, app):
    global LOCALES
    global babel

    translation_dirs = getattr(config, 'TRANSLATION_DIRS', None)

    if translation_dirs is None:
            translation_dirs = \
                    path.join(path.dirname(path.realpath(__file__)),
                              'translations')

    # `babel.translation_directories` is a nightmare
    # We need to set this manually via an absolute path
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = translation_dirs

    babel = Babel(app)
    if len(list(babel.translation_directories)) != 1:
        raise AssertionError(
            'Expected exactly one translation directory but got {}.'
            .format(babel.translation_directories))

    translation_directories = next(babel.translation_directories)
    for dirname in os.listdir(translation_directories):
        if dirname != 'messages.pot':
            LOCALES.append(dirname)

    LOCALES = _get_supported_locales(
        LOCALES,
        getattr(config, 'SUPPORTED_LOCALES', None),
        getattr(config, 'DEFAULT_LOCALE', None),
        translation_directories)

    babel.localeselector(lambda: get_locale(config))
Example #6
0
def app():
    app = Flask(__name__)
    babel = Babel(app, default_locale="fr", default_timezone=USER_TZ)
    babel.localeselector(en_locale)
    babel.timezoneselector(user_tz)
    with app.app_context():
        yield app
Example #7
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    from docassemble.base.config import daconfig
    import docassemble.webapp.database
    import docassemble.webapp.db_object
    connect_string = docassemble.webapp.database.connection_string()
    alchemy_connect_string = docassemble.webapp.database.alchemy_connection_string()
    app.config['SQLALCHEMY_DATABASE_URI'] = alchemy_connect_string
    app.secret_key = daconfig.get('secretkey', '38ihfiFehfoU34mcq_4clirglw3g4o87')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db = docassemble.webapp.db_object.init_flask()
    db.init_app(app)
    csrf = CSRFProtect()
    csrf.init_app(app)
    babel = Babel()
    babel.init_app(app)
    if daconfig.get('behind https load balancer', False):
        if proxyfix_version >= 15:
            app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
        else:
            app.wsgi_app = ProxyFix(app.wsgi_app)
    return app, csrf, babel
Example #8
0
class TCC3Babel(object):
    DEFAULT_LOCALE = 'zh_Hans_CN'

    def __init__(self, app=None):
        self._locale = TCC3Babel.DEFAULT_LOCALE
        self.babel = Babel()
        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        """:type app : Flask"""

        self.babel.init_app(app)
        self.babel.localeselector(TCC3Babel.get_locale)

    def set_locale(self, locale=DEFAULT_LOCALE):
        self._locale = locale
        # TODO

    @classmethod
    def get_locale(cls):
        locale = request.accept_languages.best_match(LANGUAGES.keys())
        print('locale: ', locale)
        return locale
Example #9
0
 def __init__(self, import_name, conf={}):
     defaults = {
         'BOOTSTRAP_SERVE_LOCAL': True,
         'AGHERANT_DESCRIPTIONS': [],
         'API_URL': '/api/v1',
         'RESULTS_PER_PAGE': 30,
         'MAX_RESULTS_PER_PAGE': 100
     }
     defaults.update(conf)
     super(LibreantViewApp, self).__init__(import_name, defaults)
     if self.config['AGHERANT_DESCRIPTIONS']:
         self.register_blueprint(agherant, url_prefix='/agherant')
     api = get_blueprint_api(users_routes=self.users_enabled)
     self.register_blueprint(api, url_prefix=self.config['API_URL'])
     Bootstrap(self)
     self.babel = Babel(self)
     self.available_translations = [l.language for l in self.babel.list_translations()]
     if self.users_enabled:
         self.autht = auth.AuthtFromSessionAnon()
         self.authz = auth.AuthzFromSession(authenticator=self.autht)
     else:
         self.autht = auth.TransparentAutht()
         self.authz = auth.TransparentAuthz()
Example #10
0
created 9-dec-2019 by [email protected]
"""
import connexion
from flask import g
from flask_babel import Babel
import os

from apicrud import ServiceConfig, initialize

import controllers
from messaging import send_contact
import models

application = connexion.FlaskApp(__name__)
babel = Babel(application.app)


@application.app.before_request
def before_request():
    initialize.before_request()


@application.app.after_request
def add_header(response):
    return initialize.after_request(response)


@application.app.teardown_appcontext
def cleanup(resp_or_exc):
    """When a flask thread terminates, close the database session"""
Example #11
0
 def create_app(self):
   app = Flask(__name__)
   babel = Babel(app, default_locale='fr', default_timezone=USER_TZ)
   babel.localeselector(en_locale)
   babel.timezoneselector(user_tz)
   return app
Example #12
0
from flask_babel import lazy_gettext as _l
from elasticsearch import Elasticsearch
from config import Config
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from redis import Redis
import rq

db = SQLAlchemy()
migrate = Migrate()
login = LoginManager()
mail = Mail()
bootstrap = Bootstrap()
moment = Moment()
babel = Babel()

login.login_view = 'auth.login'  # para proteger páginas de los no logeados
login.login_message = _l('Please log in to access this page')


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
Example #13
0
def create_app(main_module: bool = False):
    app = Flask(__name__, static_url_path='/static', static_folder='static')
    
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = os.path.abspath(
        'limonero/i18n/locales')
    app.json_encoder = LimoneroJSONEncoder
    
    babel = Babel(app)
    
    logging.config.fileConfig('logging_config.ini')
    
    app.secret_key = 'l3m0n4d1'
    
    
    # Cryptography key
    app.download_key = Fernet.generate_key()
    app.fernet = Fernet(app.download_key)
    
    
    # Cache
    cache.init_app(app)
    
    # CORS
    CORS(app, resources={r"/*": {"origins": "*"}})
    api = Api(app)
    
    # Swagger
    swaggerui_blueprint = get_swaggerui_blueprint(
        '/api/docs',  
        '/static/swagger.yaml',
        config={  # Swagger UI config overrides
            'app_name': "Lemonade Caipirinha"
        },
        # oauth_config={  # OAuth config. See https://github.com/swagger-api/swagger-ui#oauth2-configuration .
        #    'clientId': "your-client-id",
        #    'clientSecret': "your-client-secret-if-required",
        #    'realm': "your-realms",
        #    'appName': "your-app-name",
        #    'scopeSeparator': " ",
        #    'additionalQueryStringParams': {'test': "hello"}
        # }
    )
    
    app.register_blueprint(swaggerui_blueprint)
    
    mappings = {
        '/datasources': DataSourceListApi,
        '/datasources/upload': DataSourceUploadApi,
        '/datasources/infer-schema/<int:data_source_id>': DataSourceInferSchemaApi,
        '/datasources/sample/<int:data_source_id>': DataSourceSampleApi,
        '/datasources/initialize/<status>/<int:data_source_id>': 
            DataSourceInitializationApi,
        '/datasources/<int:data_source_id>': DataSourceDetailApi,
        '/datasources/<int:data_source_id>/permission/<int:user_id>':
            DataSourcePermissionApi,
        '/datasources/<int:data_source_id>/privacy': DataSourcePrivacyApi,
        '/privacy': GlobalPrivacyListApi,
        '/privacy/attribute-groups': AttributePrivacyGroupListApi,
        '/models': ModelListApi,
        '/models/<int:model_id>': ModelDetailApi,
    
        '/storages': StorageListApi,
        '/storages/<int:storage_id>': StorageDetailApi,
        '/storages/metadata/<int:storage_id>': StorageMetadataApi,
    }
    grouped_mappings = itertools.groupby(sorted(mappings.items()),
                                         key=lambda path: path[1])
    for view, g in grouped_mappings:
        api.add_resource(view, *[x[0] for x in g], endpoint=view.__name__)
    
    app.add_url_rule('/datasources/public/<int:data_source_id>/download',
                     methods=['GET'], endpoint='DataSourceDownload',
                     view_func=DataSourceDownload.as_view('download'))

    app.add_url_rule('/models/<int:model_id>/download',
                     methods=['GET'], endpoint='ModelDownloadApi',
                     view_func=ModelDownloadApi.as_view('download_model'))
    migrate = Migrate(app, db)
    app.handle_exception

    @babel.localeselector
    def get_locale():
        user = getattr(flask_g, 'user', None)
        if user is not None and user.locale:
            return user.locale
        else:
            return request.args.get(
                'lang', request.accept_languages.best_match(['en', 'pt', 'es']))
    
    sqlalchemy_utils.i18n.get_locale = get_locale

    config_file = None
    signal.signal(signal.SIGINT, exit_gracefully)
    if main_module:
        parser = argparse.ArgumentParser()
        parser.add_argument("-c", "--config", type=str,
                            help="Config file", required=False)
        args = parser.parse_args()
        config_file = args.config

    if config_file is None:
        config_file = os.environ.get('LIMONERO_CONFIG')

    logger = logging.getLogger(__name__)
    if config_file:
        with open(config_file) as f:
            config = yaml.load(f, Loader=yaml.FullLoader)['limonero']

        app.config['LIMONERO_CONFIG'] = config
        app.config["RESTFUL_JSON"] = {"cls": app.json_encoder}

        server_config = config.get('servers', {})
        app.config['SQLALCHEMY_DATABASE_URI'] = server_config.get(
            'database_url')
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

        is_mysql = 'mysql://' in app.config['SQLALCHEMY_DATABASE_URI']
        if config.get('config') is not None and 'config' in config and is_mysql:
            app.config.update(config.get('config', {}))
            app.config['SQLALCHEMY_POOL_SIZE'] = 10
            app.config['SQLALCHEMY_POOL_RECYCLE'] = 240

        db.init_app(app)

        port = int(config.get('port', 5000))
        logger.debug(
            gettext('Running in %(mode)s mode', mode=config.get('environment')))

        init_jvm(app, logger)
        if main_module:
            # JVM, used to interact with HDFS.
            if config.get('environment', 'dev') == 'dev':
                app.run(debug=True, port=port, host='0.0.0.0')
            else:
                eventlet.wsgi.server(eventlet.listen(('', port)), app)
        else:
            return app    
    else:
        logger.error(
            gettext('Please, set LIMONERO_CONFIG environment variable'))
        exit(1)
    return app
Example #14
0
def create_app(config_name="development",
               config_file='/etc/privacyidea/pi.cfg',
               silent=False):
    """
    First the configuration from the config.py is loaded depending on the
    config type like "production" or "development" or "testing".

    Then the environment variable PRIVACYIDEA_CONFIGFILE is checked for a
    config file, that contains additional settings, that will overwrite the
    default settings from config.py

    :param config_name: The config name like "production" or "testing"
    :type config_name: basestring
    :param config_file: The name of a config file to read configuration from
    :type config_file: basestring
    :param silent: If set to True the additional information are not printed
        to stdout
    :type silent: bool
    :return: The flask application
    :rtype: App object
    """
    if not silent:
        print("The configuration name is: {0!s}".format(config_name))
    if os.environ.get(ENV_KEY):
        config_file = os.environ[ENV_KEY]
    if not silent:
        print(
            "Additional configuration can be read from the file {0!s}".format(
                config_file))
    app = Flask(__name__,
                static_folder="static",
                template_folder="static/templates")
    if config_name:
        app.config.from_object(config[config_name])

    try:
        # Try to load the given config_file.
        # If it does not exist, just ignore it.
        app.config.from_pyfile(config_file, silent=True)
    except IOError:
        sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")
        sys.stderr.write("  WARNING: privacyidea create_app has no access\n")
        sys.stderr.write("  to {0!s}!\n".format(config_file))
        sys.stderr.write("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n")

    # Try to load the file, that was specified in the environment variable
    # PRIVACYIDEA_CONFIG_FILE
    # If this file does not exist, we create an error!
    app.config.from_envvar(ENV_KEY, silent=True)

    app.register_blueprint(validate_blueprint, url_prefix='/validate')
    app.register_blueprint(token_blueprint, url_prefix='/token')
    app.register_blueprint(system_blueprint, url_prefix='/system')
    app.register_blueprint(resolver_blueprint, url_prefix='/resolver')
    app.register_blueprint(realm_blueprint, url_prefix='/realm')
    app.register_blueprint(defaultrealm_blueprint, url_prefix='/defaultrealm')
    app.register_blueprint(policy_blueprint, url_prefix='/policy')
    app.register_blueprint(login_blueprint, url_prefix='/')
    app.register_blueprint(jwtauth, url_prefix='/auth')
    app.register_blueprint(user_blueprint, url_prefix='/user')
    app.register_blueprint(audit_blueprint, url_prefix='/audit')
    app.register_blueprint(machineresolver_blueprint,
                           url_prefix='/machineresolver')
    app.register_blueprint(machine_blueprint, url_prefix='/machine')
    app.register_blueprint(application_blueprint, url_prefix='/application')
    app.register_blueprint(caconnector_blueprint, url_prefix='/caconnector')
    app.register_blueprint(cert_blueprint, url_prefix='/certificate')
    app.register_blueprint(ttype_blueprint, url_prefix='/ttype')
    app.register_blueprint(register_blueprint, url_prefix='/register')
    app.register_blueprint(smtpserver_blueprint, url_prefix='/smtpserver')
    app.register_blueprint(recover_blueprint, url_prefix='/recover')
    app.register_blueprint(radiusserver_blueprint, url_prefix='/radiusserver')
    app.register_blueprint(periodictask_blueprint, url_prefix='/periodictask')
    app.register_blueprint(privacyideaserver_blueprint,
                           url_prefix='/privacyideaserver')
    app.register_blueprint(eventhandling_blueprint, url_prefix='/event')
    app.register_blueprint(smsgateway_blueprint, url_prefix='/smsgateway')
    app.register_blueprint(client_blueprint, url_prefix='/client')
    app.register_blueprint(subscriptions_blueprint,
                           url_prefix='/subscriptions')
    app.register_blueprint(monitoring_blueprint, url_prefix='/monitoring')
    db.init_app(app)
    migrate = Migrate(app, db)

    try:
        # Try to read logging config from file
        log_config_file = app.config.get("PI_LOGCONFIG",
                                         "/etc/privacyidea/logging.cfg")
        if os.path.isfile(log_config_file):
            logging.config.fileConfig(log_config_file)
            if not silent:
                print("Reading Logging settings from {0!s}".format(
                    log_config_file))
        else:
            raise Exception("The config file specified in PI_LOGCONFIG does "
                            "not exist.")
    except Exception as exx:
        if not silent:
            sys.stderr.write("{0!s}\n".format(exx))
            sys.stderr.write("Could not use PI_LOGCONFIG. "
                             "Using PI_LOGLEVEL and PI_LOGFILE.\n")
        level = app.config.get("PI_LOGLEVEL", logging.DEBUG)
        # If there is another logfile in pi.cfg we use this.
        logfile = app.config.get("PI_LOGFILE")
        if logfile:
            if not silent:
                sys.stderr.write("Using PI_LOGLEVEL {0!s}.\n".format(level))
                sys.stderr.write("Using PI_LOGFILE {0!s}.\n".format(logfile))
            PI_LOGGING_CONFIG["handlers"]["file"]["filename"] = logfile
            PI_LOGGING_CONFIG["handlers"]["file"]["level"] = level
            PI_LOGGING_CONFIG["loggers"]["privacyidea"]["level"] = level
            logging.config.dictConfig(PI_LOGGING_CONFIG)
        else:
            if not silent:
                sys.stderr.write("No PI_LOGFILE found. Using default "
                                 "config.\n")
            logging.config.dictConfig(DEFAULT_LOGGING_CONFIG)

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if we are not in the request context, return None to use the default
        # locale
        if not request:
            return None
        # otherwise try to guess the language from the user accept
        # header the browser transmits.  We support de/fr/en in this
        # example.  The best match wins.
        return request.accept_languages.best_match(
            ['de', 'fr', 'it', 'es', 'en'])

    queue.register_app(app)

    return app
Example #15
0
def create_app(app_name=None):

    # Configuration settings
    import config
    if not app_name:
        app_name = config.APP_NAME
    """Create the Flask application, startup logging and dynamically load
    additional modules (blueprints) that are found in this directory."""
    app = PgAdmin(__name__, static_url_path='/static')
    # Removes unwanted whitespace from render_template function
    app.jinja_env.trim_blocks = True
    app.config.from_object(config)
    app.config.update(dict(PROPAGATE_EXCEPTIONS=True))

    ##########################################################################
    # Setup logging and log the application startup
    ##########################################################################

    # Add SQL level logging, and set the base logging level
    logging.addLevelName(25, 'SQL')
    app.logger.setLevel(logging.DEBUG)
    app.logger.handlers = []

    # We also need to update the handler on the webserver in order to see
    # request. Setting the level prevents werkzeug from setting up it's own
    # stream handler thus ensuring all the logging goes through the pgAdmin
    # logger.
    logger = logging.getLogger('werkzeug')
    logger.setLevel(logging.INFO)

    # Set SQLITE_PATH to TEST_SQLITE_PATH while running test cases
    if "PGADMIN_TESTING_MODE" in os. environ and \
                    os.environ["PGADMIN_TESTING_MODE"] == "1":
        config.SQLITE_PATH = config.TEST_SQLITE_PATH

    # Ensure the various working directories exist
    from pgadmin.setup import create_app_data_directory, db_upgrade
    create_app_data_directory(config)

    # File logging
    fh = logging.FileHandler(config.LOG_FILE, encoding='utf-8')
    fh.setLevel(config.FILE_LOG_LEVEL)
    fh.setFormatter(logging.Formatter(config.FILE_LOG_FORMAT))
    app.logger.addHandler(fh)
    logger.addHandler(fh)

    # Console logging
    ch = logging.StreamHandler()
    ch.setLevel(config.CONSOLE_LOG_LEVEL)
    ch.setFormatter(logging.Formatter(config.CONSOLE_LOG_FORMAT))
    app.logger.addHandler(ch)
    logger.addHandler(ch)

    # Log the startup
    app.logger.info('########################################################')
    app.logger.info('Starting %s v%s...', config.APP_NAME, config.APP_VERSION)
    app.logger.info('########################################################')
    app.logger.debug("Python syspath: %s", sys.path)

    ##########################################################################
    # Setup i18n
    ##########################################################################

    # Initialise i18n
    babel = Babel(app)

    app.logger.debug('Available translations: %s' % babel.list_translations())

    @babel.localeselector
    def get_locale():
        """Get the language for the user."""
        language = 'en'
        if config.SERVER_MODE is False:
            # Get the user language preference from the miscellaneous module
            misc_preference = Preferences.module('miscellaneous', False)
            if misc_preference:
                user_languages = misc_preference.preference('user_language')
                if user_languages:
                    language = user_languages.get() or language
        else:
            # If language is available in get request then return the same
            # otherwise check the session or cookie
            data = request.form
            if 'language' in data:
                language = data['language'] or language
                setattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(session, 'PGADMIN_LANGUAGE'):
                language = getattr(session, 'PGADMIN_LANGUAGE', language)
            elif hasattr(request.cookies, 'PGADMIN_LANGUAGE'):
                language = getattr(request.cookies, 'PGADMIN_LANGUAGE',
                                   language)

        return language

    ##########################################################################
    # Setup authentication
    ##########################################################################

    app.config[
        'SQLALCHEMY_DATABASE_URI'] = u'sqlite:///{0}?timeout={1}'.format(
            config.SQLITE_PATH.replace(u'\\', u'/'),
            getattr(config, 'SQLITE_TIMEOUT', 500))

    # Only enable password related functionality in server mode.
    if config.SERVER_MODE is True:
        # TODO: Figure out how to disable /logout and /login
        app.config['SECURITY_RECOVERABLE'] = True
        app.config['SECURITY_CHANGEABLE'] = True

    # Create database connection object and mailer
    db.init_app(app)

    ##########################################################################
    # Upgrade the schema (if required)
    ##########################################################################
    with app.app_context():
        # Run migration for the first time i.e. create database
        from config import SQLITE_PATH
        if not os.path.exists(SQLITE_PATH):
            db_upgrade(app)
        else:
            version = Version.query.filter_by(name='ConfigDB').first()
            schema_version = version.value

            # Run migration if current schema version is greater than the
            # schema version stored in version table
            if CURRENT_SCHEMA_VERSION >= schema_version:
                db_upgrade(app)

            # Update schema version to the latest
            if CURRENT_SCHEMA_VERSION > schema_version:
                version = Version.query.filter_by(name='ConfigDB').first()
                version.value = CURRENT_SCHEMA_VERSION
                db.session.commit()

    Mail(app)

    import pgadmin.utils.paths as paths
    paths.init_app(app)

    # Setup Flask-Security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(None, user_datastore)

    ##########################################################################
    # Setup security
    ##########################################################################
    with app.app_context():
        config.CSRF_SESSION_KEY = Keys.query.filter_by(
            name='CSRF_SESSION_KEY').first().value
        config.SECRET_KEY = Keys.query.filter_by(
            name='SECRET_KEY').first().value
        config.SECURITY_PASSWORD_SALT = Keys.query.filter_by(
            name='SECURITY_PASSWORD_SALT').first().value

    # Update the app.config with proper security keyes for signing CSRF data,
    # signing cookies, and the SALT for hashing the passwords.
    app.config.update(dict(CSRF_SESSION_KEY=config.CSRF_SESSION_KEY))
    app.config.update(dict(SECRET_KEY=config.SECRET_KEY))
    app.config.update(
        dict(SECURITY_PASSWORD_SALT=config.SECURITY_PASSWORD_SALT))

    security.init_app(app, user_datastore)

    app.session_interface = create_session_interface(app)

    # Make the Session more secure against XSS & CSRF when running in web mode
    if config.SERVER_MODE:
        paranoid = Paranoid(app)
        paranoid.redirect_view = 'browser.index'

    ##########################################################################
    # Load all available server drivers
    ##########################################################################
    driver.init_app(app)

    ##########################################################################
    # Register language to the preferences after login
    ##########################################################################
    @user_logged_in.connect_via(app)
    def register_language(sender, user):
        # After logged in, set the language in the preferences if we get from
        # the login page
        data = request.form
        if 'language' in data:
            language = data['language']

            # Set the user language preference
            misc_preference = Preferences.module('miscellaneous')
            user_languages = misc_preference.preference('user_language')

            if user_languages and language:
                language = user_languages.set(language)

    ##########################################################################
    # Register any local servers we can discover
    ##########################################################################
    @user_logged_in.connect_via(app)
    def on_user_logged_in(sender, user):
        # Keep hold of the user ID
        user_id = user.id

        # Get the first server group for the user
        servergroup_id = 1
        servergroups = ServerGroup.query.filter_by(
            user_id=user_id).order_by("id")

        if servergroups.count() > 0:
            servergroup = servergroups.first()
            servergroup_id = servergroup.id
        '''Add a server to the config database'''
        def add_server(user_id, servergroup_id, name, superuser, port,
                       discovery_id, comment):
            # Create a server object if needed, and store it.
            servers = Server.query.filter_by(
                user_id=user_id, discovery_id=svr_discovery_id).order_by("id")

            if servers.count() > 0:
                return

            svr = Server(user_id=user_id,
                         servergroup_id=servergroup_id,
                         name=name,
                         host='localhost',
                         port=port,
                         maintenance_db='postgres',
                         username=superuser,
                         ssl_mode='prefer',
                         comment=svr_comment,
                         discovery_id=discovery_id)

            db.session.add(svr)
            db.session.commit()

        # Figure out what servers are present
        if winreg is not None:
            arch_keys = set()
            proc_arch = os.environ['PROCESSOR_ARCHITECTURE'].lower()

            try:
                proc_arch64 = os.environ['PROCESSOR_ARCHITEW6432'].lower()
            except:
                proc_arch64 = None

            if proc_arch == 'x86' and not proc_arch64:
                arch_keys.add(0)
            elif proc_arch == 'x86' or proc_arch == 'amd64':
                arch_keys.add(winreg.KEY_WOW64_32KEY)
                arch_keys.add(winreg.KEY_WOW64_64KEY)

            for arch_key in arch_keys:
                for server_type in ('PostgreSQL', 'EnterpriseDB'):
                    try:
                        root_key = winreg.OpenKey(
                            winreg.HKEY_LOCAL_MACHINE,
                            "SOFTWARE\\" + server_type + "\Services", 0,
                            winreg.KEY_READ | arch_key)
                        for i in xrange(0, winreg.QueryInfoKey(root_key)[0]):
                            inst_id = winreg.EnumKey(root_key, i)
                            inst_key = winreg.OpenKey(root_key, inst_id)

                            svr_name = winreg.QueryValueEx(
                                inst_key, 'Display Name')[0]
                            svr_superuser = winreg.QueryValueEx(
                                inst_key, 'Database Superuser')[0]
                            svr_port = winreg.QueryValueEx(inst_key, 'Port')[0]
                            svr_discovery_id = inst_id
                            svr_comment = gettext(
                                "Auto-detected %s installation with the data directory at %s"
                                % (winreg.QueryValueEx(inst_key,
                                                       'Display Name')[0],
                                   winreg.QueryValueEx(inst_key,
                                                       'Data Directory')[0]))

                            add_server(user_id, servergroup_id, svr_name,
                                       svr_superuser, svr_port,
                                       svr_discovery_id, svr_comment)

                            inst_key.Close()
                    except:
                        pass
        else:
            # We use the postgres-winreg.ini file on non-Windows
            try:
                from configparser import ConfigParser
            except ImportError:
                from ConfigParser import ConfigParser  # Python 2

            registry = ConfigParser()

        try:
            registry.read('/etc/postgres-reg.ini')
            sections = registry.sections()

            # Loop the sections, and get the data from any that are PG or PPAS
            for section in sections:
                if section.startswith('PostgreSQL/') or section.startswith(
                        'EnterpriseDB/'):
                    svr_name = registry.get(section, 'Description')
                    svr_superuser = registry.get(section, 'Superuser')
                    svr_port = registry.getint(section, 'Port')
                    svr_discovery_id = section
                    description = registry.get(section, 'Description')
                    data_directory = registry.get(section, 'DataDirectory')
                    if hasattr(str, 'decode'):
                        description = description.decode('utf-8')
                        data_directory = data_directory.decode('utf-8')
                    svr_comment = gettext(
                        u"Auto-detected %s installation with the data directory at %s"
                        % (description, data_directory))
                    add_server(user_id, servergroup_id, svr_name,
                               svr_superuser, svr_port, svr_discovery_id,
                               svr_comment)

        except:
            pass

    @user_logged_in.connect_via(app)
    @user_logged_out.connect_via(app)
    def force_session_write(app, user):
        session.force_write = True

    ##########################################################################
    # Load plugin modules
    ##########################################################################
    for module in app.find_submodules('pgadmin'):
        app.logger.info('Registering blueprint module: %s' % module)
        app.register_blueprint(module)

    ##########################################################################
    # Handle the desktop login
    ##########################################################################

    @app.before_request
    def before_request():
        """Login the default user if running in desktop mode"""

        # Check the auth key is valid, if it's set, and we're not in server
        # mode, and it's not a help file request.
        if not config.SERVER_MODE and app.PGADMIN_KEY != '':
            if ((not 'key' in request.args
                 or request.args['key'] != app.PGADMIN_KEY)
                    and request.cookies.get('PGADMIN_KEY') != app.PGADMIN_KEY
                    and request.endpoint != 'help.static'):
                abort(401)

        if not config.SERVER_MODE:
            user = user_datastore.get_user(config.DESKTOP_USER)

            # Throw an error if we failed to find the desktop user, to give
            # the sysadmin a hint. We'll continue to try to login anyway as
            # that'll through a nice 500 error for us.
            if user is None:
                app.logger.error(
                    'The desktop user %s was not found in the configuration database.'
                    % config.DESKTOP_USER)
                abort(401)

            login_user(user)

    @app.after_request
    def after_request(response):
        if 'key' in request.args:
            response.set_cookie('PGADMIN_KEY', value=request.args['key'])

        return response

    ##########################################################################
    # Minify output
    ##########################################################################
    # HTMLMIN doesn't work with Python 2.6.
    if not config.DEBUG and sys.version_info >= (2, 7):
        from flask_htmlmin import HTMLMIN
        HTMLMIN(app)

    @app.context_processor
    def inject_blueprint():
        """Inject a reference to the current blueprint, if any."""
        return {
            'current_app': current_app,
            'current_blueprint': current_blueprint
        }

    ##########################################################################
    # All done!
    ##########################################################################

    return app
Example #16
0
def create_app():
    app = Flask(__name__, static_folder="dist", static_url_path="")

    if os.environ.get('FLASK_ENV') in ['production', 'staging', 'autopush']:
        createMiddleWare(app, StackdriverExporter())
        import googlecloudprofiler
        # Profiler initialization. It starts a daemon thread which continuously
        # collects and uploads profiles. Best done as early as possible.
        try:
            # service and service_version can be automatically inferred when
            # running on GCP.
            googlecloudprofiler.start(verbose=3)
        except (ValueError, NotImplementedError) as exc:
            logging.error(exc)

    # Setup flask config
    cfg = libconfig.get_config()
    app.config.from_object(cfg)

    # Init extentions
    from cache import cache
    cache.init_app(app)

    # apply the blueprints to the app
    from routes import (protein, browser, dev, factcheck, place, placelist,
                        ranking, redirects, static, tools)
    app.register_blueprint(protein.bp)
    app.register_blueprint(browser.bp)
    app.register_blueprint(dev.bp)
    app.register_blueprint(place.bp)
    app.register_blueprint(placelist.bp)
    app.register_blueprint(ranking.bp)
    app.register_blueprint(redirects.bp)
    app.register_blueprint(tools.bp)
    from routes.api import (protein as protein_api, browser as browser_api,
                            choropleth, place as place_api, landing_page,
                            ranking as ranking_api, stats, translator)
    app.register_blueprint(protein_api.bp)
    app.register_blueprint(browser_api.bp)
    app.register_blueprint(choropleth.bp)
    app.register_blueprint(factcheck.bp)
    app.register_blueprint(place_api.bp)
    app.register_blueprint(landing_page.bp)
    app.register_blueprint(ranking_api.bp)
    app.register_blueprint(static.bp)
    app.register_blueprint(stats.bp)
    app.register_blueprint(translator.bp)

    # Load chart config
    with open('chart_config.json', encoding='utf-8') as f:
        chart_config = json.load(f)
    app.config['CHART_CONFIG'] = chart_config

    if not cfg.TEST and not cfg.LITE:
        secret_client = secretmanager.SecretManagerServiceClient()
        secret_name = secret_client.secret_version_path(cfg.SECRET_PROJECT,
                                                        'maps-api-key', '1')
        secret_response = secret_client.access_secret_version(name=secret_name)
        app.config['MAPS_API_KEY'] = secret_response.payload.data.decode(
            'UTF-8')

    if cfg.TEST or cfg.WEBDRIVER or cfg.LITE:
        app.config['PLACEID2DCID'] = {
            "ChIJCzYy5IS16lQRQrfeQ5K5Oxw": "country/USA",
            "ChIJPV4oX_65j4ARVW8IJ6IJUYs": "geoId/06"
        }
    else:
        # Load placeid2dcid mapping from GCS
        storage_client = storage.Client()
        bucket = storage_client.get_bucket(app.config['GCS_BUCKET'])
        blob = bucket.get_blob('placeid2dcid.json')
        app.config['PLACEID2DCID'] = json.loads(blob.download_as_bytes())

    # Initialize translations
    babel = Babel(app, default_domain='all')
    app.config['BABEL_DEFAULT_LOCALE'] = i18n.DEFAULT_LOCALE
    app.config['BABEL_TRANSLATION_DIRECTORIES'] = 'i18n'

    if not cfg.TEST:
        timeout = 120  # seconds
        counter = 0
        isOpen = False
        while not isOpen:
            try:
                urllib.request.urlopen(cfg.API_ROOT + "/version")
                break
            except urllib.error.URLError:
                time.sleep(1)
                counter += 1
            if counter > timeout:
                raise RuntimeError("Mixer not ready after %s second" % timeout)

    @app.before_request
    def before_request():
        requested_locale = request.args.get('hl', i18n.DEFAULT_LOCALE)
        g.locale_choices = i18n.locale_choices(requested_locale)
        g.locale = g.locale_choices[0]

    @babel.localeselector
    def get_locale():
        return g.locale

    # Propagate hl parameter to all links (if not 'en')
    @app.url_defaults
    def add_language_code(endpoint, values):
        if 'hl' in values or g.locale == i18n.DEFAULT_LOCALE:
            return
        values['hl'] = g.locale

    # Provides locale parameter in all templates
    @app.context_processor
    def inject_locale():
        return dict(locale=get_locale())

    return app
Example #17
0
def make_flask_stack(conf, **app_conf):
    """ This has to pass the flask app through all the same middleware that
    Pylons used """

    root = os.path.dirname(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    debug = asbool(app_conf.get('debug', app_conf.get('DEBUG', False)))
    testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False)))

    app = flask_app = CKANFlask(__name__)
    app.debug = debug
    app.testing = testing
    app.template_folder = os.path.join(root, 'templates')
    app.app_ctx_globals_class = CKAN_AppCtxGlobals
    app.url_rule_class = CKAN_Rule
    app.jinja_loader = ChoiceLoader(
        [app.jinja_loader, CkanextTemplateLoader()])

    # Update Flask config with the CKAN values. We use the common config
    # object as values might have been modified on `load_environment`
    if config:
        app.config.update(config)
    else:
        app.config.update(conf)
        app.config.update(app_conf)

    # Do all the Flask-specific stuff before adding other middlewares

    # Secret key needed for flask-debug-toolbar and sessions
    if not app.config.get('SECRET_KEY'):
        app.config['SECRET_KEY'] = config.get('beaker.session.secret')
    if not app.config.get('SECRET_KEY'):
        raise RuntimeError(u'You must provide a value for the secret key'
                           ' with the SECRET_KEY config option')

    if debug:
        from flask_debugtoolbar import DebugToolbarExtension
        app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
        DebugToolbarExtension(app)

    # Use Beaker as the Flask session interface
    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            if 'beaker.session' in request.environ:
                return request.environ['beaker.session']

        def save_session(self, app, session, response):
            session.save()

    namespace = 'beaker.session.'
    session_opts = dict([(k.replace('beaker.', ''), v)
                         for k, v in config.iteritems()
                         if k.startswith(namespace)])
    if (not session_opts.get('session.data_dir')
            and session_opts.get('session.type', 'file') == 'file'):
        cache_dir = app_conf.get('cache_dir') or app_conf.get('cache.dir')
        session_opts['session.data_dir'] = '{data_dir}/sessions'.format(
            data_dir=cache_dir)

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    # Add Jinja2 extensions and filters
    extensions = [
        'jinja2.ext.do', 'jinja2.ext.with_', jinja_extensions.SnippetExtension,
        jinja_extensions.CkanExtend,
        jinja_extensions.CkanInternationalizationExtension,
        jinja_extensions.LinkForExtension, jinja_extensions.ResourceExtension,
        jinja_extensions.UrlForStaticExtension,
        jinja_extensions.UrlForExtension
    ]
    for extension in extensions:
        app.jinja_env.add_extension(extension)
    app.jinja_env.filters['empty_and_escape'] = \
        jinja_extensions.empty_and_escape

    # Common handlers for all requests
    app.before_request(ckan_before_request)
    app.after_request(ckan_after_request)

    # Template context processors
    app.context_processor(helper_functions)
    app.context_processor(c_object)

    @app.context_processor
    def ungettext_alias():
        u'''
        Provide `ungettext` as an alias of `ngettext` for backwards
        compatibility
        '''
        return dict(ungettext=ungettext)

    # Babel
    app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = os.path.join(root, u'i18n')
    app.config[u'BABEL_DOMAIN'] = 'ckan'

    babel = Babel(app)

    babel.localeselector(get_locale)

    @app.route('/hello', methods=['GET'])
    def hello_world():
        return 'Hello World, this is served by Flask'

    @app.route('/hello', methods=['POST'])
    def hello_world_post():
        return 'Hello World, this was posted to Flask'

    # Auto-register all blueprints defined in the `views` folder
    _register_core_blueprints(app)

    # Set up each IBlueprint extension as a Flask Blueprint
    for plugin in PluginImplementations(IBlueprint):
        if hasattr(plugin, 'get_blueprint'):
            app.register_extension_blueprint(plugin.get_blueprint())

    # Set flask routes in named_routes
    for rule in app.url_map.iter_rules():
        if '.' not in rule.endpoint:
            continue
        controller, action = rule.endpoint.split('.')
        needed = list(rule.arguments - set(rule.defaults or {}))
        route = {
            rule.endpoint: {
                'action': action,
                'controller': controller,
                'highlight_actions': action,
                'needed': needed
            }
        }
        config['routes.named_routes'].update(route)

    # Start other middleware
    for plugin in PluginImplementations(IMiddleware):
        app = plugin.make_middleware(app, config)

    # Fanstatic
    if debug:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': True,
            'minified': False,
            'bottom': True,
            'bundle': False,
        }
    else:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': False,
            'minified': True,
            'bottom': True,
            'bundle': True,
        }
    root_path = config.get('ckan.root_path', None)
    if root_path:
        root_path = re.sub('/{{LANG}}', '', root_path)
        fanstatic_config['base_url'] = root_path
    app = Fanstatic(app, **fanstatic_config)

    for plugin in PluginImplementations(IMiddleware):
        try:
            app = plugin.make_error_log_middleware(app, config)
        except AttributeError:
            log.critical('Middleware class {0} is missing the method'
                         'make_error_log_middleware.'.format(
                             plugin.__class__.__name__))

    # Initialize repoze.who
    who_parser = WhoConfig(conf['here'])
    who_parser.parse(open(app_conf['who.config_file']))

    app = PluggableAuthenticationMiddleware(
        app,
        who_parser.identifiers,
        who_parser.authenticators,
        who_parser.challengers,
        who_parser.mdproviders,
        who_parser.request_classifier,
        who_parser.challenge_decider,
        logging.getLogger('repoze.who'),
        logging.WARN,  # ignored
        who_parser.remote_user_key)

    # Update the main CKAN config object with the Flask specific keys
    # that were set here or autogenerated
    flask_config_keys = set(flask_app.config.keys()) - set(config.keys())
    for key in flask_config_keys:
        config[key] = flask_app.config[key]

    # Add a reference to the actual Flask app so it's easier to access
    app._wsgi_app = flask_app

    return app
Example #18
0
from datetime import date

from flask import Flask, g, request, render_template, abort, make_response, url_for, redirect
from flask_babel import Babel, gettext

EVENT = gettext('PyCon SK 2019')
DOMAIN = 'https://2019.pycon.sk'
API_DOMAIN = 'https://api.pycon.sk'

LANGS = ('en', 'sk')
TIME_FORMAT = '%Y-%m-%dT%H:%M:%S+00:00'

app = Flask(__name__, static_url_path='/static')  # pylint: disable=invalid-name
app.config['BABEL_DEFAULT_LOCALE'] = 'sk'
app.jinja_options = {'extensions': ['jinja2.ext.with_', 'jinja2.ext.i18n']}
babel = Babel(app)  # pylint: disable=invalid-name


@app.route('/sitemap.xml')
def sitemap():
    excluded = {'static', 'sitemap'}
    pages = []

    for lang in LANGS:
        for rule in app.url_map.iter_rules():
            if 'GET' in rule.methods and rule.endpoint not in excluded:
                # `url_for` appends unknown arguments as query parameters.
                # We want to avoid that when a page isn't localized.
                values = {
                    'lang_code': lang
                } if 'lang_code' in rule.arguments else {}
Example #19
0
def register_extensions(app):
    """ register extensions to the app """
    app.jinja_env.add_extension('jinja2.ext.do')  # Global values in jinja

    # Uncomment to enable profiler
    # See scripts/profile_analyzer.py to analyze output
    # app = setup_profiler(app)

    # Compress app responses with gzip
    compress = Compress()
    compress.init_app(app)

    # Influx db time-series database
    db.init_app(app)
    influx_db.init_app(app)

    # Limit authentication blueprint requests to 60 per minute
    limiter = Limiter(app, key_func=get_ip_address)
    limiter.limit("60/minute")(routes_authentication.blueprint)

    # Language translations
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        try:
            user = User.query.filter(
                User.id == flask_login.current_user.id).first()
            if user and user.language != '':
                for key in LANGUAGES:
                    if key == user.language:
                        return key
        # Bypass endpoint test error "'AnonymousUserMixin' object has no attribute 'id'"
        except AttributeError:
            pass
        return request.accept_languages.best_match(LANGUAGES.keys())

    # User login management
    login_manager = flask_login.LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def user_loader(user_id):
        user = User.query.filter(User.id == user_id).first()
        if not user:
            return
        return user

    @login_manager.unauthorized_handler
    def unauthorized():
        flash(gettext('Please log in to access this page'), "error")
        return redirect(url_for('routes_authentication.do_login'))

    # Create and populate database if it doesn't exist
    with app.app_context():
        db.create_all()
        populate_db()

        # This is disabled because there's a bug that messes up user databases
        # The upgrade script will execute alembic to upgrade the database
        # alembic_upgrade_db()

    # Check user option to force all web connections to use SSL
    # Fail if the URI is empty (pytest is running)
    if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
        with session_scope(
                app.config['SQLALCHEMY_DATABASE_URI']) as new_session:
            misc = new_session.query(Misc).first()
            if misc and misc.force_https:
                SSLify(app)
Example #20
0
def create_app(path_to_notebook, *args, **kwds):
    """
    This is the main method to create a running notebook. This is
    called from the process spawned in run_notebook.py
    """
    global notebook
    startup_token = kwds.pop('startup_token', None)

    #############
    # OLD STUFF #
    #############
    import sagenb.notebook.notebook as notebook
    notebook.MATHJAX = True
    notebook = notebook.load_notebook(path_to_notebook, *args, **kwds)
    init_updates()

    ##############
    # Create app #
    ##############
    app = SageNBFlask('flask_version',
                      startup_token=startup_token,
                      template_folder=TEMPLATE_PATH)
    app.secret_key = os.urandom(24)
    oid.init_app(app)
    app.debug = True

    @app.before_request
    def set_notebook_object():
        g.notebook = notebook

    ####################################
    # create Babel translation manager #
    ####################################
    babel = Babel(app, default_locale='en_US')

    #Check if saved default language exists. If not fallback to default
    @app.before_first_request
    def check_default_lang():
        def_lang = notebook.conf()['default_language']
        trans_ids = [str(trans) for trans in babel.list_translations()]
        if def_lang not in trans_ids:
            notebook.conf()['default_language'] = None

    #register callback function for locale selection
    #this function must be modified to add per user language support
    @babel.localeselector
    def get_locale():
        return g.notebook.conf()['default_language']

    ########################
    # Register the modules #
    ########################
    app.register_blueprint(base)

    from .worksheet_listing import worksheet_listing
    app.register_blueprint(worksheet_listing)

    from .admin import admin
    app.register_blueprint(admin)

    from .authentication import authentication
    app.register_blueprint(authentication)

    from .doc import doc
    app.register_blueprint(doc)

    from .worksheet import ws as worksheet
    app.register_blueprint(worksheet)

    from .settings import settings
    app.register_blueprint(settings)

    # Handles all uncaught exceptions by sending an e-mail to the
    # administrator(s) and displaying an error page.
    @app.errorhandler(Exception)
    def log_exception(error):
        from sagenb.notebook.notification import logger
        logger.exception(error)
        return app.message(gettext('''500: Internal server error.'''),
                           username=getattr(g, 'username', 'guest')), 500

    #autoindex v0.3 doesnt seem to work with modules
    #routing with app directly does the trick
    #TODO: Check to see if autoindex 0.4 works with modules
    idx = AutoIndex(app, browse_root=SRC, add_url_rules=False)

    @app.route('/src/')
    @app.route('/src/<path:path>')
    @guest_or_login_required
    def autoindex(path='.'):
        filename = os.path.join(SRC, path)
        if os.path.isfile(filename):
            from cgi import escape
            src = escape(open(filename).read().decode('utf-8', 'ignore'))
            if (os.path.splitext(filename)[1]
                    in ['.py', '.c', '.cc', '.h', '.hh', '.pyx', '.pxd']):
                return render_template(os.path.join('html',
                                                    'source_code.html'),
                                       src_filename=path,
                                       src=src,
                                       username=g.username)
            return src
        return idx.render_autoindex(path)

    return app
Example #21
0
def _load_file():
    """Load Beancount files.

    This is run automatically on the first request.
    """
    app.config["LEDGERS"] = {}
    for filepath in app.config["BEANCOUNT_FILES"]:
        ledger = FavaLedger(filepath)
        slug = slugify(ledger.options["title"])
        if not slug:
            slug = slugify(filepath)
        app.config["LEDGERS"][slug] = ledger
    app.config["FILE_SLUGS"] = list(app.config["LEDGERS"].keys())


BABEL = Babel(app)


@BABEL.localeselector
def get_locale() -> Optional[str]:
    """Get locale.

    Returns:
        The locale that should be used for Babel. If not given as an option to
        Fava, guess from browser.
    """
    if g.ledger.fava_options["language"]:
        return g.ledger.fava_options["language"]
    return request.accept_languages.best_match(["en"] + LANGUAGES)

Example #22
0
def create_app(test_config=None):                   # For automated tests
    # Setup Flask and read config from ConfigClass defined above
    app = Flask(__name__)
    app.config.from_object(__name__+'.ConfigClass')

    # Load local_settings.py if file exists         # For automated tests
    try: app.config.from_object('local_settings')
    except: pass

    # Load optional test_config                     # For automated tests
    if test_config:
        app.config.update(test_config)

    # Initialize Flask extensions
    db = SQLAlchemy(app)                            # Initialize Flask-SQLAlchemy
    mail = Mail(app)                                # Initialize Flask-Mail
    babel = Babel(app)                              # Initialize Flask-Babel
    @babel.localeselector
    def get_locale():
        translations = [str(translation) for translation in babel.list_translations()]
        language = request.accept_languages.best_match(translations)
        return language

    # Define the User data model. Make sure to add flask_user UserMixin !!!
    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')
        reset_password_token = db.Column(db.String(100), nullable=False, server_default='')

        # User email information
        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())

        # User information
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')
        first_name = db.Column(db.String(100), nullable=False, server_default='')
        last_name = db.Column(db.String(100), nullable=False, server_default='')

    # Create all database tables
    db.create_all()

    # Setup Flask-User
    db_adapter = SQLAlchemyAdapter(db,  User)       # Select database adapter
    user_manager = UserManager(db_adapter, app)     # Init Flask-User and bind to app

    # The Home page is accessible to anyone
    @app.route('/')
    def home_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>{%trans%}Home Page{%endtrans%}</h2>
                {% if current_user.is_authenticated() %}
                <p> <a href="{{ url_for('user_profile_page') }}">
                    {%trans%}Profile Page{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.logout') }}">
                    {%trans%}Sign out{%endtrans%}</a></p>
                {% else %}
                <p> <a href="{{ url_for('user.login') }}">
                    {%trans%}Sign in or Register{%endtrans%}</a></p>
                {% endif %}
            {% endblock %}
            """)
        if current_user.is_authenticated():
            return redirect(url_for('user_profile_page'))
        else:
            return redirect(url_for('user.login'))

# The Profile page requires a logged-in user
    @app.route('/user/profile')
    @login_required                                 # Use of @login_required decorator
    @confirm_email_required
    def user_profile_page():
        return render_template_string("""
            {% extends "base.html" %}
            {% block content %}
                <h2>{%trans%}Profile Page{%endtrans%}</h2>
                <p> {%trans%}Hello{%endtrans%}
                    {{ current_user.username or current_user.email }},</p>
                <p> <a href="{{ url_for('home_page') }}">
                    {%trans%}Home Page{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.change_username') }}">
                    {%trans%}Change username{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.change_password') }}">
                    {%trans%}Change password{%endtrans%}</a></p>
                <p> <a href="{{ url_for('user.logout') }}">
                    {%trans%}Sign out{%endtrans%}</a></p>
            {% endblock %}
            """)

    return app
Example #23
0
import quotes
from agenda import Agenda
from journaling import Journaling
from tasks import Tasks
from user import get_user_content_right
from workout import Workout

NavigationItem = namedtuple('NavigationItem', 'id title icon')

app = Flask(__name__)
with open('config.yaml', 'r') as f:
    config = yaml.full_load(f)

locale = config['locale'] if 'locale' in config else 'en'
babel = Babel(app, default_locale=locale)

with app.app_context():  # this is required to have translations in loading functions
    _agenda = Agenda()
    _journaling = Journaling(config['journaling'])
    _workout = None
    if 'workout' in config:
        _workout = Workout(config['workout'])
    _tasks = None
    if 'redmine' in config:
        config['redmine']['date_format'] = config['date_format']  # copy from global
        _tasks = Tasks(config['redmine'])


@app.route('/')
def index_page():
Example #24
0
    # Testing on GitHub Actions
    application.config[
        "SQLALCHEMY_DATABASE_URI"
    ] = "postgres://*****:*****@localhost:5432/mosp"
elif ON_HEROKU:
    # Deployment on Heroku
    application.config.from_pyfile("heroku.py", silent=False)
else:
    try:
        application.config.from_pyfile("production.py", silent=False)
    except Exception:
        application.config.from_pyfile("development.py", silent=False)
db = SQLAlchemy(application)


babel = Babel(application)


@babel.localeselector
def get_locale():
    # if a user is logged in, use the locale from the user settings
    # user = getattr(g, 'user', None)
    # if user is not None:
    #     return user.locale
    # otherwise try to guess the language from the user accept
    # header the browser transmits.  We support de/fr/en in this
    # example.  The best match wins.
    return request.accept_languages.best_match(["fr", "en"])


# @babel.timezoneselector
Example #25
0

class Blog(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey("myuser.id"), nullable=False)
    title = db.Column(db.Text)
    text = db.Column(db.UnicodeText)


# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
app.security = Security(app, user_datastore)

# Setup Babel - not strictly necessary but since our virtualenv has Flask-Babel
# we need to initialize it
Babel(app)

# Set this so unit tests can mock out.
app.blog_cls = Blog


# Create users and roles (and first blog!)
@app.before_first_request
def create_users():
    if current_app.testing:
        return
    db.create_all()
    user_datastore.find_or_create_role(
        name="admin",
        permissions={"admin-read", "admin-write", "user-read", "user-write"},
    )
Example #26
0
 def __init__(self, *args, **kwargs):
   BabelBase.__init__(self, *args, **kwargs)
Example #27
0
# -*- coding: utf-8 -*-
from werkzeug.contrib.fixers import ProxyFix
from flask_babel import Babel, gettext as _
from app import create_app

app.create_app()
saasapp = app.app_

babel = Babel(app.app_)

saasapp.wsgi_app = ProxyFix(saasapp.wsgi_app)

if __name__ == '__main__':
    saasapp.run()
Example #28
0
class AppKernelEngine(object):
    def __init__(self,
                 app_id,
                 app=None,
                 root_url='/',
                 log_level=logging.DEBUG,
                 cfg_dir=None,
                 development=None,
                 enable_defaults=False):
        """
        Initialiser of Flask Engine.
        :param app: the Flask App
        :type app: Flask
        :param root_url: the url where the service are exposed to.
        :type root_url: str
        :param log_level: the level of log
        :param cfg_dir: the directory containing the cfg.yml file. If not provided it will be taken from the command line or from current working dir;
        :param development: the system will be initialised in development mode if True. If None, it will try to read the value as command line parameter or default to false;
        :type log_level: logging
        """
        assert app_id is not None, 'The app_id must be provided'
        assert re.match(
            '[A-Za-z0-9-_]', app_id
        ), 'The app_id must be a single word, no space or special characters except - or _ .'
        self.app = app or current_app
        assert self.app is not None, 'The Flask App must be provided as init parameter.'
        try:
            config.service_registry = {}
            self.before_request_functions = []
            self.after_request_functions = []
            self.app_id = app_id
            self.root_url = root_url
            self.__configure_flask_app()
            self.__init_web_layer()
            self.cmd_line_options = get_cmdline_options()
            self.cfg_dir = cfg_dir or self.cmd_line_options.get('cfg_dir')
            self.cfg_engine = CfgEngine(self.cfg_dir, optional=enable_defaults)
            config.cfg_engine = self.cfg_engine
            self.__init_babel()
            self.__init_cross_cutting_concerns()
            self.development = development or self.cmd_line_options.get(
                'development')
            cwd = self.cmd_line_options.get('cwd')
            self.init_logger(log_folder=cwd, level=log_level)
            # -- initialisation
            # this can raise false positives if a bit of code running
            # longer than 1 seconds.
            # the timeout can be increased by adding the parameter:
            # resolution=3, where the value 3 represents 3 seconds.
            eventlet.debug.hub_blocking_detection(True, resolution=3)
            atexit.register(self.shutdown_hook)
            if hasattr(app, 'teardown_appcontext'):
                app.teardown_appcontext(self.teardown)
            else:
                app.teardown_request(self.teardown)
            # -- database host
            db_host = self.cfg_engine.get(
                'appkernel.mongo.host') or 'localhost'
            db_name = self.cfg_engine.get('appkernel.mongo.db') or 'app'
            self.mongo_client = MongoClient(host=db_host)
            config.mongo_database = self.mongo_client[db_name]
        except (AppInitialisationError, AssertionError) as init_err:
            # print >> sys.stderr,
            self.app.logger.error(init_err.message)
            sys.exit(-1)

    def enable_security(self, authorisation_method=None):
        self.enable_pki()
        if not authorisation_method:
            authorisation_method = authorize_request
        self.add_before_request_function(authorisation_method)
        config.security_enabled = True
        return self

    def enable_pki(self):
        if not hasattr(self.app, 'public_key'):
            self.__init_crypto()

    def add_before_request_function(self, func):
        self.before_request_functions.append(func)

    def add_after_request_function(self, func):
        self.after_request_functions.append(func)

    def __init_cross_cutting_concerns(self):
        def create_function_chain_executor(chain):
            def function_chain_executor():
                for func in chain:
                    return func()

            return function_chain_executor

        # todo: journaling request responses
        # todo: rate limiting
        self.app.before_request(
            create_function_chain_executor(self.before_request_functions))
        # todo: add after request processor
        # self.app.after_request(create_function_chain_executor(self.after_request_functions))

    def __init_crypto(self):
        # https://stackoverflow.com/questions/29650495/how-to-verify-a-jwt-using-python-pyjwt-with-public-key
        with self.app.app_context():
            with open('{}/keys/appkernel.pem'.format(self.cfg_dir),
                      "rb") as key_file:
                private_key = serialization.load_pem_private_key(
                    key_file.read(), password=None, backend=default_backend())
                config.private_key = private_key
            with open('{}/keys/appkernel.pub'.format(self.cfg_dir),
                      'rb') as key_file:
                public_key = serialization.load_pem_public_key(
                    key_file.read(), backend=default_backend())
                config.public_key = public_key

    def __init_babel(self):
        self.babel = Babel(self.app)
        # translations = Translations.load('translations')
        # translations.merge(Translations.load())
        # todo: support for multiple plugins
        supported_languages = []
        for supported_lang in self.cfg_engine.get(
                'appkernel.i18n.languages') or ['en-US']:
            supported_languages.append(supported_lang)
            if '-' in supported_lang:
                supported_languages.append(supported_lang.split('-')[0])

        def get_current_locale():
            with self.app.app_context():
                best_match = request.accept_languages.best_match(
                    supported_languages, default='en')
                return best_match.replace('-', '_')

        self.babel.localeselector(get_current_locale)
        # catalogs = gettext.find('locale', 'locale', all=True)
        # self.logger.info('Using message catalogs: {}'.format(catalogs))

    @property
    def logger(self):
        return self.app.logger

    def run(self):
        self.app.logger.info('===== Starting {} ====='.format(self.app_id))
        self.app.run(debug=self.development)

    def shutdown_hook(self):
        if config.mongo_database:
            self.mongo_client.close()
        if self.app and self.app.logger:
            self.app.logger.info('======= Shutting Down {} ======='.format(
                self.app_id))

    def get_cmdline_options(self):
        # working dir is also available on: self.app.root_path
        argv = sys.argv[1:]
        opts, args = getopt.getopt(
            argv, 'c:dw:', ['config-dir=', 'development', 'working-dir='])
        # -- config directory
        config_dir_provided, config_dir_param = AppKernelEngine.is_option_provided(
            ('-c', '--config-dir'), opts, args)
        cwd = os.path.dirname(os.path.realpath(sys.argv[0]))
        if config_dir_provided:
            cfg_dir = '{}/'.format(str(config_dir_param).rstrip('/'))
            cfg_dir = os.path.expanduser(cfg_dir)
            if not os.path.isdir(cfg_dir) or not os.access(cfg_dir, os.W_OK):
                raise AppInitialisationError(
                    'The config directory [{}] is not found/not writable.'.
                    format(cfg_dir))
        else:
            cfg_dir = '{}/../'.format(cwd.rstrip('/'))

        # -- working directory
        working_dir_provided, working_dir_param = AppKernelEngine.is_option_provided(
            ('-w', '--working-dir'), opts, args)
        if working_dir_provided:
            cwd = os.path.expanduser('{}/'.format(
                str(config_dir_param).rstrip('/')))
            if not os.path.isdir(cwd) or not os.access(cwd, os.W_OK):
                raise AppInitialisationError(
                    'The working directory[{}] is not found/not writable.'.
                    format(cwd))
        else:
            cwd = '{}/../'.format(cwd.rstrip('/'))
        development, param = AppKernelEngine.is_option_provided(
            ('-d', '--development'), opts, args)
        return {'cfg_dir': cfg_dir, 'development': development, 'cwd': cwd}

    @staticmethod
    def is_option_provided(option_dict, opts, args):
        for opt, arg in opts:
            if opt in option_dict:
                return True, arg
        return False, ''

    def __configure_flask_app(self):
        if hasattr(self.app, 'teardown_appcontext'):
            self.app.teardown_appcontext(self.teardown)
        else:
            self.app.teardown_request(self.teardown)
        if not hasattr(self.app, 'extensions'):
            self.app.extensions = {}
        self.app.extensions['appkernel'] = self

    def __init_web_layer(self):
        self.app.json_encoder = AppKernelJSONEncoder
        self.app.register_error_handler(Exception, self.generic_error_handler)
        for code in default_exceptions.keys():
            # add a default error handler for everything is unhandled
            self.app.register_error_handler(code, self.generic_error_handler)

            def set_locale_on_request():
                g.locale = str(get_locale())

            self.app.before_request(set_locale_on_request)

    def init_logger(self, log_folder, level=logging.DEBUG):
        assert log_folder is not None, 'The log folder must be provided.'
        if self.development:
            formatter = logging.Formatter("%(levelname)s - %(message)s")
            handler = logging.StreamHandler()
            handler.setLevel(level)
            self._enable_werkzeug_logger(handler)
        else:
            # self.cfg_engine.get_value_for_section()
            # log_format = ' in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s'
            formatter = logging.Formatter(
                "%(asctime)s - %(levelname)s - %(name)s:%(lineno)d - %(message)s"
            )
            max_bytes = self.cfg_engine.get(
                'appkernel.logging.max_size') or 10485760
            backup_count = self.cfg_engine.get(
                'appkernel.logging.backup_count') or 3
            file_name = self.cfg_engine.get(
                'appkernel.logging.file_name') or '{}.log'.format(self.app_id)
            handler = RotatingFileHandler('{}/{}.log'.format(
                log_folder, file_name),
                                          maxBytes=max_bytes,
                                          backupCount=backup_count)
            # handler = TimedRotatingFileHandler('logs/foo.log', when='midnight', interval=1)
            handler.setLevel(level)
        handler.setFormatter(formatter)
        self.app.logger.setLevel(level)
        self.app.logger.addHandler(handler)
        self.app.logger.info('Logger initialised')

    def _enable_werkzeug_logger(self, handler):
        logger = logging.getLogger('werkzeug')
        logger.setLevel(logging.DEBUG)
        logger.addHandler(handler)

    def create_custom_error(self, code, message):
        return make_response(
            jsonify({
                '_type': MessageType.ErrorMessage.name,
                'code': code,
                'message': message
            }), code)

    def generic_error_handler(self, ex=None):
        """
        Takes a generic exception and returns a json error message which will be returned to the client
        :param ex:
        :return:
        """
        code = (ex.code if isinstance(ex, HTTPException) else 500)
        if ex:
            msg = '{}/{}'.format(
                ex.__class__.__name__,
                ex.description if isinstance(ex, HTTPException) else str(ex))
            self.logger.exception('generic error handler: {}/{}'.format(
                ex.__class__.__name__, str(ex)))
        else:
            msg = 'Generic server error.'
            self.logger.warn('generic error handler: {}/{}'.format(
                ex.__class__.__name__, str(ex)))
        return self.create_custom_error(code, msg)

    def teardown(self, exception):
        """
        context teardown based deallocation
        :param exception:
        :type exception: Exception
        :return:
        """
        if exception is not None:
            self.app.logger.warn(exception.message)

    def register(self,
                 service_class,
                 url_base=None,
                 methods=['GET'],
                 enable_hateoas=True):
        """

        :param service_class:
        :param url_base:
        :param methods:
        :param enable_hateoas:
        :return:
        :rtype: Service
        """
        assert issubclass(
            service_class,
            appkernel.Service), 'Only subclasses of Service can be registered.'
        service_class.set_app_engine(self,
                                     url_base or self.root_url,
                                     methods=methods,
                                     enable_hateoas=enable_hateoas)
        return service_class
Example #29
0
# -*- coding: utf-8 -*-
from flask import Flask
from flask_babel import Babel
from flask_wtf import CSRFProtect

from flask_bootstrap import Bootstrap

babel = Babel(configure_jinja=False)
bootstrap = Bootstrap()
csrf = CSRFProtect()

app = Flask('texrrow')
Example #30
0
def create_app(configfile=None):
    app = Flask(__name__)

    app.config.from_object('web.config.Config')

    Markdown(app)

    # JSON
    app.json_encoder = CustomJSONEncoder
    app.json_decoder = CustomJSONDecoder

    # Typography Jinja2 Filter
    app.jinja_env.filters['typogrify'] = typogrify_filters.typogrify

    # Static Assets Config (Javascript and SCSS)
    env = assets.Environment(app)

    env.load_path = [
        os.path.join(app.config['STATIC_PATH'], 'bower'),
        os.path.join(app.config['STATIC_PATH'], 'scss'),
        os.path.join(app.config['STATIC_PATH'], 'javascript')
    ]

    env.register('js_all',
                 assets.Bundle('jquery/dist/jquery.min.js',
                               'leaflet/dist/leaflet.js',
                               assets.Bundle('iconic.min.js'),
                               assets.Bundle('app.js'),
                               output='app.js'))

    sass = get_filter('scss')
    sass.load_paths = env.load_path

    env.register('css_all',
                 assets.Bundle('app.scss',
                               filters=(sass,),
                               depends=(os.path.join(app.config['STATIC_PATH'],
                                        'scss/**/*.scss')),
                               output='app.css'))

    # i18n Config
    babel = Babel(app)

    @app.url_defaults
    def set_language_code(endpoint, values):
        if 'lang_code' in values or not g.get('lang_code', None):
            return
        if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
            values['lang_code'] = g.lang_code

    @app.url_value_preprocessor
    def get_lang_code(endpoint, values):
        if values is not None:
            g.lang_code = values.pop('lang_code', None)

    @app.before_request
    def ensure_lang_support():
        lang_code = g.get('lang_code', None)
        if lang_code and lang_code not in app.config['LANGUAGES'].keys():
            return abort(404)

    @babel.localeselector
    def get_locale():
        return g.get('lang_code', app.config['BABEL_DEFAULT_LOCALE'])

    @babel.timezoneselector
    def get_timezone():
        return app.config['BABEL_DEFAULT_TIMEZONE']

    @app.context_processor
    def utility_processor():
        def get_talk(slug):
            return filters.get_talk(slug)
        return dict(get_talk=get_talk)

    # Register the Blueprints
    app.register_blueprint(view_pages, url_prefix='/<lang_code>')
    app.register_blueprint(view_schedule, url_prefix='/<lang_code>/schedule')

    # Register the filters
    app.jinja_env.filters['format_datetime'] = filters.format_datetime
    app.jinja_env.filters['format_date'] = filters.format_date
    app.jinja_env.filters['format_time'] = filters.format_time

    return app
#!/usr/bin/env python3
""" Get locale from request
"""
from flask import Flask, render_template, request
from flask_babel import Babel

app = Flask(__name__)
babel = Babel(app)


class Config(object):
    """ Class config
    """
    LANGUAGES = ['en', 'fr']
    BABEL_DEFAULT_LOCALE = 'en'
    BABEL_DEFAULT_TIMEZONE = 'UTC'


app.config.from_object(Config)


@babel.localeselector
def get_locale():
    """ Function with the babel.localeselector decorator
    """
    return request.accept_languages.best_match(app.config['LANGUAGES'])


@app.route('/', methods=['GET'], strict_slashes=False)
def index():
    """ Basic Flask app index
Example #32
0
from flask import Flask, render_template
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_mysqldb import MySQL
#from flask_migrate import Migrate
from flask_babel import Babel, lazy_gettext as _l
import json
import pandas as pd
import numpy as np
import os, base64, re, logging

AppServer = Flask(__name__)

AppServer.config.from_object(Config)
db = SQLAlchemy(AppServer)
babel = Babel()
babel.init_app(AppServer)

#migrate = Migrate(AppServer, db)

import routes
Example #33
0
from flask import Flask, render_template, request, redirect, url_for, flash, session, redirect   
from lynx import create_app, db
from flask_login import current_user
from lynx.services.mail_api import send_email
from flask_babel import Babel

app = create_app()
babel = Babel(app) #language support

@babel.localeselector
def get_locale():
    if current_user.is_authenticated:
        return current_user.user_lang or 'en'
    else:
        if session.get('userlang'):
            lng = session.get('userlang') or 'en'
        else:
            lng = request.accept_languages.best_match(app.config['LANGUAGES'].keys())
            session['userlang'] = lng
        return lng

@app.route('/')
@app.route('/home')
def home():
    try:
        if current_user.is_authenticated:
            return redirect(url_for('dashboard.dashboard'))

        langs = []
        for lng in app.config['LANGUAGES'].items(): # items gives both: app.config['LANGUAGES'].keys() and .values()
            langs.append(lng)
Example #34
0
 def __init__(self, app=None):
     self._locale = TCC3Babel.DEFAULT_LOCALE
     self.babel = Babel()
     if app is not None:
         self.init_app(app)
Example #35
0
File: app.py Project: tuna/registr
app.config.update(
    SQLALCHEMY_TRACK_MODIFICATIONS=False,  # As suggested by flask_sqlalchemy
)

# retrieve configuration from environment
Settings(app, rules={
    "BABEL_DEFAULT_LOCALE": (str, "en_US"),
    "SQLALCHEMY_DATABASE_URI": str,
    "BASIC_AUTH_USERNAME": str,
    "BASIC_AUTH_PASSWORD": str,
    "SECRET_KEY": str,
    "DEBUG": (bool, False),
})

babel = Babel()

app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')
app.jinja_env.globals['_'] = _
babel.init_app(app)

all_locales = babel.list_translations() + [Locale('en', 'US')]


@babel.localeselector
def get_locale():
    # Try to retrieve locale from query strings.
    locale = request.args.get('locale', None)
    if locale is not None:
        session["locale"] = locale
        return locale
Example #36
0
def get_app(config=None,
            media_storage=None,
            config_object=None,
            init_elastic=None):
    """App factory.

    :param config: configuration that can override config from ``default_settings.py``
    :param media_storage: media storage class to use
    :param config_object: config object to load (can be module name, module or an object)
    :param init_elastic: obsolete config - kept there for BC
    :return: a new SuperdeskEve app instance
    """

    abs_path = SUPERDESK_PATH
    app_config = flask.Config(abs_path)
    app_config.from_object("superdesk.default_settings")
    app_config.setdefault("APP_ABSPATH", abs_path)
    app_config.setdefault("DOMAIN", {})
    app_config.setdefault("SOURCES", {})

    if config_object:
        app_config.from_object(config_object)

    try:
        app_config.update(config or {})
    except TypeError:
        app_config.from_object(config)

    if not media_storage:
        media_storage = get_media_storage_class(app_config)

    app = SuperdeskEve(
        data=SuperdeskDataLayer,
        auth=TokenAuth,
        media=media_storage,
        settings=app_config,
        json_encoder=SuperdeskJSONEncoder,
        validator=SuperdeskValidator,
        template_folder=os.path.join(abs_path, "templates"),
    )

    app.notification_client = None

    app.jinja_options = {"autoescape": False}
    app.json_encoder = SuperdeskJSONEncoder  # seems like eve param doesn't set it on flask

    # init client_config with default config
    app.client_config = {
        "content_expiry_minutes": app.config.get("CONTENT_EXPIRY_MINUTES", 0),
        "ingest_expiry_minutes": app.config.get("INGEST_EXPIRY_MINUTES", 0),
    }

    superdesk.app = app

    custom_loader = jinja2.ChoiceLoader([
        jinja2.FileSystemLoader("templates"),
        jinja2.FileSystemLoader(os.path.join(SUPERDESK_PATH, "templates")),
    ])

    app.jinja_loader = custom_loader
    app.mail = Mail(app)
    app.sentry = SuperdeskSentry(app)

    # setup babel
    app.config.setdefault("BABEL_TRANSLATION_DIRECTORIES",
                          os.path.join(SUPERDESK_PATH, "translations"))
    app.babel_tzinfo = None
    app.babel_locale = None
    app.babel_translations = None
    babel = Babel(app, configure_jinja=False)

    @babel.localeselector
    def get_locale():
        user = getattr(g, "user", {})
        user_language = user.get("language",
                                 app.config.get("DEFAULT_LANGUAGE", "en"))
        try:
            # Attempt to load the local using Babel.parse_local
            parse_locale(user_language.replace("-", "_"))
        except ValueError:
            # If Babel fails to recognise the locale, then use the default language
            user_language = app.config.get("DEFAULT_LANGUAGE", "en")

        return user_language.replace("-", "_")

    set_error_handlers(app)

    @app.after_request
    def after_request(response):
        # fixing previous media prefixes if defined
        if app.config["MEDIA_PREFIXES_TO_FIX"] and app.config["MEDIA_PREFIX"]:
            current_prefix = app.config["MEDIA_PREFIX"].rstrip("/").encode()
            for prefix in app.config["MEDIA_PREFIXES_TO_FIX"]:
                response.data = response.data.replace(
                    prefix.rstrip("/").encode(), current_prefix)
        return response

    init_celery(app)
    installed = set()

    def install_app(module_name):
        if module_name in installed:
            return
        installed.add(module_name)
        app_module = importlib.import_module(module_name)
        if hasattr(app_module, "init_app"):
            app_module.init_app(app)

    for module_name in app.config.get("CORE_APPS", []):
        install_app(module_name)

    for module_name in app.config.get("INSTALLED_APPS", []):
        install_app(module_name)

    for resource in superdesk.DOMAIN:
        app.register_resource(resource, superdesk.DOMAIN[resource])

    for name, jinja_filter in superdesk.JINJA_FILTERS.items():
        app.jinja_env.filters[name] = jinja_filter

    configure_logging(app.config["LOG_CONFIG_FILE"])

    return app
Example #37
0
def make_flask_stack(conf, **app_conf):
    """ This has to pass the flask app through all the same middleware that
    Pylons used """

    root = os.path.dirname(
        os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

    debug = asbool(app_conf.get('debug', app_conf.get('DEBUG', False)))
    testing = asbool(app_conf.get('testing', app_conf.get('TESTING', False)))

    app = flask_app = CKANFlask(__name__)
    app.debug = debug
    app.testing = testing
    app.template_folder = os.path.join(root, 'templates')
    app.app_ctx_globals_class = CKAN_AppCtxGlobals
    app.url_rule_class = CKAN_Rule

    # Update Flask config with the CKAN values. We use the common config
    # object as values might have been modified on `load_environment`
    if config:
        app.config.update(config)
    else:
        app.config.update(conf)
        app.config.update(app_conf)

    # Do all the Flask-specific stuff before adding other middlewares

    # Secret key needed for flask-debug-toolbar and sessions
    if not app.config.get('SECRET_KEY'):
        app.config['SECRET_KEY'] = config.get('beaker.session.secret')
    if not app.config.get('SECRET_KEY'):
        raise RuntimeError(u'You must provide a value for the secret key'
                           ' with the SECRET_KEY config option')

    if debug:
        from flask_debugtoolbar import DebugToolbarExtension
        app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
        DebugToolbarExtension(app)

    # Use Beaker as the Flask session interface
    class BeakerSessionInterface(SessionInterface):
        def open_session(self, app, request):
            if 'beaker.session' in request.environ:
                return request.environ['beaker.session']

        def save_session(self, app, session, response):
            session.save()

    namespace = 'beaker.session.'
    session_opts = dict([(k.replace('beaker.', ''), v)
                        for k, v in config.iteritems()
                        if k.startswith(namespace)])
    if (not session_opts.get('session.data_dir') and
            session_opts.get('session.type', 'file') == 'file'):
        cache_dir = app_conf.get('cache_dir') or app_conf.get('cache.dir')
        session_opts['session.data_dir'] = '{data_dir}/sessions'.format(
                data_dir=cache_dir)

    app.wsgi_app = SessionMiddleware(app.wsgi_app, session_opts)
    app.session_interface = BeakerSessionInterface()

    # Add Jinja2 extensions and filters
    extensions = [
        'jinja2.ext.do', 'jinja2.ext.with_',
        jinja_extensions.SnippetExtension,
        jinja_extensions.CkanExtend,
        jinja_extensions.CkanInternationalizationExtension,
        jinja_extensions.LinkForExtension,
        jinja_extensions.ResourceExtension,
        jinja_extensions.UrlForStaticExtension,
        jinja_extensions.UrlForExtension
    ]
    for extension in extensions:
        app.jinja_env.add_extension(extension)
    app.jinja_env.filters['empty_and_escape'] = \
        jinja_extensions.empty_and_escape

    # Common handlers for all requests
    app.before_request(ckan_before_request)
    app.after_request(ckan_after_request)

    # Template context processors
    app.context_processor(helper_functions)
    app.context_processor(c_object)

    @app.context_processor
    def ungettext_alias():
        u'''
        Provide `ungettext` as an alias of `ngettext` for backwards
        compatibility
        '''
        return dict(ungettext=ungettext)

    # Babel
    app.config[u'BABEL_TRANSLATION_DIRECTORIES'] = os.path.join(root, u'i18n')
    app.config[u'BABEL_DOMAIN'] = 'ckan'

    babel = Babel(app)

    babel.localeselector(get_locale)

    @app.route('/hello', methods=['GET'])
    def hello_world():
        return 'Hello World, this is served by Flask'

    @app.route('/hello', methods=['POST'])
    def hello_world_post():
        return 'Hello World, this was posted to Flask'

    # Auto-register all blueprints defined in the `views` folder
    _register_core_blueprints(app)

    # Set up each IBlueprint extension as a Flask Blueprint
    for plugin in PluginImplementations(IBlueprint):
        if hasattr(plugin, 'get_blueprint'):
            app.register_extension_blueprint(plugin.get_blueprint())

    # Start other middleware
    for plugin in PluginImplementations(IMiddleware):
        app = plugin.make_middleware(app, config)

    # Fanstatic
    if debug:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': True,
            'minified': False,
            'bottom': True,
            'bundle': False,
        }
    else:
        fanstatic_config = {
            'versioning': True,
            'recompute_hashes': False,
            'minified': True,
            'bottom': True,
            'bundle': True,
        }
    root_path = config.get('ckan.root_path', None)
    if root_path:
        root_path = re.sub('/{{LANG}}', '', root_path)
        fanstatic_config['base_url'] = root_path
    app = Fanstatic(app, **fanstatic_config)

    for plugin in PluginImplementations(IMiddleware):
        try:
            app = plugin.make_error_log_middleware(app, config)
        except AttributeError:
            log.critical('Middleware class {0} is missing the method'
                         'make_error_log_middleware.'
                         .format(plugin.__class__.__name__))

    # Initialize repoze.who
    who_parser = WhoConfig(conf['here'])
    who_parser.parse(open(app_conf['who.config_file']))

    app = PluggableAuthenticationMiddleware(
        app,
        who_parser.identifiers,
        who_parser.authenticators,
        who_parser.challengers,
        who_parser.mdproviders,
        who_parser.request_classifier,
        who_parser.challenge_decider,
        logging.getLogger('repoze.who'),
        logging.WARN,  # ignored
        who_parser.remote_user_key
    )

    # Update the main CKAN config object with the Flask specific keys
    # that were set here or autogenerated
    flask_config_keys = set(flask_app.config.keys()) - set(config.keys())
    for key in flask_config_keys:
        config[key] = flask_app.config[key]

    # Add a reference to the actual Flask app so it's easier to access
    app._wsgi_app = flask_app

    return app
Example #38
0
 def create_app(self):
     app = Flask(__name__)
     babel = Babel(app, default_locale='fr', default_timezone=USER_TZ)
     babel.localeselector(en_locale)
     babel.timezoneselector(user_tz)
     return app
def init(babel: Babel) -> None:
    LANGUAGES.extend([str(locale) for locale in babel.list_translations()])
    babel.localeselector(get_locale)
Example #40
0
def create_app(config_name=None):

    if config_name == None:
        config_name = "production"

    app = Flask(__name__, template_folder="templates")

    # https://trstringer.com/logging-flask-gunicorn-the-manageable-way/
    if(config_name == "production"):
        gunicorn_logger = logging.getLogger("gunicorn.error")
        app.logger.handlers = gunicorn_logger.handlers
        app.logger.setLevel(gunicorn_logger.level)

    config_module = f"lightbluetent.config.{config_name.capitalize()}Config"

    app.config.from_object(config_module)

    if not app.secret_key and "FLASK_SECRET_KEY" in os.environ:
        app.secret_key = os.environ["FLASK_SECRET_KEY"]

    if not app.request_class.trusted_hosts and "FLASK_TRUSTED_HOSTS" in os.environ:
        app.request_class.trusted_hosts = os.environ["FLASK_TRUSTED_HOSTS"].split(",")

    app.config["CSRF_CHECK_REFERER"] = False
    csrf = SeaSurf(app)
    csp = {
        "default-src": ["'self'", "www.srcf.net"],
        "img-src": ["'self'", "data:", "www.srcf.net"],
        'style-src': [
            '\'self\'',
            '\'unsafe-inline\'',
            'www.srcf.net'
        ]
    }
    Talisman(app, content_security_policy=csp)

    babel = Babel(app)

    app.jinja_env.globals["sif"] = sif
    app.jinja_env.globals["gen_unique_string"] = gen_unique_string
    app.jinja_env.globals["ordinal"] = ordinal

    from lightbluetent.models import db, migrate

    db.init_app(app)
    migrate.init_app(app, db)

    app.register_blueprint(admin.bp)
    app.register_blueprint(home.bp)
    app.register_blueprint(society.bp)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, server_error)

    @app.context_processor
    def inject_gh_rev():
        return dict(
            github_rev=subprocess.check_output(["git", "describe", "--tags"])
            .strip()
            .decode()
        )

    return app
Example #41
0
 def _setup_babel(self):
     # avoid events on this
     self.babel_tzinfo = None
     self.babel_locale = None
     self.babel_translations = None
     Babel(self)
Example #42
0
from flask_babel import Babel

from layout import initialize_app
from common import cache

os.environ['DASH_PRUNE_ERRORS'] = 'False'
os.environ['DASH_SILENCE_ROUTES_LOGGING'] = 'False'

app = dash.Dash(__name__)
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True

server = app.server
with server.app_context():
    server.config.from_object('common.settings')

    cache.init_app(server)

    sess = Session()
    sess.init_app(server)

    babel = Babel(server)

initialize_app(app)

if __name__ == '__main__':
    # Write the process pid to a file for easier profiling with py-spy
    with open('.ghgdash.pid', 'w') as pid_file:
        pid_file.write(str(os.getpid()))
    app.run_server(debug=True)
Example #43
0
def app(request):
    app = Flask(__name__)
    app.response_class = Response
    app.debug = True
    app.config["SECRET_KEY"] = "secret"
    app.config["TESTING"] = True
    app.config["LOGIN_DISABLED"] = False
    app.config["WTF_CSRF_ENABLED"] = False
    # Our test emails/domain isn't necessarily valid
    app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {
        "check_deliverability": False
    }
    app.config["SECURITY_TWO_FACTOR_SECRET"] = {
        "1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B"
    }
    app.config["SECURITY_SMS_SERVICE"] = "test"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    app.config["SECURITY_PASSWORD_SALT"] = "salty"
    # Make this plaintext for most tests - reduces unit test time by 50%
    app.config["SECURITY_PASSWORD_HASH"] = "plaintext"
    # Make this hex_md5 for token tests
    app.config["SECURITY_HASHING_SCHEMES"] = ["hex_md5"]
    app.config["SECURITY_DEPRECATED_HASHING_SCHEMES"] = []

    for opt in [
            "changeable",
            "recoverable",
            "registerable",
            "trackable",
            "passwordless",
            "confirmable",
            "two_factor",
            "unified_signin",
    ]:
        app.config["SECURITY_" + opt.upper()] = opt in request.keywords

    pytest_major = int(pytest.__version__.split(".")[0])
    if pytest_major >= 4:
        marker_getter = request.node.get_closest_marker
    else:
        marker_getter = request.keywords.get
    settings = marker_getter("settings")
    babel = marker_getter("babel")
    if settings is not None:
        for key, value in settings.kwargs.items():
            app.config["SECURITY_" + key.upper()] = value

    mail = Mail(app)
    if not NO_BABEL and (babel is None or babel.args[0]):
        Babel(app)
    app.json_encoder = JSONEncoder
    app.mail = mail

    @app.route("/")
    def index():
        return render_template("index.html", content="Home Page")

    @app.route("/profile")
    @auth_required()
    def profile():
        if hasattr(app, "security"):
            if app.security._want_json(flask_request):
                return jsonify(message="profile")

        return render_template("index.html", content="Profile Page")

    @app.route("/post_login")
    @login_required
    def post_login():
        return render_template("index.html", content="Post Login")

    @app.route("/http")
    @http_auth_required
    def http():
        return "HTTP Authentication"

    @app.route("/http_admin_required")
    @http_auth_required
    @permissions_required("admin")
    def http_admin_required():
        assert get_request_attr("fs_authn_via") == "basic"
        return "HTTP Authentication"

    @app.route("/http_custom_realm")
    @http_auth_required("My Realm")
    def http_custom_realm():
        assert get_request_attr("fs_authn_via") == "basic"
        return render_template("index.html", content="HTTP Authentication")

    @app.route("/token", methods=["GET", "POST"])
    @auth_token_required
    def token():
        assert get_request_attr("fs_authn_via") == "token"
        return render_template("index.html", content="Token Authentication")

    @app.route("/multi_auth")
    @auth_required("session", "token", "basic")
    def multi_auth():
        return render_template("index.html",
                               content="Session, Token, Basic auth")

    @app.route("/post_logout")
    def post_logout():
        return render_template("index.html", content="Post Logout")

    @app.route("/post_register")
    def post_register():
        return render_template("index.html", content="Post Register")

    @app.route("/post_confirm")
    def post_confirm():
        return render_template("index.html", content="Post Confirm")

    @app.route("/admin")
    @roles_required("admin")
    def admin():
        assert get_request_attr("fs_authn_via") == "session"
        return render_template("index.html", content="Admin Page")

    @app.route("/admin_and_editor")
    @roles_required("admin", "editor")
    def admin_and_editor():
        return render_template("index.html", content="Admin and Editor Page")

    @app.route("/admin_or_editor")
    @roles_accepted("admin", "editor")
    def admin_or_editor():
        return render_template("index.html", content="Admin or Editor Page")

    @app.route("/simple")
    @roles_accepted("simple")
    def simple():
        return render_template("index.html", content="SimplePage")

    @app.route("/admin_perm")
    @permissions_accepted("full-write", "super")
    def admin_perm():
        return render_template("index.html",
                               content="Admin Page with full-write or super")

    @app.route("/admin_perm_required")
    @permissions_required("full-write", "super")
    def admin_perm_required():
        return render_template("index.html", content="Admin Page required")

    @app.route("/page1")
    def page_1():
        return "Page 1"

    @app.route("/json", methods=["GET", "POST"])
    def echo_json():
        return jsonify(flask_request.get_json())

    @app.route("/unauthz", methods=["GET", "POST"])
    def unauthz():
        return render_template("index.html", content="Unauthorized")

    @app.route("/fresh", methods=["GET", "POST"])
    @auth_required(within=0)
    def fresh():
        if app.security._want_json(flask_request):
            return jsonify(title="Fresh Only")
        else:
            return render_template("index.html", content="Fresh Only")

    return app
Example #44
0
    def __init__(self, conf, init):

        # import configuration_file from parametes
        self.host = conf['host']
        self.port = conf['port']
        self.debug_mode = conf['debug_mode']

        # use Flask as app and set app configuration :
        self.app = Flask(__name__)
        self.app.config[
            'SQLALCHEMY_DATABASE_URI'] = 'sqlite:///models/sqlite_file/bdd.dl'
        self.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
        self.app.config['BABEL_DEFAULT_LOCALE'] = 'en'
        # self.app.config['SECRET_KEY'] = os.urandom(16)
        self.app.config['SECRET_KEY'] = 'test_key'

        # use Babel
        # see doc : https://pythonhosted.org/Flask-Babel/
        self.babel = Babel(self.app)

        # use SQLAlchemy
        # see doc : http://flask-sqlalchemy.pocoo.org/2.3/
        self.bdd = bdd.bdd(self.app)

        # use Flask session
        # see doc : https://pythonhosted.org/Flask-Session/

        # use managers :
        self.inventory_manager = Inventory(conf['ansible_dir_path'],
                                           conf['inventory_file_subpath'])
        # self.inventory_manager = Inventory()
        self.users_and_users_groups_manager = Users_and_users_groups_manager()
        self.manage_validator = Validator()
        self.permissions_manager = Permissions_manager(
            self.users_and_users_groups_manager, self.inventory_manager)

        # set global vars (lang):
        # use app_context -> see doc : http://flask.pocoo.org/docs/1.0/appcontext/ for details
        with self.app.app_context():
            g.lang = self.app.config['BABEL_DEFAULT_LOCALE']

        # print(self.users_and_users_groups_manager.add_user(
        #                                             conf['default_user'],
        #                                             conf['hash'],
        #                                             True
        #                                             ))
        #
        #
        # if init:
        #     self.users_and_users_groups_manager.add_user(
        #                                                 conf['default_user'],
        #                                                 conf['hash'],
        #                                                 True
        #                                                 )
        #
        #     self.users_and_users_groups_manager.add_users_group('group-1')
        #     self.users_and_users_groups_manager.add_user_in_users_group(
        #                                                                 conf['default_user'],
        #                                                                 'group-1'
        #                                                                 )
        #     self.inventory_manager.add_group('nodes-group-1')
        #
        #     self.permissions_manager.init_permission(
        #                                             'group-1',
        #                                             'nodes-group-1',
        #                                             {
        #                                                 'read': True,
        #                                                 'write':True,
        #                                                 'execute':True
        #                                             }
        #                                             )
        # if hash('DL_Lib_56270.') == conf['hash']:
        #     print('manage.py : line 93 : hash valid')

        print(
            self.users_and_users_groups_manager.add_user(
                conf['default_user'], conf['hash'], True))
        # vars_dict ={"var1": "value1", "var2": "value2"}
        # self.inventory_manager.set_node_by_name_vars_dict(self, "node1", vars_dict)
        # print(self.users_and_users_groups_manager.get_user('admin'))
        #
        #

        # print(self.inventory_manager.add_node("node1"))
        # print(self.inventory_manager.add_node("node1"))
        # print(self.inventory_manager.add_node("node2"))
        # print(self.inventory_manager.add_node("node3"))
        # print(self.inventory_manager.add_group("group1"))
        # print(self.inventory_manager.add_group("group2"))
        # print(self.inventory_manager.add_group("group3"))
        #
        # print(self.inventory_manager.add_node("node5"))
        # print(self.inventory_manager.add_node("node6"))
        # print(self.inventory_manager.add_node("node7"))
        # print(self.inventory_manager.add_node("node8"))
        # print(self.inventory_manager.add_group("group5"))
        # print(self.inventory_manager.add_group("group6"))
        # print(self.inventory_manager.add_group("group7"))
        #
        #
        # print(self.inventory_manager.set_group_by_name_vars_dict("group2", {"var1": "value1", "var2": "value2"}))
        # print(self.inventory_manager.set_group_by_name_vars_dict("group1", {"var1": "value1", "var2": "value2"}))
        # print(self.inventory_manager.get_group_by_name_vars_dict("group2"))
        # print(self.inventory_manager.update_group_by_name_var("group2", "var1", "value1updated"))
        # print(self.inventory_manager.get_group_by_name_value("group2", "var1"))
        # print(self.inventory_manager.get_group_by_name_vars_dict("group2"))
        # print(self.inventory_manager.get_nodes_names_not_in_group_by_name("group2"))
        # print(self.inventory_manager.add_node_name_in_group_name("node2", "group2"))
        # print(self.inventory_manager.add_node_name_in_group_name("node", "group1"))
        # print(self.inventory_manager.get_nodes_not_in_group_by_name("group2"))
        # print(self.inventory_manager.get_nodes_names_not_in_group_by_name("group2"))
        # print(self.inventory_manager.get_nodes_names_in_group_by_name("group2"))
        # print(self.inventory_manager.get_nodes_names_not_in_group_by_name("group2"))

        # print(self.inventory_manager.remove_node_name_in_group_name("node2", "group2"))
        # print(self.inventory_manager.get_nodes_names_not_in_group_by_name("group2"))
        # print(self.inventory_manager.add_node_name_in_group_name("node2", "group2"))
        # print("")

        # use views :
        self.__define_views()

        # finally start the server
        self.__run_server()

        # override babel locale :
        # g.lang define with globals
        @self.babel.localeselector
        def get_locale():
            return g.lang