Example #1
0
def create_app(name, config_filename):
    app = Flask(name,
                template_folder='app/templates',
                static_folder='app/static')
    app.config.from_pyfile(config_filename)

    from app.models import db
    db.init_app(app)
    db.app = app
    from app.sms import mail
    mail.init_app(app)
    mail.app = app

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

    #TODO: Secure admin view
    admin = Admin()
    admin.init_app(app)
    admin.app = app
    admin.add_view(ModelView(User, db.session))

    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler, RotatingFileHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='dci-notify Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))

        file_handler = RotatingFileHandler(filename=os.path.join(basedir,
                                                                 'app.log'),
                                           maxBytes=1048756,
                                           backupCount=5)

        mail_handler.setLevel(logging.ERROR)
        file_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        file_handler.setFormatter(Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
        ))
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)

    return app
Example #2
0
def create_app(config=None):
    app = Flask(__name__)

    if config is None:
        config = os.path.join(
            app.root_path, os.environ.get('FLASK_APPLICATION_SETTINGS')
        )

    app.config.from_pyfile(config)
    app.secret_key = app.config['SECRET_KEY']

    db.init_app(app)
    migrate.init_app(app, db)
    sec_state = security.init_app(app)
    admin.init_app(app)

    admin.add_view(UserAdmin(User, db.session, category="Accounts"))
    admin.add_view(RoleAdmin(Role, db.session, category="Accounts"))

    @sec_state.context_processor
    def security_context_processor():
        return dict(
            admin_base_template=admin.base_template,
            admin_view=admin.index_view,
            h=admin_helpers,
        )

    app.register_blueprint(cart)

    return app
Example #3
0
def create_app():
    app = Flask(__name__)

    # Determine current environment
    env = os.environ.get('APOLLO_ENV').capitalize() if os.environ.get('APOLLO_ENV') else 'Development'
    app.config.from_object('config.'+ env)
    app.config['ENV'] = env

    # Are we using postgres specific features?
    assert 'postgres' in app.config['SQLALCHEMY_DATABASE_URI']

    # Set up api routes
    from app.controllers import question
    app.register_blueprint(question)

    # Set up template routes
    @app.route("/")
    def index():
        values = {}
        questions = Question.query.filter(Question.is_live==True).all()
        values["questions"] = questions
        return render_template('index.html', **values)

    # Set up connection to DB
    db.init_app(app)
    return app
Example #4
0
def create_app(config_name):
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'admin.login'

    if not app.debug:
        import logging
        from logging import FileHandler, Formatter

        file_handler = FileHandler(Constant.LOG_DIR, encoding='utf8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(Formatter(
            '[%(asctime)s] %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(file_handler)

    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    patch_request_class(app, size=16*1024*1024) # 16MB
    configure_uploads(app, resource_uploader)

    return app
Example #5
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # blueprints
    from app.main import main as main_blueprint
    from app.blog import blog as blog_blueprint
    from app.admin import admin as admin_blueprint
    from app.projects import projects as projects_blueprint
    app.register_blueprint(main_blueprint)
    app.register_blueprint(blog_blueprint, url_prefix='/blog')
    app.register_blueprint(admin_blueprint)
    app.register_blueprint(projects_blueprint, url_prefix='/projects')

    # initializations
    csrf.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    md = Markdown(app)
    md.register_extension(CodeHiliteExtension)

    app.jinja_env.filters['timesince'] = timesince_filter

    return app
Example #6
0
    def init_app(cls, app):
        Config.init_app(app)

        with app.app_context():
            from app.models import db
            from app.models import User, Notebook

            db.init_app(app)
Example #7
0
def create_app():
    app = Flask("test", template_folder=basedir + "/../app/templates")
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'opinionated-test.db')
    app.config['SERVER_NAME'] = 'localhost:5000'
    app.debug = True
    db.app = app
    db.init_app(app)
    return app
Example #8
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    github.init_app(app)
    db.init_app(app)
    app.register_blueprint(main_blueprint)
    return app
def create_app():
    auto = Autodoc(app)
    cal = Calendar()

    app.register_blueprint(api_v1_routes)
    app.register_blueprint(sitemap_routes)
    migrate = Migrate(app, db)

    app.config.from_object(environ.get('APP_CONFIG', 'config.ProductionConfig'))
    db.init_app(app)
    manager = Manager(app)
    manager.add_command('db', MigrateCommand)

    cors = CORS(app)
    app.secret_key = 'super secret key'
    app.json_encoder = MiniJSONEncoder
    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
    app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
    app.config['STATIC_URL'] = '/static/'
    app.config['STATIC_ROOT'] = 'staticfiles'
    app.config['STATICFILES_DIRS'] = (os.path.join(BASE_DIR, 'static'),)
    app.config['SQLALCHEMY_RECORD_QUERIES'] = True
    app.config['SERVER_NAME'] = 'open-event-dev.herokuapp.com'
    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.INFO)
    app.jinja_env.add_extension('jinja2.ext.do')
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
    app.jinja_env.undefined = SilentUndefined
    app.jinja_env.filters['operation_name'] = operation_name
    # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    # set up jwt
    app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24*60*60)
    app.config['JWT_AUTH_URL_RULE'] = None
    jwt = JWT(app, jwt_authenticate, jwt_identity)

    # setup celery
    app.config['CELERY_BROKER_URL'] = environ.get('REDIS_URL', 'redis://localhost:6379/0')
    app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']

    HTMLMIN(app)
    admin_view = AdminView("Open Event")
    admin_view.init(app)
    admin_view.init_login(app)

    # API version 2
    with app.app_context():
        from app.api import api_v2
        app.register_blueprint(api_v2)

    sa.orm.configure_mappers()

    return app, manager, db, jwt
def create_app():
    babel.init_app(app)
    BlueprintsManager.register(app)
    Migrate(app, db)

    app.config.from_object(environ.get('APP_CONFIG', 'config.ProductionConfig'))
    db.init_app(app)
    _manager = Manager(app)
    _manager.add_command('db', MigrateCommand)

    if app.config['CACHING']:
        cache.init_app(app, config={'CACHE_TYPE': 'simple'})
    else:
        cache.init_app(app, config={'CACHE_TYPE': 'null'})

    stripe.api_key = 'SomeStripeKey'
    app.secret_key = 'super secret key'
    app.json_encoder = MiniJSONEncoder
    app.config['BABEL_DEFAULT_LOCALE'] = 'en'
    app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
    app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'

    app.logger.addHandler(logging.StreamHandler(sys.stdout))
    app.logger.setLevel(logging.ERROR)
    app.jinja_env.add_extension('jinja2.ext.do')
    app.jinja_env.add_extension('jinja2.ext.loopcontrols')
    app.jinja_env.undefined = SilentUndefined
    app.jinja_env.filters['operation_name'] = operation_name

    # set up jwt
    app.config['JWT_AUTH_USERNAME_KEY'] = 'email'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(seconds=24 * 60 * 60)
    app.config['JWT_AUTH_URL_RULE'] = None
    _jwt = JWT(app, jwt_authenticate, jwt_identity)

    # setup celery
    app.config['CELERY_BROKER_URL'] = environ.get('REDIS_URL', 'redis://localhost:6379/0')
    app.config['CELERY_RESULT_BACKEND'] = app.config['CELERY_BROKER_URL']

    HTMLMIN(app)
    CORS(app, resources={r"/api/*": {"origins": "*"}})
    AuthManager.init_login(app)

    if app.config['TESTING'] and app.config['PROFILE']:
        # Profiling
        app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[30])

    # API version 2
    with app.app_context():
        from app.api import api_v1
        app.register_blueprint(api_v1)

    sa.orm.configure_mappers()

    return app, _manager, db, _jwt
Example #11
0
def create_app(config_obj):
    app = Flask(__name__)
    app.config.from_object(config_obj)

    from app.models import db
    db.init_app(app)

    from app.views import bro, login_manager
    app.register_blueprint(bro)
    login_manager.init_app(app)

    return app
Example #12
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
    CSRFProtect(app)
    Session(app)
    app.redis_cli = redis.StrictRedis(config.REDIS_HOST,config.REDIS_PORT,config.REDIS_DB)

    app.register_blueprint(index_blueprint)
    app.register_blueprint(user_blueprint)
    app.register_blueprint(detail_blueprint)
    return app
Example #13
0
def create_app():
    app = Flask(__name__)
    # app.config.from_object('app.secure')
    app.config.from_object('app.setting')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.register_blueprint(web)
    db.init_app(app)
    db.create_all(app=app)
    login_manager.init_app(app)
    login_manager.login_view = 'views.login'
    login_manager.login_message = '请先登录'
    mail.init_app(app)
    return app
Example #14
0
def create_app(config_name):

    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)


    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    return app
Example #15
0
def create_app():
    app = Flask(__name__)

    app.config.update(DEBUG=True, SECRET_KEY='secret_xxx')

    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.sqlite'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    #register blue prints
    app.register_blueprint(home)
    app.register_blueprint(planner)

    return app
Example #16
0
def register_extensions(app):
    db.init_app(app)
    Migrate(app, db)

    app.jinja_env.filters['timesince'] = timesince
    login_manager = LoginManager()
    login_manager.init_app(app)

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

    login_manager.login_view = 'home.login'
Example #17
0
def create_app(config='DevConfig'):

    app = Flask(__name__)

    app.config.from_object("app.config.{}".format(config))

    # instantiate blueprints
    app.register_blueprint(api)
    # instantiate extensions
    db.init_app(app)

    # db.create_all()
    return app
Example #18
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile('config.py')
    from app.models import db
    db.init_app(app)
    from app.tasks import tm
    tm.init_app(app, db)
    with app.app_context():
        db.create_all()
        from app.blueprints import web, api
        app.register_blueprint(web)
        app.register_blueprint(api, url_prefix='/api')
    return app
Example #19
0
def create_app(conf=config.Config):
    app = Flask(__name__)
    app.config.from_object(conf)

    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    mail.init_app(app)
    admin.init_app(app)
    csrf.init_app(app)
    configure_routes(app)

    return app
Example #20
0
def create_app(config_name):
    #创建app实例
    app = Flask(__name__)#初始化配置
    if config_name not in config:
        config_name = 'default'
    app.config.from_object(config[config_name])
    db.init_app(app)
    app.register_blueprint(bp)
    app.register_blueprint(bp_two)
    app.register_blueprint(bp_three)
    app.register_blueprint(bp_PM)
    app.app_context().push()
    return app
def create_app():
    pymysql.install_as_MySQLdb()
    app = Flask(__name__)
    app.register_blueprint(auth.auth)
    app.register_blueprint(project.project)
    app.register_blueprint(projectManagement.manager)
    app.register_blueprint(requirementManage.requirementManage)
    app.config.from_object(Dev)
    app.app_context().push()
    db.init_app(app)
    db.create_all()
    data_init()
    return app
Example #22
0
def create_app(config_name):
    """
    App factory. Can be used to instantiate various environments.
    """
    _app = Flask(__name__)

    configure_service(_app, config_name)
    db.init_app(_app)

    with _app.app_context():
        db.create_all()
	
    return _app
Example #23
0
def create_app():

    app = Flask(__name__,
                static_folder=STATIC_PATH,
                template_folder=TEMPLATE_PATH)
    # 加载配置
    app.config.from_object(Conf)
    # 蓝图
    app.register_blueprint(blueprint=blue, url_prefix='/user')
    # 初始化
    db.init_app(app)

    return app
Example #24
0
def create_app(config_class=Config):
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config_class)
    app.config.from_pyfile('config.py', silent=True)

    from app.models import db, ma, migrate
    db.init_app(app)
    ma.init_app(app)
    migrate.init_app(app, db)
    from app.resources import api
    api.init_app(app)
    CORS(app)
    return app
Example #25
0
def create_app(config_name):
    app = Flask(__name__)
    CORS(app, supports_credentials=True)
    app.config.from_object(config[config_name])

    # cors.init_app(app)
    db.init_app(app)
    bootstrap.init_app(app)

    from .api_1_0 import api
    app.register_blueprint(api)

    return app
Example #26
0
def create_app():
    app = Flask(__name__)

    app.config.from_object(Config)

    db.app = app
    db.init_app(app)

    app.register_blueprint(tempBp)

    app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'

    return app
def create_app(object_name='config'):

    app = Flask(__name__)

    app.config.from_object(object_name)

    db.init_app(app)
    with app.app_context():
        db.create_all()

    app.register_blueprint(main)

    return app
Example #28
0
def create_app(debug):
    '''creates app instance, db instance, and apimanager instance'''

    # Extra config stuff
    app.config['DEBUG'] = debug
    #if debug:
    #	app.config['PROPAGATE_EXCEPTIONS'] = False
    #	app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = True

    # Generate DB URI
    if debug and not os.getenv('MYSQL_HOST'):
        db_uri = settings.SQLALCHEMY_SQLITE_URI
    else:  # for production
        from app.initializers import secrets
        MYSQL_HOST = os.getenv('MYSQL_HOST') or 'localhost'
        db_uri = 'mysql://%s:%s@%s/%s' % (settings.MYSQL_USER,
                                          secrets.MYSQL_PASSWORD, MYSQL_HOST,
                                          settings.MYSQL_DB)
        app.config['SQLALCHEMY_POOL_RECYCLE'] = 299
        app.config['SQLALCHEMY_POOL_TIMEOUT'] = 20

    app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
    #app.secret_key = SECRET_KEY  # move this out of here eventually

    # Templating engines
    #Flask.jinja_options['extensions'].append(SlimishExtension)
    Flask.jinja_options['extensions'].append(PyJadeExtension)

    db.init_app(app)

    app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
    #toolbar = DebugToolbarExtension(app)

    # Set up user management
    app.config['CSRF_ENABLED'] = True
    app.config['USER_ENABLE_EMAIL'] = False

    #load blueprints
    register_blueprints(app)

    # Initialize assets
    init_assets(app)

    with app.app_context():
        db.create_all()

    #Markdown(app)              # doesn't work anymore!!!

    cache.init_app(app)

    return app
Example #29
0
def create_app(config_name):
    """ app factory """

    # import config options
    from config.config import app_config

    app = Flask(__name__)

    # allow cross-domain requests
    CORS(app)

    # use running config settings on app
    app.config.from_object(app_config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # register app with the db
    db.init_app(app)

    # initialize api resources
    api.init_app(app)

    # handle default 404 exceptions with a custom response
    @app.errorhandler(404)
    def resource_not_found(exception):
        response = jsonify(
            dict(status='fail',
                 data={
                     'error':
                     'Not found',
                     'message':
                     'The requested URL was'
                     ' not found on the server. If you entered the URL '
                     'manually please check and try again'
                 }))
        response.status_code = 404
        return response

    # both error handlers below handle default 500 exceptions with a custom
    # response
    @app.errorhandler(500)
    def internal_server_error(error):
        response = jsonify(
            dict(status=error,
                 error='Internal Server Error',
                 message='The server encountered an internal error and was'
                 ' unable to complete your request.  Either the server is'
                 ' overloaded or there is an error in the application'))
        response.status_code = 500
        return response

    return app
Example #30
0
def fix_bad_genres():
    with app.app_context():
        db.init_app(app)

        all_anime = Anime.query.all()
        all_manga = Manga.query.all()

        models = []

        for anime in all_anime:
            if len(
                    anime.genre
            ) == 4:  # Bad genres are in the form of "., ." where . is any symbol
                print("Anime ID: " + str(anime.id) + " Genre: " + anime.genre)
                models.append(anime)

        for manga in all_manga:
            if len(
                    manga.genre
            ) == 4:  # Bad genres are in the form of "., ." where . is any symbol
                print("Manga ID: " + str(manga.id) + " Genre: " + manga.genre)
                models.append(manga)

        image_json = {}
        for anime_file_num in os.listdir(data_folder + jikan_anime):
            with open(data_folder + jikan_anime +
                      anime_file_num) as anime_datafile:
                print("anime: " + anime_file_num)
                anime_json_data = json.load(anime_datafile)

                image_json[anime_json_data["image"]] = anime_json_data

        for manga_file_num in os.listdir(data_folder + jikan_manga):
            with open(data_folder + jikan_manga +
                      manga_file_num) as manga_datafile:
                print("manga: " + manga_file_num)
                manga_json_data = json.load(manga_datafile)

                image_json[manga_json_data["image"]] = manga_json_data

        for model in models:
            # print(image_json[model.picture]['genre'])
            genre = image_json[model.picture]['genre']
            if type(genre) is dict:
                print(genre["name"])
                model.genre = genre["name"]
            if type(genre) is list:
                print(genre[1])
                model.genre = genre[1]

        db.session.commit()
Example #31
0
def create_app(config="app.config.Config"):
    app = Flask(__name__)

    # Set Config
    app.config.from_object(config)

    with app.app_context():
        # Create Database(if it doesn't created)
        url = create_database()

        # Set MySQL's charset to utf8mb4 forcely
        app.config["SQLALCHEMY_DATABASE_URI"] = str(url)

        # Set Redis Session
        app.session_interface = redis.RedisSessionInterface()

        # Register Database
        db.init_app(app)

        # Create DB Session & Engine (if db is not defined, create db too.)
        db.create_all()

        # Set ReCaptcha
        if is_setup():
            app.config["RECAPTCHA_SITE_KEY"] = get_config("recaptcha_site_key")
            app.config["RECAPTCHA_SECRET_KEY"] = get_config(
                "recaptcha_secret_key")

        recaptcha.init_app(app)

        # Initialization
        init_template_globals(app)
        init_request_processors(app)

        # Cache Initialization
        cache.init_app(app)
        app.cache = cache

        from app.admin import admin
        from app.handler import page_not_found, forbidden, general_error, gateway_error, too_many_requests

        app.register_blueprint(admin)

        # Error Handler
        app.register_error_handler(403, forbidden)
        app.register_error_handler(404, page_not_found)
        app.register_error_handler(429, too_many_requests)
        app.register_error_handler(500, general_error)
        app.register_error_handler(502, gateway_error)

        return app
Example #32
0
def create_app():
    APP_ROOT = os.path.join(os.path.dirname(__file__), "..")
    app = Flask(__name__, instance_path=os.path.join(APP_ROOT, "instance"))

    # Environment configurations
    APP_ROOT = os.path.join(os.path.dirname(__file__), "..")
    dotenv_path = os.path.join(APP_ROOT, ".env")
    load_dotenv(dotenv_path)
    app.config.from_object('config.settings.' + os.environ.get('FLASK_ENV'))

    # Initialize extensions
    db.init_app(app)
    ma.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)
    migrate.init_app(app, db)

    from app.models import Model
    from app.models.Model import User, Task

    with app.app_context():
        # create DB tables
        db.create_all()

        # Small HTTP Error Handling
        @app.errorhandler(404)
        def not_found(error):
            title = 'page not found'
            return render_template('errors/404.html', title=title), 404

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

        # blueprint for auth routes in our app
        from app.views.auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint)

        # blueprint for non-auth parts of app
        from app.views.home import home as home_blueprint
        app.register_blueprint(home_blueprint)

        # blueprint for tasks
        from app.views.task import task as task_blueprint
        app.register_blueprint(task_blueprint)

        # blueprint for categories
        from app.views.category import category as category_blueprint
        app.register_blueprint(category_blueprint)

        return app
Example #33
0
def create_app():
    app = Flask(__name__, static_folder=static_folder)

    try:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ[
            'OPENSHIFT_MYSQL_DB_URL'] + os.environ['OPENSHIFT_APP_NAME']
    except KeyError:
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}'.format(
            os.path.abspath(
                os.path.join(app.root_path, '..', 'data-dev.sqlite')))

    app.config['THEME_PATHS'] = (os.path.join(
        os.environ.get('OPENSHIFT_DATA_DIR', app.root_path), 'themes'), )

    cfg_folder = os.environ.get('OPENSHIFT_DATA_DIR', app.root_path)

    if not os.path.exists(os.path.join(cfg_folder, 'config.yml')):
        make_config(cfg_folder)
        if 'OPENSHIFT_DATA_DIR' in os.environ:
            shutil.copytree(os.path.join(app.root_path, 'static'),
                            os.path.join(cfg_folder, 'static'))
            shutil.copytree(os.path.join(app.root_path, 'themes'),
                            os.path.join(cfg_folder, 'themes'))

    with open(os.path.join(cfg_folder, 'config.yml')) as f:
        app.config.update(yaml.load(f))

    # Database / Admin
    db.init_app(app)
    themes.init_themes(app, app_identifier='WikiWizard')
    login_manager.init_app(app)
    with app.app_context():
        try:
            User.query.all()
        except (OperationalError, ProgrammingError):
            db.create_all()
            install_data()
    # From Flask-Bootstrap
    app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter
    app.jinja_env.filters['css_sanitized'] = css_sanitizer
    app.jinja_env.add_extension(WikiInclude)

    # URL Rules / Blueprints
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # Admin view
    from admin import create_admin
    create_admin(app)

    return app
Example #34
0
def create_app():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = SECRET_KEY  # For flash messages

    # Configure the database
    app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.init_app(app)
    migrate.init_app(app, db)

    # Configure routes - register each route we have with the app
    app.register_blueprint(home_routes)
    app.register_blueprint(model_routes)
    return app
Example #35
0
def create_app(env, additional_settings={}):
    logger.info('Environment in __init__: "%s"', env)
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object(config[env])

    config[env].init_app(app)
    app.config.update(additional_settings)

    db.init_app(app)

    # Blueprints
    app.register_blueprint(api_v1_blueprint, url_prefix='/api/v1')

    return app
Example #36
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('../config.py')

    app.register_blueprint(pdvs, url_prefix='/')

    db.init_app(app)

    migrate = Migrate(app, db)

    from app import models

    return app
Example #37
0
def create_app(config_file):
    app = Flask(__name__)
    app.config.from_object(config_file)

    db.init_app(app)

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

    app.register_blueprint(error.app)
    app.register_blueprint(entry.app)
    app.register_blueprint(user.app)

    return app
Example #38
0
def create_app():
    app = Flask(__name__)
    CORS(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = db_file_uri

    from app.models import db
    migrate = Migrate(app, db)
    db.init_app(app)

    app.register_blueprint(home.bp)
    app.register_blueprint(questions.bp)
    app.register_blueprint(items.bp)

    return app
Example #39
0
def create_app(config):
    app = Flask(__name__)
    app.config.from_object(config)

    from app.models import db, migrate, ma
    db.init_app(app)
    migrate.init_app(app, db)
    ma.init_app(app)

    from app.routes import api, cors
    cors.init_app(app)
    app.register_blueprint(api)

    return app
Example #40
0
def init(**config_overrides):

    handler = RotatingFileHandler(
        LOG_FILENAME,
        maxBytes=1024 * 1024 * 100,
        backupCount=20
    )
    handler.setLevel(logging.INFO)
    app.logger.addHandler(handler)

    # apply overrides
    app.config.update(config_overrides)

    db.init_app(app)
Example #41
0
 def setUp(self):
     app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///aafood-test.db'
     app.config['REDIS_URL'] = 'redis://localhost:6379/30'
     app.config['TESTING'] = True
     self.app = app.test_client()
     with app.app_context():
         db.init_app(app)
         if os.path.exists('app/aafood.db') == True:
             #TODO: 未來的 DB 從 production 複製過去
             shutil.copyfile('app/aafood.db', 'app/aafood-test.db')
         if os.path.exists("app/aafood-test.db") == False:
             db.create_all()
             add_data()
         redis_store.init_app(app)
Example #42
0
def Create_app():
    app = Flask(__name__,
                static_folder=STATIC_PATH,
                template_folder=TEMPLATE_PATH)
    # 配置
    app.config.from_object(Conf)
    # 注册蓝图
    app.register_blueprint(blueprint=u_blue,url_prefix='/user')
    app.register_blueprint(blueprint=o_blue,url_prefix='/order')
    app.register_blueprint(blueprint=h_blue,url_prefix='/house')
    # 初始化各种第三方库
    db.init_app(app)

    return app
Example #43
0
def create_app(app_config, db_config):
    app = Flask(__name__)
    app.config.from_object(app_config)
    app.config.update(SECRET_KEY=urandom(16),
                      SQLALCHEMY_DATABASE_URI=db_config.URI)

    from .views.pages import blue_view
    app.register_blueprint(blue_view)

    from app.models import db
    db.init_app(app)

    socketio.init_app(app, logger=True, engineio_logger=True)
    return app
Example #44
0
def create_app(config: Dict[str, Any] = None) -> Flask:
    app = Flask(__name__)

    app.config.from_object("app.config")
    if config:
        app.config.update(config)

    for url, blueprint in ACTIVE:
        app.register_blueprint(blueprint, url_prefix=url)

    db.init_app(app)
    Migrate(app, db)

    return app
Example #45
0
def create_app():
    app = Flask(__name__, static_folder=static_folder)

    try:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['OPENSHIFT_MYSQL_DB_URL'] + os.environ['OPENSHIFT_APP_NAME']
    except KeyError:
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{0}'.format(
            os.path.abspath(os.path.join(app.root_path, '..', 'data-dev.sqlite')))

    app.config['THEME_PATHS'] = (os.path.join(os.environ.get('OPENSHIFT_DATA_DIR', app.root_path), 'themes'), )

    cfg_folder = os.environ.get('OPENSHIFT_DATA_DIR', app.root_path)

    if not os.path.exists(os.path.join(cfg_folder, 'config.yml')):
        make_config(cfg_folder)
        if 'OPENSHIFT_DATA_DIR' in os.environ:
            shutil.copytree(os.path.join(app.root_path, 'static'), os.path.join(cfg_folder, 'static'))
            shutil.copytree(os.path.join(app.root_path, 'themes'), os.path.join(cfg_folder, 'themes'))

    with open(os.path.join(cfg_folder, 'config.yml')) as f:
        app.config.update(yaml.load(f))

    # Database / Admin
    db.init_app(app)
    themes.init_themes(app, app_identifier='WikiWizard')
    login_manager.init_app(app)
    with app.app_context():
        try:
            User.query.all()
        except (OperationalError, ProgrammingError):
            db.create_all()
            install_data()
    # From Flask-Bootstrap
    app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter
    app.jinja_env.filters['css_sanitized'] = css_sanitizer
    app.jinja_env.add_extension(WikiInclude)

    # URL Rules / Blueprints
    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    # Admin view
    from admin import create_admin
    create_admin(app)

    return app
Example #46
0
def create_app(config=None, environment=None):
    app = Flask(__name__)
    app.config['ENVIRONMENT'] = environment
    app.config.load()
    app.config.update(config or {})
    if not (app.config['ENVIRONMENT'] == 'development' or
            app.config['TESTING']):
        app.config['SERVER_NAME'] = app.config['SITE_URL']

    security.init_app(app, user_datastore)
    db.init_app(app)
    admin.init_app(app)
    app.register_blueprint(index_bp)

    register_processors(app)

    return app
Example #47
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    login_manager.init_app(app)

    from main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from ajax import ajax as ajax_blueprint
    app.register_blueprint(ajax_blueprint, url_prefix='/ajax')

    patch_request_class(app, size=16*1024*1024) # 16MB
    configure_uploads(app, resource_uploader)

    return app
Example #48
0
def create_app():
    '''
    Create an instance of the app.
    '''
    app = Flask(__name__, template_folder="templates")

    ordbok = FlaskOrdbok(app)
    ordbok.load()

    app.config.update(ordbok)
    #app.config.update(config or {})

    app.register_blueprint(views)

    babel.init_app(app)
    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    bcrypt.init_app(app)
    #security.init_app(app, bcrypt)
    s3.init_app(app)
    configure_uploads(app, (photos))

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

    db.init_app(app)
    #login_manager.init_app(app)
    assets.init_app(app)

    app.jinja_env.filters['slug'] = lambda x: slugify(x).lower()
    app.jinja_env.filters['noop'] = lambda x: ''

    # Constant that should be available for all templates.
    app.jinja_env.globals['ORG_TYPES'] = ORG_TYPES
    app.jinja_env.globals['CONTENT'] = CONTENT
    app.jinja_env.globals['NOI_COLORS'] = NOI_COLORS
    app.jinja_env.globals['LEVELS'] = LEVELS
    app.jinja_env.globals['DOMAINS'] = DOMAINS
    app.jinja_env.globals['QUESTIONS_BY_ID'] = QUESTIONS_BY_ID

    return app
def create_app():
    """Generates an instance of the app.

    This function contains all the config values
    for the different parts of the app; it returns
    a variable 'app' that contains all these values
    for use throughout the rest of the application.
    """
    app = Flask(__name__)

    # Sets the application into debug mode
    app.debug = True

    # Sets configuration variables used application-wise
    app.config['SECRET_KEY'] = 'vYqTMY88zsuXSG7R4xYdPxYk'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///../database.db'

    # Configures SQLAlchemy
    db.init_app(app)

    # Configures the login manager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'  # Sets the login view.
    login_manager.login_message_category = 'warning'

    # Loads the current user by running a query on the id
    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    # Configures application blueprints
    from app.controllers.main import main
    app.register_blueprint(main)
    
    from app.controllers.auth import auth
    app.register_blueprint(auth)
    
    from app.controllers.ajax import ajax
    app.register_blueprint(ajax)

    return app
Example #50
0
def create_app(object_name, env="prod"):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. app.settings.ProdConfig

        env: The name of the current environment, e.g. prod or dev
    """

    app = Flask(__name__)

    app.config.from_object(object_name)
    app.config["ENV"] = env

    # initialize the cache
    cache.init_app(app)

    # initialize the debug tool bar
    debug_toolbar.init_app(app)

    # initialize SQLAlchemy
    db.init_app(app)

    # Use Foundation for templating
    Foundation(app)

    login_manager.init_app(app)

    # Import and register the different asset bundles
    assets_env.init_app(app)
    assets_loader = PythonAssetsLoader(assets)
    for name, bundle in assets_loader.load_bundles().items():
        assets_env.register(name, bundle)

    # register our blueprints
    app.register_blueprint(main)
    app.register_blueprint(notebook)

    return app
Example #51
0
def create_app(config_file):
    app = Flask(__name__)
    app.config.from_pyfile(config_file)

    from app.models import db
    db.app = app
    db.init_app(app)
    with app.app_context():
        db.create_all()

    if config_file == 'config_dev.py':
        from app.models import User
        admin_user = User("admin", "*****@*****.**", "Th1515NOT53cur3")
        admin_user.is_admin = True
        admin_user.zipcode = 80915
        admin_user.viewable = True
        db.session.add(admin_user)
        db.session.commit()

    app.register_blueprint(home)
    app.register_blueprint(auth)
    app.register_blueprint(market)
    app.register_blueprint(comm)
    app.register_blueprint(admin)
    app.debug = True

    from app.login_manager import lm
    lm.init_app(app)
    lm.login_view = 'auth.login'
    lm.login_message = u"You must be logged in to access that page."
    
    from app.email import mail
    mail.init_app(app)
    
    resize.init_app(app)

    from app.models import Item
    whooshalchemy.whoosh_index(app, Item)

    toolbar = DebugToolbarExtension(app)

    return app
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.models import db
    db.init_app(app)

    # Blueprints   
    from app.users.views import users
    app.register_blueprint(users, url_prefix='/api/v1/users')
    
    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
        return response

    return app
    
Example #53
0
def create_app(test=False):
    app = Flask(__name__)
    if test:
        app.config.from_object("config.TestingConfig")
    else:
        app.config.from_object(os.environ['APP_SETTINGS'])

    from app.models import db
    db.init_app(app)

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

    if os.environ.get('HEROKU') is not None:
        import logging
        stream_handler = logging.StreamHandler()
        app.logger.addHandler(stream_handler)
        app.logger.setLevel(logging.INFO)
        app.logger.info('monkeygrape startup')

    return app
Example #54
0
def init_database():
    db.app = app
    db.init_app(app)
    db.create_all()

    # add users, if they doesn't exist
    if not db.session.query(Player).filter(Player.name == 'Daniel').all():
        db.session.add(Player(name='Daniel', email='*****@*****.**', twitter='volrath'))
    if not db.session.query(Player).filter(Player.name == 'Pedro').all():
        db.session.add(Player(name='Pedro', email='*****@*****.**', twitter='pedrojosep'))
    if not db.session.query(Player).filter(Player.name == 'Julio').all():
        db.session.add(Player(name='Julio', email='*****@*****.**', twitter='jccb'))
    if not db.session.query(Player).filter(Player.name == 'Kristoffer').all():
        db.session.add(Player(name='Kristoffer', email='*****@*****.**', twitter='kpantic'))
    if not db.session.query(Player).filter(Player.name == 'Alberto').all():
        db.session.add(Player(name='Alberto', email='*****@*****.**', twitter='alb3rto269'))
    if not db.session.query(Player).filter(Player.name == 'German').all():
        db.session.add(Player(name='German', email='*****@*****.**', twitter=''))

    # create.
    db.session.commit()
Example #55
0
def create_app(object_name):
    """
    An flask application factory, as explained here:
    http://flask.pocoo.org/docs/patterns/appfactories/

    Arguments:
        object_name: the python path of the config object,
                     e.g. appname.settings.ProdConfig
    """

    app = Flask(__name__)

    app.config.from_object(object_name)


    # initialize SQLAlchemy
    db.init_app(app)

    # register our blueprints
    app.register_blueprint(main)

    return app
def create_app(config_name):
    app = Flask(__name__)
    
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    bootstrap = Bootstrap()
    bootstrap.init_app(app)

    from app.models import db
    db.init_app(app)
    
    from app.models import login_manager
    login_manager.session_protection = 'strong'
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)
    
    from app.email import mail
    mail.init_app(app)

    if not app.debug and not app.testing:
        from flask.ext.sslify import SSLify
        sslify = SSLify(app)

    from app.blueprints.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from app.blueprints.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    # Add additional blueprints here...
    # example:
    # from .myblueprint import myblueprint as myblueprint_blueprint
    # app.register_blueprint(myblueprint_blueprint, url_prefix='/myblueprint')

    return app
Example #57
0
__author__ = 'motomizuki'

from flask import Flask
from app.api.auth import module as auth
from app.api.users import module as users
from app.api.companies import module as companies
from app.models import db

# flask app
app = Flask(__name__)
app.config['SECRET_KEY'] = 'adf|SW+k64vKielnfEg23/+'

# database settings
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://vagrant:vagrant@localhost:3306/vagrant'
db.init_app(app)

# blueprint modules
app.register_blueprint(auth, url_prefix='/api/auth')
app.register_blueprint(users, url_prefix='/api/users')
app.register_blueprint(companies, url_prefix='/api/companies')
Example #58
0
def create_app(config=None): #pylint: disable=too-many-statements
    '''
    Create an instance of the app.
    '''
    app = Flask(__name__)

    with open('/noi/app/config/config.yml', 'r') as config_file:
        app.config.update(yaml.load(config_file))

    app.config['CELERYBEAT_SCHEDULE'] = CELERYBEAT_SCHEDULE

    if config is None:
        try:
            with open('/noi/app/config/local_config.yml', 'r') as config_file:
                app.config.update(yaml.load(config_file))
        except IOError:
            app.logger.warn("No local_config.yml file")
    else:
        app.config.update(config)

    # Confirming email is currently unsupported.
    app.config['SECURITY_CONFIRMABLE'] = False

    with open('/noi/app/data/deployments.yaml') as deployments_yaml:
        deployments = yaml.load(deployments_yaml)

    l10n.configure_app(app)

    app.register_blueprint(views)
    if app.config['DEBUG']:
        app.register_blueprint(style_guide.views)

        try:
            from flask_debugtoolbar import DebugToolbarExtension
            debug_toolbar = DebugToolbarExtension(app)
        except:
            app.logger.exception('Initialization of Flask-DebugToolbar '
                                 'failed.')

    if not app.config['DEBUG'] and app.config.get('ADMINS'):
        email_errors.init_app(app)

    cache.init_app(app)
    csrf.init_app(app)
    mail.init_app(app)
    bcrypt.init_app(app)
    s3.init_app(app)
    #configure_uploads(app, (photos))

    # Setup Flask-Security
    user_datastore = DeploySQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, datastore=user_datastore,
                      login_form=NOILoginForm,
                      register_form=NOIRegisterForm,
                      forgot_password_form=NOIForgotPasswordForm,
                      reset_password_form=NOIResetPasswordForm,
                      change_password_form=NOIChangePasswordForm)

    db.init_app(app)
    alchemydumps.init_app(app, db)
    #login_manager.init_app(app)
    assets.init_app(app)

    app.jinja_env.filters['slug'] = lambda x: slugify(x).lower()

    noi_deploy = app.config['NOI_DEPLOY']
    if noi_deploy == '_default':
        app.logger.warn('No NOI_DEPLOY found in config, deploy-specific '
                        'attributes like the About page, custom domains and '
                        'logos will be missing.')
    this_deployment = deployments.get(noi_deploy, deployments['_default'])
    default_deployment = deployments['_default']
    if 'locale' in this_deployment:
        app.config['BABEL_DEFAULT_LOCALE'] = this_deployment['locale']
    app.config['SEARCH_DEPLOYMENTS'] = this_deployment.get('searches', []) or []
    app.config['SEARCH_DEPLOYMENTS'].append(noi_deploy)
    babel.init_app(app)
    l10n.init_app(app)
    admin.init_app(app)

    app.config['DOMAINS'] = this_deployment.get('domains',
                                                default_deployment['domains'])

    app.config['CONTACT_FORM_ID'] = this_deployment.get('contact_form_id',
                                                default_deployment['contact_form_id'])

    # Constants that should be available for all templates.

    global_config_json = {}

    for exposed_var in EXPOSED_APP_CONFIG_VARS:
        if exposed_var in app.config:
            global_config_json[exposed_var] = app.config[exposed_var]

    global_config_json = json.dumps(global_config_json)

    app.jinja_env.globals['global_config_json'] = global_config_json
    app.jinja_env.globals['get_locale'] = get_locale
    app.jinja_env.globals['NOI_DEPLOY'] = noi_deploy
    app.jinja_env.globals['ORG_TYPES'] = ORG_TYPES
    app.jinja_env.globals['NOI_COLORS'] = NOI_COLORS
    app.jinja_env.globals['LEVELS'] = LEVELS
    app.jinja_env.globals['LEVELS_BY_SCORE'] = LEVELS_BY_SCORE
    app.jinja_env.globals['QUESTIONS_BY_ID'] = QUESTIONS_BY_ID
    app.jinja_env.globals['QUESTIONNAIRES_BY_ID'] = QUESTIONNAIRES_BY_ID

    app.jinja_env.globals['ABOUT'] = this_deployment.get('about',
                                                         default_deployment['about'])

    if not app.config.get('MAIL_USERNAME') or not app.config.get('MAIL_PASSWORD'):
        app.logger.warn('No MAIL_SERVER found in config, password reset will '
                        'not work.')

    if not app.config.get('GA_TRACKING_CODE'):
        app.logger.warn('No GA_TRACKING_CODE found in config, analytics will'
                        ' not work.')

    # Order questionnaires for deployments that want custom order.
    questionnaire_order = this_deployment.get('questions',
                                              default_deployment['questions'])
    if questionnaire_order:
        new_order = []
        for topic in questionnaire_order:
            if isinstance(topic, basestring):
                q_id = topic
                custom_description = None
            else:
                q_id = topic.keys()[0]
                custom_description = topic[q_id].get('description')

            try:
                questionnaire = [q for q in QUESTIONNAIRES if q['id'] == q_id][0]
                if custom_description:
                    questionnaire['description'] = custom_description
                new_order.append(questionnaire)
                #new_order.append(filter(lambda q: q['id'] == q_id, QUESTIONNAIRES)[0])
            except IndexError:
                raise Exception('Cannot find questionairre ID "{}", aborting'.format(
                    q_id))
        app.jinja_env.globals['QUESTIONNAIRES'] = new_order
    else:
        app.jinja_env.globals['QUESTIONNAIRES'] = QUESTIONNAIRES

    # Signals
    @user_registered.connect_via(app)
    def add_deployment_role(sender, **kwargs):
        """
        Add role for this deployment whenever a new user registers.
        """
        user = kwargs['user']
        try:
            role = Role.query.filter_by(name=sender.config['NOI_DEPLOY']).one()
        except NoResultFound:
            role = Role(name=sender.config['NOI_DEPLOY'])
            db.session.add(role)

        user.roles.append(role)
        db.session.add(user)
        db.session.commit()

    sass.init_app(app)
    csp.init_app(app)

    if app.config.get('BASIC_AUTH_FORCE'):
        from flask.ext.basicauth import BasicAuth

        basic_auth = BasicAuth()
        basic_auth.init_app(app)

    return app
Example #59
0
def init_db(app):
    db.init_app(app)
    with app.app_context():
        db.create_all()
Example #60
0
# -*- coding: utf-8 -*-

from flask import Flask
from app.models import db
from app.routes import bp_account, bp_transaction

api = Flask(__name__)

api.register_blueprint(bp_account)
api.register_blueprint(bp_transaction)

with api.app_context():
    api.config.from_pyfile('../config.py', silent=True)
    db.init_app(api)
    db.create_all()