Ejemplo n.º 1
0
def register_extensions(app):

    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    ckeditor.init_app(app)
Ejemplo n.º 2
0
def create_app(config):
    application = Flask(__name__)
    application.config.from_object(config)

    application.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    application.jinja_env.add_extension('jinja2.ext.do')

    db.init_app(app=application)
    security.init_app(app=application, datastore=user_datastore)
    api.init_app(app=application)

    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
    migrate = Migrate(application, db)

    _load_application_blueprints(application)

    _load_api_blueprints(application)

    load_flask_dance_authorization(application)

    register_assets(application)

    _register_global_variables(application)

    return application
Ejemplo n.º 3
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)
    # db = SQLAlchemy(app)
    # migrate = Migrate(app, db)
    # login = LoginManager(app)
    # login.login_view = 'login'
    # upload = UploadSet(name='images', extensions=IMAGES)
    # configure_uploads(app, upload)
    db.init_app(app)
    migrate.init_app(app, db)
    main_login.init_app(app)
    main_login.login_view = 'main.login'
    api_login.init_app(app)
    api_login.login_view = 'api.login'
    configure_uploads(app, upload)
    
    from app.api import bp as api_bp
    app.register_blueprint(api_bp, url_prefix='/api')

    # from app.main import bp as main_bp
    # app.register_blueprint(main_bp)

    from app.errors import bp as errors_bp
    app.register_blueprint(errors_bp)

    # from app import routes, models

    return app
Ejemplo n.º 4
0
def register_extensions(app):
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    Mail(app)

    user_datastore = SQLAlchemyUserDatastore(db, USER, Role)
    security = Security(app,
                        user_datastore,
                        login_form=ExtendedLoginForm,
                        register_form=ExtendedRegisterForm)

    @security.context_processor
    def security_context_processor():
        return dict(title="Вход")

    @security.register_context_processor
    def security_register_processor():
        return dict(title="Регистрация")

    @user_registered.connect_via(app)
    def user_registered_sighandler(app, user, confirm_token):
        default_role = user_datastore.find_role("user")
        user_datastore.add_role_to_user(user, default_role)
        db.session.commit()
Ejemplo n.º 5
0
def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    csrf.exempt(api_v1)
    babel.init_app(app)
    migrate.init_app(app)
Ejemplo n.º 6
0
def create_app(config=None):
    app = Flask(__name__)

    if config:
        app.config.from_object(config)
    else:
        app.config.from_object(os.environ['APP_SETTINGS'])

    handler = RotatingFileHandler(app.config['LOGGING_LOCATION'],
                                  maxBytes=10000,
                                  backupCount=1)

    from app.home.views import home
    app.register_blueprint(home)

    from app.song.api import songsearch
    app.register_blueprint(songsearch)

    from app.song.api import SongAPI, SongsAPI
    api.add_resource(SongAPI, '/api/song')
    api.add_resource(SongsAPI, '/api/songs')

    from app.playlist.api import PlaylistAPI, PlaylistsAPI, PlaylistSongAPI
    api.add_resource(PlaylistAPI, '/api/playlist')
    api.add_resource(PlaylistsAPI, '/api/playlists')
    api.add_resource(PlaylistSongAPI, '/api/playlist/<int:playlist_id>/song',
                     '/api/playlist/<int:playlist_id>/songs')

    api.init_app(app)
    db.init_app(app)

    return app
Ejemplo n.º 7
0
def init_app(app: Flask):
    # 创建表
    @app.before_first_request
    def create_all_models():
        return
        db.create_all(app=app)
        prepare_data_id_needed()

    # 慢查询检测
    @app.after_request
    def query_time_out(response):

        for query in get_debug_queries():
            if query.duration >= 0.05:
                app.logger.warn(
                    "Context: {} \n SLOW QUERY: {} \n Parameters: {} \n Duration: {} \n"  # noqa
                    .format(
                        query.context,
                        query.statement,
                        query.parameters,
                        query.duration,
                    ))
        return response

    try:
        from flask_migrate import Migrate
        db.init_app(app)
        Migrate(app=app, db=db)
    except ImportError:
        pass
Ejemplo n.º 8
0
def create_app(config_file="settings.py"):
    app = Flask(__name__)

    app.register_error_handler(401, unauthorized)
    app.register_error_handler(404, page_not_found)
    app.register_error_handler(500, server_error)

    app.config.from_pyfile(config_file)

    db.init_app(app)

    bs.init_app(app)

    migrate.init_app(app, db)

    login_manager.init_app(app)

    login_manager.login_view = "auth.login"

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

    app.register_blueprint(main)
    app.register_blueprint(auth)

    app.cli.add_command(create_tables)

    return app
Ejemplo n.º 9
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)
    api.init_app(app)

    if app.config['ELASTIC_ENABLED'] == '1':
        apm.init_app(app)
    else:
        app.logger.debug(
            'ELASTIC_ENABLED: FALSE, set ELASTIC_ENABLED=1 to enable')

    try:
        jwt.init_app(app)
    except Exception as error:
        app.logger.error("Failed to initialize JWT library: " + str(error))

    cache.init_app(app)
    db.init_app(app)

    CORS(app)
    Compress(app)

    return None
Ejemplo n.º 10
0
def test_tab_db(test_flask_shell):
    db.init_app(test_flask_shell)
    db.session.commit()
    db.drop_all()
    db.create_all()

    return db
Ejemplo n.º 11
0
def register_extensions(app):

    api.app = app

    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)

    api.init_app(app)
    if app.config['ELASTIC_ENABLED'] == '1':
        apm.init_app(app)
        logging.getLogger('elasticapm').setLevel(30)
    else:
        app.logger.info(
            'ELASTIC_ENABLED: FALSE, set ELASTIC_ENABLED=1 to enable')

    try:
        jwt.init_app(app)
    except Exception as error:
        app.logger.error("Failed to initialize JWT library: " + str(error))

    cache.init_app(app)
    db.init_app(app)
    CORS(app)

    # Set up Marshmallow
    with app.app_context():
        setup_marshmallow()
Ejemplo n.º 12
0
def create_app(config_name):
    """Initialize the flask app with external configuration."""
    ## App ##
    app = Flask(__name__, static_folder='static',
                template_folder='templates')

    ## Config ##
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    ## Database ##
    db.init_app(app)
    db.app = app

    ## Mail ##
    mail = Mail()
    mail.init_app(app)

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        sslify = SSLify(app)

    ## Blueprints ##
    register_blueprints(app)

    return app
Ejemplo n.º 13
0
def create_app(environment=None):
    """Create and bootstrap app."""
    # Instantiate the app
    app = FlaskAPI(__name__)

    # Enable CORS
    CORS(app)

    # Set config
    if not environment:
        environment = os.getenv('APP_SETTINGS', 'development')
    config_object = app_config[environment]
    app.config.from_object(config_object)

    # Set up extensions
    mongoDB.init_app(app)
    db.init_app(app)
    bcrypt.init_app(app)
    migrate.init_app(app, db)

    # Register application components
    register_tool_result_modules(app)
    register_display_modules(app)
    register_blueprints(app)
    register_error_handlers(app)

    # Update Celery config
    update_celery_settings(celery, config_object)

    return app
Ejemplo n.º 14
0
def register_extensions(app):
    """Register Flask extensions."""
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    jwt.init_app(app)
Ejemplo n.º 15
0
def register_extensions(app):
    origins = app.config.get('CORS_ORIGIN_WHITELIST', '*')
    cors.init_app(app, origins=origins)
    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    jwt.init_app(app)
Ejemplo n.º 16
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    app.config['UPLOADED_PHOTOS_DEST'] = 'app/static/user_images'
    configure_uploads(app, photos)

    compress.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    bootstrap.init_app(app)

    from app.auth import bp as auth_bp
    app.register_blueprint(auth_bp, url_prefix='/auth')

    from app.main import bp as main_bp
    app.register_blueprint(main_bp)

    if not app.debug and not app.testing:
        # FUTURE AUTOMATED TEST LOGGING HERE
        pass

    app.cli.add_command(create_tables)
    app.cli.add_command(fill_image_table)

    return app
Ejemplo n.º 17
0
def configure_extensions(app):
    ''' 配置扩展 '''
    db.init_app(app)
    migrate.init_app(app, db)
    # cors.init_app(app)
    bootstrap.init_app(app)
    login.init_app(app)
Ejemplo n.º 18
0
def register_extensions(app):
    bcrypt.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login.init_app(app)
    debug_toolbar.init_app(app)
    mail.init_app(app)
    migrate.init_app(app, db)
    moment.init_app(app)
    if not app.debug and not app.testing:
        if app.config['MAIL_SERVER']:
            auth = None
            if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
                auth = (app.config['MAIL_USERNAME'],
                        app.config['MAIL_PASSWORD'])
            secure = None
            if app.config['MAIL_USE_TLS']:
                secure = ()
            mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr='no-reply@' + app.config['MAIL_SERVER'],
                toaddrs=app.config['ADMINS'], subject='Microblog Failure',
                credentials=auth, secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)
    return None
Ejemplo n.º 19
0
def register_extensions(app):
    """Register the application with needed extensions."""
    hashing.init_app(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()
        db.session.commit()
Ejemplo n.º 20
0
def create_app():
   app = Flask(__name__, static_folder='', template_folder='app/admin/templates')
   print app.root_path
   #load config
   app.config.from_object(AdminProdConfig)
   
   #init extension
   db.init_app(app)
   
   #init login
   login_manager.login_view = "frontend.login"
   @login_manager.user_loader
   def load_user(id):
       return AdminUser.by_id(id)
       
   login_manager.init_app(app)
   
   #init admin
   admin = Admin(name='DD Admin', index_view=HomeView(),url='/admin')
   admin.init_app(app)
   
   admin.add_view(getAdminUserView())
   admin.add_view(getAdminEmailView())
   admin.add_view(getAdminSellingPostView())
   admin.add_view(getAdminBuyRequestView())
   admin.add_view(getAdminHashtagView())
   admin.add_view(getAdminBugPostView())
   
   admin.add_view(LogoutView(name="Logout"))
   
   #register blueprint
   app.register_blueprint(frontend)

   return app
Ejemplo n.º 21
0
def register_extensions(app):
    # 数据库
    db.init_app(app)
    # 数据库迁移工具
    migrate.init_app(app, db)
    # 跨域
    cors.init_app(app)
Ejemplo n.º 22
0
def register_extensions(app):
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    bootstrap.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    return None
Ejemplo n.º 23
0
def create_app(config=None):
    app = JSONFlask(__name__)
    if config:
        app.config.from_object(config)

    db.init_app(app)
    jwt.init_app(app)
    cors.init_app(app)
    mail.init_app(app)

    app.register_blueprint(account_bp, url_prefix='/api/v1/account')
    app.register_blueprint(categories_bp, url_prefix='/api/v1/categories')
    app.register_blueprint(food_item_state_bp,
                           url_prefix='/api/v1/food_item_state')
    app.register_blueprint(stock_bp, url_prefix='/api/v1/stock')
    app.register_blueprint(snapshot_bp, url_prefix='/api/v1/snapshot')
    app.register_blueprint(unit_of_measure_bp,
                           url_prefix='/api/v1/unit_of_measure')

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def catch_all(path):
        return app.send_static_file("index.html")

    return app
Ejemplo n.º 24
0
def register_extensions(app):

    api.app = app
    # Overriding swaggerUI base path to serve content under a prefix
    apidoc.apidoc.static_url_path = '{}/swaggerui'.format(Config.BASE_PATH)
    api.init_app(app)

    cache.init_app(app)
    db.init_app(app)
    jwt.init_app(app)
    apm.init_app(app) if app.config['ELASTIC_ENABLED'] == '1' else None
    sched.init_app(app)

    CORS(app)
    Compress(app)

    if app.config.get('ENVIRONMENT_NAME') in ['test', 'prod']:
        if not app.debug or os.environ.get("WERKZEUG_RUN_MAIN") == 'true':
            sched.start()
            _schedule_NRIS_jobs(app)
            # This is here to prevent this from running in production until we are confident in the permit data.
            if app.config.get('ENVIRONMENT_NAME') == 'test':
                _schedule_ETL_jobs(app)

    return None
Ejemplo n.º 25
0
def create_app(fs: str = 'settings.py'):
    app = Flask(__name__)
    cnf = os.getenv('FLASK_ENV')
    if cnf.lower().startswith('dev'):
        app.config.from_object(DevConfig)
    else:
        app.config.from_object(DevConfig)

    crsf.init_app(app)

    # Server-side session config
    app.config["SESSION_TYPE"] = 'sqlalchemy'
    app.config["SESSION_PERMANENT"] = True
    app.config['PERMANENT_SESSION_LIFETIME'] = 6000
    app.config["SESSION_USE_SIGNER"] = True
    app.config["SESSION_SQLALCHEMY"] = db
    app.config["SESSION_SQLALCHEMY_TABLE"] = "sessions"
    sess = Session()
    sess.init_app(app)

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

    app.register_blueprint(main)

    # Acquisizione della configurazione per il generatore e altri dati
    # di configurazione
    with app.app_context():
        _, objlist = GeneratorConfig.parse_config()
        diz = dict()
        for obj in objlist:
            diz[obj.conf_key] = obj.conf_value
        set_builder_conf(diz)
    return app
Ejemplo n.º 26
0
def create_app(config=Config()):
    """Flask application factory."""

    app = Flask(__name__)

    if config is not None:
        app.config.from_object(config)

    # override settings by environment variables

    if 'DEBUG' in os.environ:
        app.config['DEBUG'] = os.environ['DEBUG'].lower() == 'true'

    if 'SECRET_KEY' in os.environ:
        app.config['SECRET_KEY'] = os.environ['SECRET_KEY']

    if 'SSL_ENABLE_REDIRECTS' in os.environ:
        app.config['SSL_ENABLE_REDIRECTS'] = os.environ['SSL_ENABLE_REDIRECTS'].lower() == 'true'

    if 'DATABASE_URL' in os.environ:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']

    db.init_app(app)
    babel = Babel(app)
    login_manager.setup_app(app)
    oid.init_app(app)
    DebugToolbarExtension(app)

    app.register_blueprint(times)

    admin = Admin(app, url_prefix='/admin', title='Admin')
    admin.add_path_security('/', secure_admin_path)
    admin.add_path_security('/auth', secure_admin_auth_path)

    auth_node = admin.register_node('/auth', 'auth', 'Authentication')
    time_node = admin.register_node('/time_node', 'time_node', 'Times')

    admin.register_module(UserAdmin, '/users', 'users', 'Users', parent=auth_node)
    admin.register_module(CompanyAdmin, '/companies', 'companies', 'Companies', parent=time_node)
    admin.register_module(ProjectAdmin, '/projects', 'projects', 'Projects', parent=time_node)
    admin.register_module(TaskAdmin, '/tasks', 'tasks', 'Tasks', parent=time_node)
    admin.register_module(WorkingUnitAdmin, '/times', 'times', 'Working Times', parent=time_node)

    @login_manager.user_loader
    def load_user(userid):
        return User.query.get(int(userid))

    @app.context_processor
    def inject_context():
        version = os.environ.get('VERSION', 'devel')
        return dict(user=current_user, now=datetime.now(), version=version)

    @babel.localeselector
    def get_locale():
        if hasattr(current_user, 'locale'):
            return current_user.locale
        return request.accept_languages.best_match(['en', 'ja', 'de'])

    return app
Ejemplo n.º 27
0
def configure_extensions(app, cli):
    """configure flask extensions
    """
    db.init_app(app)
    jwt.init_app(app)

    if cli is True:
        migrate.init_app(app, db)
Ejemplo n.º 28
0
def configure_extensions(app):
    '''Configures the extensions.'''
    # Enable CORS
    cors.init_app(app)
    # Init Flask-SQLAlchemy
    db.init_app(app)
    # Init Flask-Migrate
    migrate.init_app(app, db)
Ejemplo n.º 29
0
def register_extensions(app):
    """Register extension with app."""
    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    sess.init_app(app)
Ejemplo n.º 30
0
def register_extensions(app):
    decorators = []
    decorators += [basic_auth.login_required]

    db.init_app(app)
    migrate.init_app(app, db)
    api_scaffold.init_app(app, db, decorators)
    return None
Ejemplo n.º 31
0
def register_extensions(app):
    db.init_app(app)
    ma.init_app(app)
    bcrypt.init_app(app)
    jwt.init_app(app)
    initialize_routes(api)
    api.init_app(app)
    return None
Ejemplo n.º 32
0
def create_light_app() -> Flask:
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = DB_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    db.init_app(app)

    return app
Ejemplo n.º 33
0
def register_extensions(app):
    db.init_app(app)
    cache.init_app(app)
    bcrypt.init_app(app)
    celery.config_from_object(app.config)
    redis.init_app(app)
    login_manager.init_app(app)
    principal.init_app(app)
Ejemplo n.º 34
0
def configure_extensions(app):
    # configure extensions
    db.init_app(app)
    migrate = Migrate(app, db)
    cache.init_app(app)
    sentry.init_app(app)
    redis.init_app(app)

    core.init_login(app)
Ejemplo n.º 35
0
def create_app():
    app = Flask("app") # Nome da pasta que contém este arquivo
    app.config.from_object(ConfigDev)

    db.init_app(app)
    
    register_blueprints(app)

    return app
Ejemplo n.º 36
0
def register_extensions(app):
    db.init_app(app)
    migrate.init_app(app, db)

    # @todo there is no init_app in SQLAlchemyUserDatastore :'(
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)

    security.init_app(app, user_datastore)

    return None
Ejemplo n.º 37
0
def register_extensions(app):
    """Register Flask extensions."""
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)
    return None
Ejemplo n.º 38
0
def init_db():
    """ Clean up and create database. """

    app = Flask(__name__)
    load_config(app)

    db.init_app(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(os.path.abspath(os.path.dirname(__file__)), 'app.sqlite')
    with app.app_context():
        db.drop_all()
        db.create_all()
Ejemplo n.º 39
0
def create_app(config_name):
    app = Flask(__name__,
                static_folder=STATIC_FOLDER,
                template_folder=TEMPLATES_FOLDER)
    app.config.from_object(config[config_name])
    app.wsgi_app = AuthMiddleware(app.wsgi_app)

    db.init_app(app)
    redis.init_app(app)

    for module in Module.get_all():
        app.register_blueprint(module)

    return app
Ejemplo n.º 40
0
def celery_worker_init_db(**_):
    """Initialize SQLAlchemy right after the Celery worker process forks.

    This ensures each Celery worker has its own dedicated connection to the MySQL database. Otherwise
    one worker may close the connection while another worker is using it, raising exceptions.

    Without this, the existing session to the MySQL server is cloned to all Celery workers, so they
    all share a single session. A SQLAlchemy session is not thread/concurrency-safe, causing weird
    exceptions to be raised by workers.

    Based on http://stackoverflow.com/a/14146403/1198943
    """
    # LOG.debug('Initializing SQLAlchemy for PID {}.'.format(os.getpid()))
    db.init_app(current_app)
def register_extensions(app):
    """
    Import and register flask extensions and initialize with app object
    """

    from app.assets import env
    env.init_app(app)

    from app.extensions import db
    db.init_app(app)
    # XXX avoids "RuntimeError: application not registered on db instance and
    # no application bound to current context" when accessing db outside of app
    # context
    db.app = app

    from flask_migrate import Migrate
    from sqlalchemy.exc import ArgumentError
    migrate = Migrate()
    # XXX SQLite chokes on constraint changes without this
    with app.app_context():
        try:
            render_as_batch = db.engine.url.drivername == 'sqlite'

        # XXX this happens during a test
        except ArgumentError:
            render_as_batch = True

        migrate.init_app(app, db, render_as_batch=bool(render_as_batch))

    from flask_humanize import Humanize
    Humanize(app)

    from flask_security import Security
    from app.extensions import user_datastore
    from app.main.models import AnonymousUser, Role, User
    user_datastore.role_model = Role
    user_datastore.user_model = User
    Security(app, user_datastore, anonymous_user=AnonymousUser)

    from app.extensions import notify
    notify.init_app(app)

    from app.oidc_client import OIDCClient
    OIDCClient(app)

    from app.extensions import pay
    pay.init_app(app)
Ejemplo n.º 42
0
def configure_extensions(app):
    # http://stackoverflow.com/questions/19437883/when-scattering-flask-models-runtimeerror-application-not-registered-on-db-w
    db.app = app
    db.init_app(app)

    login_manager.login_view = 'user.login'

    @login_manager.user_loader
    def load_user(id):
        return User.get(int(id))
    login_manager.init_app(app)

    Bootstrap(app)

    twitter_api.auth = tweepy.OAuthHandler(app.config['CONSUMER_KEY'],
                                           app.config['CONSUMER_SECRET'])
    twitter_api.auth.set_access_token(app.config['ACCESS_TOKEN'],
                                      app.config['ACCESS_TOKEN_SECRET'])
Ejemplo n.º 43
0
def register_extensions(app):
    """
    Import and register flask extensions and initialize with app object
    """

    from app.assets import env
    env.init_app(app)

    from app.extensions import db
    db.init_app(app)
    # XXX avoids "RuntimeError: application not registered on db instance and
    # no application bound to current context" when accessing db outside of app
    # context
    db.app = app

    from flask_migrate import Migrate
    from sqlalchemy.exc import ArgumentError
    migrate = Migrate()
    # XXX SQLite chokes on constraint changes without this
    with app.app_context():
        try:
            render_as_batch = db.engine.url.drivername == 'sqlite'

        # XXX this happens during a test
        except ArgumentError:
            render_as_batch = True

        migrate.init_app(app, db, render_as_batch=bool(render_as_batch))

    from flaskext.markdown import Markdown
    Markdown(app, extensions=app.config.get('MARKDOWN_EXTENSIONS', []))

    from flask_humanize import Humanize
    Humanize(app)

    from app.extensions import oidc
    oidc.init_app(app)

    from flask_security import Security
    from app.extensions import user_datastore
    from app.blueprints.base.models import Role, User
    user_datastore.role_model = Role
    user_datastore.user_model = User
    Security(app, user_datastore)
Ejemplo n.º 44
0
def configure_extensions(app):
    """
    Initialize Flask Extensions.
    """
    db.init_app(app)
    babel.init_app(app)
    csrf.init_app(app)

    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    login_manager.login_message = lazy_gettext('Please, log in '
                                               'to access this page.')
    login_manager.login_message_category = 'warning'
    login_manager.anonymous_user = AnonymousUser

    Markdown(app, extensions=['codehilite', 'toc', 'tables', 'def_list'])

    @login_manager.user_loader
    def _user_loader(user_id):
        # User loader callback function
        return User.query.get(int(user_id))
Ejemplo n.º 45
0
def create_app(config_obj, no_sql=False):
    app = Flask(__name__, template_folder=TEMPLATE_FOLDER, static_folder=STATIC_FOLDER)
    config_dict = dict([(k, getattr(config_obj, k)) for k in dir(config_obj) if not k.startswith('_')])
    app.config.update(config_dict)

    # Import DB models
    with app.app_context():
        for module in app.config.get('DB_MODELS_IMPORTS', list()):
            import_module(module)
    # Setup redirects and register blueprints
    for bp in all_blueprints:
        import_module(bp.import_name)
        app.register_blueprint(bp)

    # Initialize extensions/add-ons/plugins
    db.init_app(app)
    celery.init_app(app)

    # Activate middleware

    # Return the application instance.
    return app
Ejemplo n.º 46
0
def create_app(config=None):
    
    app = Flask(__name__)

    if config:
        app.config.from_object(config)
    else:
        app.config.from_object(os.environ['APP_SETTINGS'])

    # Init logger
    handler = RotatingFileHandler(app.config['LOGGING_LOCATION'], maxBytes=10000, backupCount=1)
    handler.setLevel(app.config['LOGGING_LEVEL'])
    app.logger.addHandler(handler)

    # Init routes
    from app.home.views import home
    app.register_blueprint(home)

    from app.home.api import TestApi
    api.add_resource(TestApi, '/api/protected')

    from app.user.api import UserApi
    api.add_resource(UserApi, '/api/user/register')

    # Init extensions
    db.init_app(app)
    api.init_app(app)
    bcrypt.init_app(app)

    from app.user.auth import authenticate, identity, payload_handler
    jwt.authentication_handler(authenticate)
    jwt.identity_handler(identity)
    jwt.jwt_payload_handler(payload_handler)
    jwt.init_app(app)

    return app
Ejemplo n.º 47
0
def initdb():
    """Init/reset database."""

    db.init_app(app)

    metadata = MetaData(db.engine)
    metadata.reflect()
    for table in metadata.tables.values():
        for fk in table.foreign_keys:
            db.engine.execute(DropConstraint(fk.constraint))
    db.drop_all()
    db.create_all()

    # create tasks

    db.session.add_all([
        Task(identifier='mass_m', name='Mass - Metric'),
        Task(identifier='mass_i', name='Mass - Imperial'),
        Task(identifier='mass_c', name='Mass - Combined'),
        Task(identifier='length_m', name='Length - Metric'),
        Task(identifier='length_i', name='Length - Imperial'),
        Task(identifier='length_c', name='Length - Combined'),
        Task(identifier='area', name='Area'),
        Task(identifier='temperature_m', name='Temperature'),
        Task(identifier='temperature_i', name='Temperature'),
        Task(identifier='temperature_c', name='Temperature'),
        Task(identifier='currency_czk', name='Currency - CZK'),
        Task(identifier='currency_eur', name='Currency - EUR'),
        Task(identifier='currency_usd', name='Currency - USD'),
    ])

    # create test data

    test_task = Task(identifier='test', name='Test')
    sortA1 = SortAnswer(value="36", unit="in", presented_pos=0)
    sortA2 = SortAnswer(value="1", unit="ft", presented_pos=1)
    sortA3 = SortAnswer(value="12", unit="m", presented_pos=2)
    sortA4 = SortAnswer(value="1", unit="km", presented_pos=3)
    closeA1 = CloseEndedAnswer(value="3", unit="yd", correct=False)
    closeA2 = CloseEndedAnswer(value="10", unit="in", correct=False)
    closeA3 = CloseEndedAnswer(value="1", unit="yd", correct=True)
    closeA4 = CloseEndedAnswer(value="1", unit="yd", correct=True)
    closeA5 = CloseEndedAnswer(value="11", unit="cm", correct=False)

    db.session.add_all([
        test_task,
        ScaleQuestion(scale_min=0, scale_max=10, from_value=6, from_unit="lb", to_unit="kg", tasks=[test_task]),
        CurrencyQuestion(from_value=300, from_unit="CZK", to_unit="EUR", tasks=[test_task]),
        NumericQuestion(from_value=5, from_unit="m", to_unit="ft", tasks=[test_task], image_name="car"),
        NumericQuestion(from_value=5, from_unit="m", to_unit="ft", tasks=[test_task]),
        sortA1,
        sortA2,
        sortA3,
        sortA4,
        SortQuestion(dimensionality="length", order="asc", answers=[sortA1, sortA2, sortA3, sortA4], tasks=[test_task]),
        closeA1,
        closeA2,
        closeA3,
        CloseEndedQuestion(question_en="bicycle", question_type="estimate_height", answers=[closeA1, closeA2, closeA3], tasks=[test_task]),
        CloseEndedQuestion(question_en="bicycle", question_type="estimate_height",
                           answers=[closeA4, closeA5], tasks=[test_task], image_name="bicycle"),
    ])

    db.session.commit()
Ejemplo n.º 48
0
import sys
import csv

from app.app import create_app
from app.config import config
from app.models import *
from app.extensions import db
from app.models.Question import QuestionTaskAssociation

app = create_app(config)
db.init_app(app)
db.app = app


def get_tasks():
    tasks = db.session.query(Task).all()
    tasks_dict = {}
    for task in tasks:
        tasks_dict[task.identifier] = task

    return tasks_dict


def load_numeric(file):
    tasks = get_tasks()
    questions = []

    for row in file:
        task_name = row[0]

        if len(task_name) > 0 and task_name in tasks:
Ejemplo n.º 49
0
def configure_extensions(app):
    db.init_app(app)
Ejemplo n.º 50
0
def configure_extentions(app):
    from app.extensions import db
    import wtforms_json
    db.init_app(app)
    wtforms_json.init()
Ejemplo n.º 51
0
 def _init_extensions(self):
     db.init_app(self)