예제 #1
0
def configure_i18n(app):
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        accept_languages = app.config.get('ACCEPT_LANGUAGES',
                                          ['en_US', 'zh_CN', 'zh_TW', 'ja_JP'])
        return request.accept_languages.best_match(accept_languages)
예제 #2
0
def configure_i18n(app):
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        accept_languages = app.config.get('ACCEPT_LANGUAGES', ['en_GB'])
        return request.accept_languages.best_match(accept_languages,
            default=accept_languages[0])
예제 #3
0
def init_i18n(app):

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        lan = app.config.get('ACCEPT_LANGUAGES', ['zh'])
        return request.accept_languages.best_match(lan)
예제 #4
0
def init_app(extra_config_settings={}):
    # Initialize app config settings
    app.config.from_object(
        'config.settings')  # Read config from 'app/settings.py' file
    app.config.update(extra_config_settings
                      )  # Overwrite with 'extra_config_settings' parameter
    if app.testing:
        app.config[
            'WTF_CSRF_ENABLED'] = False  # Disable CSRF checks while testing
    if os.environ['EASE_DEBUG'] == 'true':
        app.config['DEBUG'] = True
        app.config['SECRET_KEY'] = app.config['DEV_SECRET_KEY']
    else:
        try:
            app.config['SECRET_KEY'] = open('/etc/ease_secret/secret',
                                            'rb').read()
        except IOError:
            app.config['SECRET_KEY'] = random_string(64)

    # Setup Flask-Mail
    mail = Mail(app)
    babel = Babel(app)

    # Setup Flask-User to handle user account related forms
    from postgres.users import User
    db_adapter = SQLAlchemyAdapter(db, User)
    # Init Flask-User and bind to app
    app.user_manager = UserManager(db_adapter,
                                   app,
                                   password_validator=oe_password_validator)

    # Load all models.py files to register db.Models with SQLAlchemy
    from postgres import users
    from postgres import settings
    # Automatically create all registered DB tables
    db.create_all()
    db.session.commit()

    for role in USER_ROLES:
        create_role(role)

    # Load all views.py files to register @app.routes() with Flask
    from pages import main
    from pages import api
    from pages import neem_discovery
    from pages import editor
    from pages import tutorials
    from pages import oauth

    add_user(user_manager=app.user_manager,
             name='admin',
             mail=os.environ.get('OPENEASE_MAIL_USERNAME',
                                 '*****@*****.**'),
             pw=ADMIN_USER_DEFAULT_PW,
             roles=['admin'])

    app.logger.info("Webapp started.")
    return app
예제 #5
0
    def initialise(self):
        """
        The application needs initialisation to load the database
        connection etc. In previous versions this was done with the
        initialisation of the class in the __init__ method. This is
        now separated into this function.
        """
        #: Check if the secret key is defined, if not raise an
        #: exception since it is required
        assert self.secret_key, 'Secret Key is not defined in config'

        #: Load the cache
        self.load_cache()

        #: Initialise the CSRF handling
        self.csrf_protection = NereidCsrfProtect()
        self.csrf_protection.init_app(self)

        self.view_functions['static'] = self.send_static_file

        # Backend initialisation
        self.load_backend()

        #: Initialise the login handler
        login_manager = LoginManager()
        login_manager.user_loader(self._pool.get('nereid.user').load_user)
        login_manager.header_loader(
            self._pool.get('nereid.user').load_user_from_header)
        login_manager.token_loader(
            self._pool.get('nereid.user').load_user_from_token)
        login_manager.unauthorized_handler(
            self._pool.get('nereid.user').unauthorized_handler)
        login_manager.login_view = "nereid.website.login"
        login_manager.anonymous_user = self._pool.get('nereid.user.anonymous')
        login_manager.init_app(self)

        self.login_manager = login_manager

        # Monkey patch the url_for method from flask-login to use
        # the nereid specific url_for
        flask.ext.login.url_for = url_for

        self.template_context_processors[None].append(
            self.get_context_processors())

        # Add the additional template context processors
        self.template_context_processors[None].append(
            nereid_default_template_ctx_processor)

        # Add template_filters registered using decorator
        for name, function in self.get_template_filters():
            self.jinja_env.filters[name] = function

        # Initialize Babel
        Babel(self)

        # Finally set the initialised attribute
        self.initialised = True
예제 #6
0
def configure_extensions(app):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-mail
    mail.init_app(app)

    # flask-cache
    cache.init_app(app)

    # flask-babel
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        #TODO, first check user config?
        g.accept_languages = app.config.get('ACCEPT_LANGUAGES')
        accept_languages = g.accept_languages.keys()
        browser_default = request.accept_languages.best_match(accept_languages)
        if 'language' in session:
            language = session['language']
            #current_app.logger.debug('lang from session: %s' % language)
            if not language in accept_languages:
                #clear it
                #current_app.logger.debug('invalid %s, clearing' % language)
                session['language'] = None
                language = browser_default
        else:
            language = browser_default
            #current_app.logger.debug('lang from browser: %s' % language)
        session['language'] = language #save it to session

        #and to user?
        return language

    # flask-login
    login_manager.login_view = 'frontend.login'
    login_manager.refresh_view = 'frontend.reauth'

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(id)
    login_manager.setup_app(app)

    # flask-openid
    oid.init_app(app)

    # csrf for wtforms
    #from flask.ext.wtf import csrf
    csrf.init_app(app)
    
    # flask-restless
    rest.init_app(app, flask_sqlalchemy_db=db)
    restless_routes() #actually setup the routes

    # flask-admin
    admin = Admin(app, name='RootIO Backend', index_view=AdminHomeView())
    admin_routes(admin) #add flask-admin classes
예제 #7
0
파일: settings.py 프로젝트: sucan163/sense
def configure_i18n(app):
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        language = request.values.get("lan")
        if not language:
            language = request.cookies.get("lan", "zh")
        return language
예제 #8
0
def create_app():
    create_db()
    Babel(app)
    Mail(app)
    db_adapter = SQLAlchemyAdapter(db, models.User)
    UserManager(db_adapter, app)
    searcher = Searcher()
    init_routes(app, db.session, searcher)
    return app
예제 #9
0
def create_app(config='dev'):
    """ Flask application factory
    :param str config: type of app to build, either "prod" or "dev"
    """
    # Create flask application
    app = Flask(__name__)
    app.config.from_object('settings')
    app.config['ENV'] = config
    app.jinja_env.trim_blocks = True

    # Debug toolbar (when debug=true)
    debug_toolbar = DebugToolbarExtension(app)
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False

    # Register Blueprints
    app.register_blueprint(views_base.base)
    app.register_blueprint(views_blog.blog)

    # Flask-Assets; bundles all css/js files in minifed file
    assets = Environment(app)
    css_all = Bundle('css/bootstrap-flatly.min.css', 'css/highlightjs.min.css', 'css/font-awesome.css', 'css/main.css',
                     filters='cssmin', output='gen/style.css')
    js_all = Bundle('js/vendor/jquery.min.js', 'js/vendor/bootstrap.min.js', 'js/vendor/showdown-gfm.min.js',
                    'js/vendor/highlight.min.js', 'js/main.js', filters='jsmin', output='gen/libs.js')
    assets.register('css_all', css_all)
    assets.register('js_all', js_all)
    if app.config['DEBUG']:
        assets.debug = True
        app.config['ASSETS_DEBUG'] = True

    # Set up Flask-User
    babel = Babel(app)
    db_adapter = SQLAlchemyAdapter(db, User)
    user_manager = UserManager(db_adapter, app)  # Init Flask-User and bind to app

    # Init the cache
    cache.init_app(app)

    Moment(app)  # moment.js
    Misaka(app, autolink=True,  # Misaka Markdown
           fenced_code=True, lax_html=True, strikethrough=True,
           superscript=True, tables=True, wrap=True)

    # Init Admin page
    admin = Admin(app, index_view=AdminMain(endpoint='admin'))
    admin.add_view(PostAdminView())
    admin.add_view(NewPostView())
    admin.add_view(ModelView(Comment, db.session))
    static_path = os.path.join(BASE_DIR, 'app', 'static')
    admin.add_view(FileAdminView(static_path, '/static/', name='Static Files'))

    # Initialize DB
    db.init_app(app)

    return app
예제 #10
0
    def init_app(self, app):

        self.app = app

        app.config.setdefault('CSRF_ENABLED', True)
        app.config.setdefault('SENTRY_ENABLED', False)
        app.config.setdefault('BEHIND_REVERSE_PROXY', False)
        app.config.setdefault('REDIS_SESSIONS_ENABLED', False)
        app.config.setdefault('REDIS_SESSIONS_DB', 1)
        app.config.setdefault('REDIS_SESSIONS_HOST', '127.0.0.1')
        app.config.setdefault('REDIS_SESSIONS_PORT', 6379)
        app.config.setdefault('REDIS_SESSIONS_PICKLE_PROTO', 3)
        app.config.setdefault('BABEL_ENABLED', False)

        bp = Blueprint('boilerplate', __name__, template_folder='templates')
        self.app.register_blueprint(bp)

        # Inject various globals into jinja
        app.jinja_env.globals['csrf_setup'] = csrf_setup
        app.jinja_env.globals['render_field'] = render_field
        app.jinja_env.filters['percent_escape'] = percent_escape
        app.jinja_env.filters['time_since'] = timesince

        if app.config.get('CSRF_ENABLED'):
            from flask_wtf.csrf import CsrfProtect
            app.csrf = CsrfProtect(app)

        if app.config.get('BEHIND_REVERSE_PROXY'):
            from .ReverseProxied import ReverseProxied
            app.wsgi_app = ReverseProxied(app.wsgi_app)

        if app.config.get('SENTRY_ENABLED') and not app.debug:
            from raven.contrib.flask import Sentry
            app.sentry = Sentry(app)

        if app.config.get('REDIS_SESSIONS_ENABLED'):
            from .RedisSessionInterface import RedisSessionInterface
            from redis import Redis

            redis = Redis(host=app.config.get('REDIS_SESSIONS_HOST'),
                          port=app.config.get('REDIS_SESSIONS_PORT'),
                          db=app.config.get('REDIS_SESSIONS_DB'))
            app.session_interface = RedisSessionInterface(
                redis=redis,
                pickle_protocol=app.config.get('REDIS_SESSIONS_PICKLE_PROTO'))

        if app.config.get('BABEL_ENABLED'):
            from flask.ext.babel import Babel
            from .filters import local_date, local_date_time
            app.babel = Babel(app)
            app.jinja_env.filters['local_date'] = local_date
            app.jinja_env.filters['local_date_time'] = local_date_time

        return True
예제 #11
0
def configure_extensions(app):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-babel
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        accept_languages = app.config.get('ACCEPT_LANGUAGES')
        return request.accept_languages.best_match(accept_languages)
예제 #12
0
def create_app():
    """Create an application."""
    app = Flask(__name__)
    app.config.from_object('flaskberry.settings')
    load_modules(app)

    socketio.init_app(app)

    babel = Babel(app)
    babel.locale_selector_func = get_locale
    return app
예제 #13
0
def register_babel(app):
    from flask.ext.babel import Babel

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        app.config.setdefault('BABEL_SUPPORTED_LOCALES', ['en', 'zh'])
        app.config.setdefault('BABEL_DEFAULT_LOCALE', 'en')
        match = app.config['BABEL_SUPPORTED_LOCALES']
        default = app.config['BABEL_DEFAULT_LOCALE']
        return request.accept_languages.best_match(match, default)
예제 #14
0
def register_extensions(app):
	""" All extensions used by the application are registered here """
	# Register database
	db.init_app(app)
	# Flask Babel for translations
	babel = Babel(app)
	@babel.localeselector
	def get_locale():
		accept_languages = app.config.get('ACCEPT_LANGUAGES')
		return request.accept_languages.best_match(accept_languages)
	# Flask Login
	login_manager.setup_app(app)
예제 #15
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'website.login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.load(user_id)

    @app.before_request
    def on_request():
        g.db = database.connect()

    @app.teardown_request
    def on_teardown(exception):
        db = getattr(g, 'db', None)
        if db is not None:
            db.close()

    @app.after_request
    def after_request_calls(response):
        for callback in getattr(g, 'after_request_callbacks', ()):
            callback(response)
        return response

    babel = Babel(app)

    @babel.localeselector
    def select_locale():
        if 'lang' in request.args:
            lang = request.args.get('lang')

            @call_after_request
            def set_cookie(request):
                request.set_cookie('lang', lang, 60 * 60 * 24 * 31 * 12)

            return lang

        return request.cookies.get('lang') or \
               request.accept_languages.best_match(app.config.get('LANGUAGES'))

    from .website import website
    app.register_blueprint(website)

    from .api import api
    app.register_blueprint(api, url_prefix='/api')

    return app
예제 #16
0
파일: init_app.py 프로젝트: winnerus/docker
def init_app(app, db_instance, extra_config_settings={}):
    # Initialize app config settings
    app.config.from_object('webrob.config.settings')        # Read config from 'app/settings.py' file
    app.config.update(extra_config_settings)                # Overwrite with 'extra_config_settings' parameter
    if app.testing:
        app.config['WTF_CSRF_ENABLED'] = False              # Disable CSRF checks while testing
    if os.environ['EASE_DEBUG'] == 'true':
        app.config['DEBUG'] = True
        app.config['SECRET_KEY'] = app.config['DEV_SECRET_KEY']
    else:
        try:
            app.config['SECRET_KEY'] = open('/etc/ease_secret/secret', 'rb').read()
        except IOError:
            app.config['SECRET_KEY'] = random_string(64)

    # Setup Flask-Mail
    mail = Mail(app)

    babel = Babel(app)

    # Setup Flask-User to handle user account related forms
    from webrob.models.users import User
    db_adapter = SQLAlchemyAdapter(db_instance, User)
    user_manager = UserManager(db_adapter, app)     # Init Flask-User and bind to app

    # Load all models.py files to register db.Models with SQLAlchemy
    from webrob.models import users
    from webrob.models import tutorials
    from webrob.models import experiments

    # Load all views.py files to register @app.routes() with Flask
    from webrob.pages import api
    from webrob.pages import db
    from webrob.pages import editor
    from webrob.pages import experiments
    from webrob.pages import knowrob
    from webrob.pages import login
    from webrob.pages import meshes
    from webrob.pages import mongo
    from webrob.pages import tutorials
    
    init_db(app, db_instance)
    init_webapp(app, db_instance)
    
    add_user(app,db_instance,user_manager,'admin',
             os.environ.get('OPENEASE_MAIL_USERNAME', '*****@*****.**'),
             os.environ.get('OPENEASE_ADMIN_PASSWORD'), ['admin'])

    app.logger.info("Webapp started.")
    return app
예제 #17
0
def configure_babel(app):
    # Load additional languages into the babel
    # cache.  We do this so we can add Haitian Creole
    # using french as a model.
    babel_patched_load('cpf')

    # flask-babel
    babel = Babel(app)

    # Wire Babel into the settings
    # and the settings code into Babel
    settings_views.set_babel(babel)
    babel.localeselector(settings_views.current_locale)

    return babel
예제 #18
0
def configure_extensions(app):
    #from simplekv.memory import DictStore
    #from flask.ext.kvsession import KVSessionExtension
    #store = DictStore()
    ## this will replace the app's session handling
    #KVSessionExtension(store, app)
    mongo.init_app(app, "FUNFUNSAY")

    # cache
    cache.init_app(app)

    # babel
    #print "create babel object"
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        # if a user is logged in, use the locale from the user settings
        if current_user.is_authenticated():
            return current_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(['zh_CN', 'en'])

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

    # login.
    from flask.ext.login import LoginManager
    login_manager = LoginManager()
    login_manager.session_protection = None  #@fixme!
    login_manager.login_view = 'homesite.login'
    login_manager.refresh_view = 'homesite.reauth'
    login_manager.login_message = _("Please log in to access this page.")

    @login_manager.user_loader
    def load_user(id):
        #print "####: loaduser ", id
        return User.load_user(id)

    login_manager.setup_app(app)

    from flask.ext.markdown import Markdown
    Markdown(app, safe_mode="escape")
예제 #19
0
def init_app(app, db_instance, extra_config_settings={}):
    _init_app_config_settings(app, extra_config_settings)

    # Setup Flask-Mail
    mail = Mail(app)

    babel = Babel(app)

    # Setup Flask-User to handle user account related forms
    from webrob.models.users import User
    db_adapter = SQLAlchemyAdapter(db_instance, User)
    app.user_manager = UserManager(db_adapter,
                                   app)  # Init Flask-User and bind to app

    # Load all models.py files to register db.Models with SQLAlchemy
    # Needs to remain in code, even if IDEs might show it's unused, Flask will use them during runtime
    from webrob.models import users
    from webrob.models import tutorials
    from webrob.models import teaching
    from webrob.models import experiments

    # Load all views.py files to register @app.routes() with Flask
    # Needs to remain in code, even if IDEs might show it's unused, Flask will use them during runtime
    from webrob.pages import api
    from webrob.pages import db
    from webrob.pages import editor
    from webrob.pages import experiments
    from webrob.pages import knowrob
    from webrob.pages import login
    from webrob.pages import meshes
    from webrob.pages import mongo
    from webrob.pages import tutorials
    from webrob.pages import oauth

    init_db(app, db_instance)
    init_webapp(app, db_instance)

    add_user(app=app,
             db=db_instance,
             user_manager=app.user_manager,
             name='admin',
             mail=evg.get_variable_with_default('OPENEASE_MAIL_USERNAME',
                                                '*****@*****.**'),
             pw=evg.get_required_variable('OPENEASE_ADMIN_PASSWORD'),
             roles=['admin'])

    _log_webapp_started(app)
    return app
예제 #20
0
def create_app(config_file=None):
    app = Flask(__name__)
    app = change_jinja_templates(app)
    if config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar("CLA_PUBLIC_CONFIG")

    if app.config.get("SENTRY_DSN"):
        app.sentry = Sentry(app,
                            dsn=app.config.get("SENTRY_DSN"),
                            logging=True,
                            level=logging.ERROR)

    app.babel = Babel(app)
    app.babel.localeselector(get_locale)

    app.cache = Cache(app)

    app.mail = Mail(app)

    for extension in app.config["EXTENSIONS"]:
        extension.init_app(app)

    app.session_interface = CheckerSessionInterface()
    app.json_encoder = CustomJSONEncoder

    register_error_handlers(app)

    app.add_template_global(honeypot.FIELD_NAME, name="honeypot_field_name")

    app.register_blueprint(base)
    app.register_blueprint(geocoder)
    app.register_blueprint(contact)
    app.register_blueprint(scope)
    if not app.config.get("CONTACT_ONLY"):
        app.register_blueprint(checker)

    logging.config.dictConfig(app.config["LOGGING"])
    # quiet markdown module
    logging.getLogger("MARKDOWN").setLevel(logging.WARNING)

    if app.debug:
        from werkzeug.debug import DebuggedApplication

        app.wsgi_app = DebuggedApplication(app.wsgi_app, True)

    return app
예제 #21
0
파일: fypress.py 프로젝트: Duncodes/Paipai
    def __init__(self, config, manager=False):
        from flask.ext.babel import Babel
        from utils.mysql import FlaskFyMySQL

        self.prepared = False
        self.config = config
        self.app = Flask(__name__,
                         template_folder=self.config.TEMPLATE_FOLDER,
                         static_folder=self.config.STATIC_FOLDER)
        self.app.config.from_object(config)
        self.app.wsgi_app = ProxyFix(self.app.wsgi_app)
        self.babel = Babel(self.app)
        self.db = FlaskFyMySQL(self.app)

        if not manager:
            self.prepare()
예제 #22
0
def create_app(**config_overrides):
    app = web.create_app(__name__, __path__, **config_overrides)

    tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
    static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
    app.template_folder = tmpl_dir
    app.static_folder = static_dir

    oauth.init_app(app)
    assets.init_app(app)
    babel = Babel(app)

    # So we can use Jade templates.
    app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension')

    return app
def locale_handlers(app):
    """
        Registers application handlers for the localization strategy.
    """
    def get_request_locale():
        default_culture = app.config["DEFAULT_CULTURE"]
        cultures = app.config["CULTURES"].keys()

        # if the culture is set in the header, then use it (needed to ensure consistency when multiple tabs are open)
        header_value = request.headers.get("X-Request-Culture")
        if header_value and header_value in cultures:
            # set and exit
            return header_value

        # if the user identity is known, support user favorite language
        user = request.user if hasattr(request, "user") else None
        if user is not None and user.culture:
            user_culture = user.culture
            if user_culture and user_culture in cultures:
                return user_culture

        culture_cookie = request.cookies.get("culture")
        if culture_cookie and culture_cookie in cultures:
            return culture_cookie

        # set culture by browser setting, or application default
        best_match = request.accept_languages.best_match(cultures)
        if best_match:
            return best_match

        return default_culture

    # localization:
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        locale = get_request_locale()
        request.culture = locale
        return locale

    @app.after_request
    def add_culture_cookie(response):
        culture = request.culture if hasattr(request, "culture") else None
        if culture:
            response.set_cookie("culture", value=culture)
        return response
예제 #24
0
def create_app():
    app = Flask(__name__)
    app.config.from_object("config")

    database.init_database(app)

    app.toolbar = DebugToolbarExtension(app)

    app.babel = Babel(app)

    @app.before_request
    def before_request():
        g.context = {}

#    elixir.setup_all()

    return app
예제 #25
0
def configi18n(app):
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        accept_languages = app.config.get('accept_languages',
                                          ['en_us', 'zh_cn'])
        default_language = app.config.get('babel_default_locale', ['en_us'])

        lang = request.accept_languages.best_match(default_language)

        for language in request.accept_languages:
            lang = language[0].replace('-', '_')
            if lang in accept_languages:
                break

        return lang
예제 #26
0
    def test_i18n_enabled(self):
        from flask import request
        from flask.ext.babel import Babel
        babel = Babel(self.app)

        @babel.localeselector
        def get_locale():
            return request.accept_languages.best_match(['en', 'zh'], 'en')

        self.app.config['CSRF_ENABLED'] = False

        response = self.client.post(
            "/", headers={'Accept-Language': 'zh-CN,zh;q=0.8'}, data={})
        assert '\u8be5\u5b57\u6bb5\u662f' in to_unicode(response.data)

        response = self.client.post("/", data={})
        assert b'This field is required.' in response.data
예제 #27
0
def configure_i18n(app):
    """
    tanzimate marbot be i18n va systeme tarjome dar in bakhsh emal mishavad
    """

    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(['fa'])
        # return 'fa'
        # find set lang
        # TODO: user az inja gerefte mishe?!
        # aslan to in marhale user darim ma ya ye chize zafeyi hast?!
        user = getattr(g, 'user', None)
        if user is not None:
            pass
        accept_languages = app.config.get('ACCEPT_LANGUAGES', ['fa', 'en'])
        return request.accept_languages.best_match(accept_languages)
예제 #28
0
def init():
    """
    Sets up flask application object `app` and returns it.
    """
    # Instantiate main app, load configs, register modules, set
    # url patterns and return the `app` object.
    app = Flask(__name__)
    app.config.from_object(settings)
    config.app = app
    # Init SQLAlchemy wrapper.
    config.db = SQLAlchemy(app)
    if app.debug:
        DebugToolbarExtension(app)
    #: Wrap the `app` with `Babel` for i18n.
    Babel(app)

    config.cache = Cache(app)
    app.jinja_env.add_extension(SlimishExtension)
    app.jinja_env.slim_debug = app.debug
    config.bcrypt = Bcrypt(app)
    # Other initializations.
    for fn, values in [
        (set_middlewares, getattr(settings, 'MIDDLEWARES', None)),
        (set_context_processors, getattr(settings, 'CONTEXT_PROCESSORS',
                                         None)),
        (set_template_filters, getattr(settings, 'TEMPLATE_FILTERS', None)),
        (set_before_handlers, getattr(settings, 'BEFORE_REQUESTS', None)),
        (set_after_handlers, getattr(settings, 'AFTER_REQUESTS', None)),
        (set_log_handlers, getattr(settings, 'LOG_HANDLERS', None)),
        (set_error_handlers, getattr(settings, 'ERROR_HANDLERS', None)),
        (set_blueprints, getattr(settings, 'BLUEPRINTS', None))
    ]:
        if values:
            fn(app, values)

    # Register all js and css files.
    assets = Environment(app)
    register_assets(app, assets)

    # URL rules.
    urls.set_urls(app)
    return app
예제 #29
0
    def setup_app(self):
        app = flask.Flask(__name__)
        from flask.ext.report import FlaskReport, utils

        report_page = flask.Blueprint("report", __name__, static_folder="static",
                                      template_folder="templates")
        db_fd, db_fname = tempfile.mkstemp()
        os.close(db_fd)
        app.config["SECRET_KEY"] = "JHdkj1adf;"
        app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'
        from flask.ext.babel import Babel
        Babel(app)
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_fname
        db.init_app(app)
        db.app = app
        import models
        db.create_all()
        FlaskReport(db, utils.collect_models(models), app, report_page, table_label_map={'TB_USER': u'角色'})
        app.register_blueprint(report_page, url_prefix="/report")
        self.init_data_set()
        self.init_notification()
        return app
예제 #30
0
def configure_extensions(app):
    # flask-sqlalchemy
    db.init_app(app)

    # flask-cache
    cache.init_app(app)

    # flask-babel
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        return request.accept_languages.best_match(DefaultConfig.LANGUAGES)

    # flask-login
    login_manager.login_view = 'admin.login'
    login_manager.refresh_view = 'admin.reauth'

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(id)
    login_manager.setup_app(app)