Esempio n. 1
0
def create_app(configuration):
    app = Flask(__name__)
    app.config.from_object(configuration)
    db.init_app(app)
    login_manager.init_app(app)
    add_resources(app)
    return app
Esempio n. 2
0
def create_app() -> Flask:
    """返回app对象"""
    app = Flask(__name__, template_folder=None, static_folder=None)
    # 配置app
    app.config.from_object(Config)
    # 初始化扩展插件
    app_db.init_app(app)
    ma.init_app(app)
    # search.init_app(app)
    mail.init_app(app)

    # 中间件
    pb_before_request_funcs_map = {}
    pb_after_request_funcs_map = {}
    for bp in bp_list:
        pb_before_request_funcs_map[bp.name] = before_request_funcs
        pb_after_request_funcs_map[bp.name] = after_request_funcs
    app.before_request_funcs = pb_before_request_funcs_map
    app.after_request_funcs = pb_after_request_funcs_map

    for bp in bp_list:  # 注册蓝图
        app.register_blueprint(bp)

    app.register_error_handler(Exception, handler_error)  # 注册异常处理

    return app
Esempio n. 3
0
def create():
	app = Flask(__name__)
	app.config.from_object(Config)
	db.init_app(app)
	lm.init_app(app)
	degrade()
	with app.test_request_context():
		db.create_all()
	import app.test as test
	app.register_blueprint(test.module)
	import app.create as create
	app.register_blueprint(create.module)
	import app.login as login
	app.register_blueprint(login.module)
	import app.index as index
	app.register_blueprint(index.module)
	import app.get as get
	app.register_blueprint(get.module)
	import app.add as add
	app.register_blueprint(add.module)
	import app.change as change
	app.register_blueprint(change.module)
	import app.remove as remove
	app.register_blueprint(remove.module)
	import app.post as post
	app.register_blueprint(post.module)
	return app
Esempio n. 4
0
def create_app(settings_module):
    app = Flask(__name__, instance_relative_config=True)
    # Load the config file specified by the APP environment variable
    app.config.from_object(settings_module)
    # Load the configuration from the instance folder
    if not app.config.get('TESTING', False):
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_pyfile('config-testing.py', silent=True)

    configure_logging(app)

    # Init third party modules
    db.init_app(app)
    ma.init_app(app)
    migrate.init_app(app, db)
    init_celery(app)

    # Init custom modules
    weather.init_app(app)

    # Catch al 404 errors
    Api(app, catch_all_404s=True)

    # Disable strict slashes
    app.url_map.strict_slashes = False

    # Blueprints registration
    app.register_blueprint(weather_bp)
    app.register_blueprint(weather_api_bp)

    # Custom error handlers
    register_error_handlers(app)

    return app
Esempio n. 5
0
    def init_app(app):
        Config.init_app(app)
        with app.app_context():

            from app.db import db
            from app.models import User
            from app.models import Plan

            db.init_app(app)
            db.create_all()

            # check if plans exist
            if len(Plan.query.all()) != 4:
                p1 = Plan(id=1, name='free', description='All the basic features of SupportService', cost=0)
                db.session.add(p1)
                p2 = Plan(id=2, name='bronze', description='Everything in free and email support.', cost=25)
                db.session.add(p2)
                p3 = Plan(id=3, name='silver', description='Everything in bronze and chat support.', cost=50)
                db.session.add(p3)
                p4 = Plan(id=4, name='gold', description='Everything in silver and 99.999% uptime SLA!', cost=50)
                db.session.add(p4)
                db.session.commit()

            # check if user exists
            if User.query.filter_by(email='*****@*****.**').first() is None:
                app.logger.info("Creating test user: [email protected] password: test")
                u = User(email='*****@*****.**')
                u.set_password('test')
                db.session.add(u)
                db.session.commit()
            else:
                app.logger.info("You can login with user: [email protected] password: test")
Esempio n. 6
0
def create_app(config_name):
    """Create an application instance."""
    app = Flask(__name__)

    # import configuration
    cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
    app.config.from_pyfile(cfg)

    # initialize extensions
    bootstrap.init_app(app)
    bs_init_app(app)
    db.init_app(app)
    lm.init_app(app)
    socketio.init_app(app,
                      async_mode='eventlet',
                      message_queue='redis://127.0.0.1:6379')

    env_assets.init_app(app)
    env_assets.register(bundles)

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

    return app
def create_app(env="DEFAULT"):
    app = Flask(__name__)
    app.config.from_object(get_config(env))

    app.register_blueprint(auth_bp)
    app.register_blueprint(shops_bp)
    app.register_blueprint(products_bp)

    db.init_app(app)
    login.init_app(app)
    db.drop_all(app=app)

    migrate.init_app(app, db)

    with app.app_context():
        db.create_all()
        """Some default data"""
        db.session.add(user_1)
        db.session.add(user_2)
        db.session.add(shop_1)
        db.session.add(shop_2)
        db.session.add(category_1)
        db.session.add(category_2)
        db.session.add(product_1)
        db.session.add(product_2)
        shop_1.products.append(product_2)
        db.session.commit()

    return app
def create_app(config=DevelopmentConfig):
    app = Flask(__name__)
    migrate = Migrate(app, db)
    csrf = CSRFProtect(app)
    app.config.from_object(config)
    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'

    login_manager.init_app(app)
    db.init_app(app)
    ma.init_app(app)
    csrf.init_app(app)

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

    # register each active blueprint
    for url, blueprint in ACTIVE_ENDPOINTS:
        app.register_blueprint(blueprint, url_prefix=url)

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

    @app.route('/spec')
    def spec():
        swag = swagger(app)
        swag['info']['version'] = "1.0.0"
        swag['info']['title'] = "pygroup-Web"
        swag['info']['description'] = "My shop example using Flask"
        return jsonify(swag)

    app.register_blueprint(swagger_blueprint, url_prefix=SAWGGER_URL)

    return app
Esempio n. 9
0
def create_app():
    app = Flask(__name__)
    CORS(app)

    #Configura la api con los parametros asignados en config/default
    app.config.from_object(defaultConfig)

    # Inicializa las extensiones
    db.init_app(app)
    ma.init_app(app)
    migrate.init_app(app, db)

    # Captura todos los errores 404
    Api(app, catch_all_404s=True)

    # Deshabilita el modo estricto de acabado de una URL con /
    app.url_map.strict_slashes = False

    # Registra los blueprints
    app.register_blueprint(SolicitudCreditosbp)

    # Registra manejadores de errores personalizados
    register_error_handlers(app)

    return app
Esempio n. 10
0
def create_app():
    """
    App factory pattern avoids circular imports, so instead of importing
    'app' directly you import its factory. If you need the current running app
    you can use 'from flask import current_app'
    :return: app
    """
    app = Flask(__name__)
    config_name = os.environ.get('FLASK_CONFIG') or 'development'
    cfg = os.path.join(os.getcwd(), 'config', config_name + '.py')
    app.config.from_pyfile(cfg)

    # initialize extensions
    bootstrap.init_app(app)
    db.init_app(app)

    # import blueprints
    from app.dashboard.views import dashboard_blueprint
    from app.operatingsystem.views import os_blueprint
    from app.project.views import project_blueprint
    from app.release.views import release_blueprint
    from app.testrun.views import run_blueprint

    app.register_blueprint(dashboard_blueprint)
    app.register_blueprint(os_blueprint)
    app.register_blueprint(project_blueprint)
    app.register_blueprint(release_blueprint)
    app.register_blueprint(run_blueprint)

    configure_admin(app, db)

    db.create_all(app=app)

    return app
Esempio n. 11
0
def create_app():
    """
    flask application initialization skeleton

    :return Flask:
    """
    app_dir_path = os.path.dirname(os.path.realpath(__file__))
    root_path = os.path.abspath(os.path.join(app_dir_path, os.pardir))
    app = Flask(__name__, instance_relative_config=True, root_path=root_path)

    app.config.from_object(os.getenv('APP_SETTINGS', 'app.config.LocalConfig'))

    if os.path.exists(os.path.join(app.instance_path, 'log_config.conf')):
        fileConfig(os.path.join(app.instance_path, 'log_config.conf'),
                   defaults={
                       'logfilename':
                       os.path.join(app.root_path,
                                    app.config.get('LOGFILE_PATH'))
                   },
                   disable_existing_loggers=False)

    with app.app_context():
        from app.api import api
        from app.db import db
        from app.routes import configure_routes

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

        db.create_all()

    return app
Esempio n. 12
0
def create_app(config_filename):
    app = Flask(__name__,
                static_url_path='',
                static_folder='../static',
                template_folder='../static')

    app.config.from_object(config_filename)
    # app.response_class = MyResponse

    from app.db import db, Difficult, Cheer, Tag

    db.init_app(app)

    # app.config['FLASK_ADMIN_SWATCH'] = 'cerulean'
    # admin = Admin(app, name='corona', template_mode='bootstrap3')
    # admin.add_view(ModelView(Difficult, db.session))
    # admin.add_view(ModelView(Cheer, db.session))
    # admin.add_view(ModelView(Tag, db.session))

    # Blueprints
    from app.difficult.views import difficult_bp
    from app.cheer.views import cheer_bp
    from app.tag.views import tag_bp
    from app.data.views import data_bp
    # limiter = Limiter(app, default_limits=["2/second"], key_func=get_remote_address)
    # limiter.limit("1/second")(difficult_bp)

    app.register_blueprint(difficult_bp, url_prefix='/api/difficult')
    app.register_blueprint(cheer_bp, url_prefix='/api/cheer')
    app.register_blueprint(tag_bp, url_prefix='/api/tag')
    app.register_blueprint(data_bp, url_prefix='/api/data')
    CORS(app)
    return app
Esempio n. 13
0
def create_app(settings_module):
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(settings_module)

    # Inicializa las extensiones
    db.init_app(app)
    ma.init_app(app)
    jwt.init_app(app)
    migrate.init_app(app, db)

    # Captura todos los errores 404
    Api(app, catch_all_404s=True)

    # Deshabilita el modo estricto de acabado de una URL con /
    app.url_map.strict_slashes = False

    # Registra los blueprints
    app.register_blueprint(user_v1_0_bp)
    app.register_blueprint(auth_v1_0_bp)
    app.register_blueprint(documents_v1_0_bp)

    # Registra manejadores de errores personalizados
    register_error_handlers(app)

    return app
Esempio n. 14
0
def create_app(config=DevelopmentConfig):
    """Create the application.

    This function is the application factory, which creates an instance of
    the application with the specified configuration class. This includes
    initializing all flask extensions and registering blueprints and routes.
    """

    # create application with specified config
    app = Flask(__name__)
    app.config.from_object(config)
    # allow hardcoded configs to be overriden by an external file
    if os.getenv('FLASK_CONFIG') is not None:
        app.config.from_envvar('FLASK_CONFIG')

    # register extensions
    bootstrap.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)

    # register blueprints
    app.register_blueprint(api_bp, url_prefix='/api/v1')
    app.register_blueprint(webapp_bp)

    return app
Esempio n. 15
0
def create_app():
    app = Flask(__name__)
    app.config.from_pyfile("config.py")
    db.init_app(app)

    # init process migration
    # export(set) FLASK_APP=app && flask db init
    migrate = Migrate(app, db)

    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = "user.login"

    app.register_blueprint(user_blueprint)
    app.register_blueprint(news_blueprint)
    app.register_blueprint(admin_blueprint)

    # when user open page, login manager get from cookies user_id
    # and put user_id func load_user
    @login_manager.user_loader
    def load_user(user_id):
        return User.query.get(user_id)

    @app.route('/')
    def index():
        title = "Блог"
        content_title = "Ежедневные заметки"
        weather = weather_by_city(current_app.config["WEATHER_DEFAULT_CITY"])
        print(weather)
        return render_template("index.html",
                               title=title,
                               content_title=content_title,
                               weather=weather)

    return app
Esempio n. 16
0
def create_app(config_name='default'):
    """
    Starts up the Flask application based on the supplied configuration
    :param config_class: Configuration to start the app with
    :type config_class:
    :return: the Flask app
    :rtype:
    """
    app = Flask(__name__)
    app.config.from_object(app_config[config_name])
    app_config[config_name].init_app(app)

    with open("log_config.yaml", 'rt') as f:
        config_data = yaml.safe_load(f.read())
        config.dictConfig(config_data)

    app.logger = logging.getLogger(app.config['LOGGING_CONFIG'])
    app.logger.error('starting the app')

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    csrf.init_app(app)
    cdn.init_app(app)

    oauth.init_app(app)
    oauth.register(
        'auth0',
        client_id=app.config['AUTH0_CLIENT_ID'],
        client_secret=app.config['AUTH0_CLIENT_SECRET'],
        api_base_url=app.config['AUTH0_CLIENT_DOMAIN'],
        access_token_url=app.config['AUTH0_CLIENT_DOMAIN'] + '/oauth/token',
        authorize_url=app.config['AUTH0_CLIENT_DOMAIN'] + '/authorize',
        client_kwargs={
            'scope': 'openid profile email',
        },
    )

    from app.errors.handlers import bp as errors_bp
    from app.auth.routes import bp as auth_bp
    from app.main.routes import bp as main_bp
    from app.support.legal_routes import bp as support_bp
    app.register_blueprint(errors_bp)
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(main_bp)
    app.register_blueprint(support_bp, url_prefix='/support')

    # this filter allows environment variables to be read inside the jinja templates
    app.jinja_env.filters['get_os_env'] = utils.get_os_env

    from app.models import User

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

    return app
Esempio n. 17
0
def create_app():
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_pyfile("config.py", silent=True)
    db.init_app(app)
    ma.init_app(app)
    Migrate(app, db)
    register_route(app)
    return app
Esempio n. 18
0
    def init_app(app):
        Config.init_app(app)
        with app.app_context():
            from app.db import db
            from app.models import User
            from app.models import Plan

            db.init_app(app)
Esempio n. 19
0
def create_app(profile="default"):
    app = Flask(__name__, template_folder="templates/")

    app.config.from_object(config[profile])
    config[profile].init_app(app)
    app.config.from_envvar("AUTH_SETTINGS", silent=True)

    app.logger.setLevel(logging.DEBUG)

    try:
        logfile = os.path.join(app.config["LOGPATH"], "anmeldesystem.log")
        loghandler = logging.handlers.RotatingFileHandler(logfile,
                                                          maxBytes=10**4,
                                                          backupCount=4)
        loghandler.setLevel(logging.WARNING)
        app.logger.addHandler(loghandler)
    except:
        pass

    from app.db import db

    db.init_app(app)
    db.app = app
    app.db = db

    mail = Mail(app)
    app.mail = mail

    # Set up sanity checks.
    from . import sanity

    app.sanity_check_modules = [sanity]

    from flask_bootstrap import Bootstrap

    Bootstrap(app)

    from app.user import user_blueprint, init_app as init_user

    app.register_blueprint(user_blueprint)
    init_user(app)

    from app.oauth2 import oauth2_blueprint, init_app as init_oauth2

    app.register_blueprint(oauth2_blueprint)
    init_oauth2(app)

    from app.api import api_blueprint, init_app as init_api

    app.register_blueprint(api_blueprint)
    init_api(app)

    from app.registration import registration_blueprint, init_app as init_reg

    app.register_blueprint(registration_blueprint)
    init_reg(app)

    return app
Esempio n. 20
0
def db(app):
    _db.init_app(app)
    with app.app_context():
        _db.drop_all()
        _db.create_all()
        print('cleaned the db for a new test case')

        yield _db
        _db.drop_all()
Esempio n. 21
0
def create_app():
    app = Flask(__name__)
    config_obj = config[app.env]
    app.config.from_object(config_obj)
    config_obj.init_app(app)
    app.register_blueprint(routes)
    db.init_app(app)

    return app
Esempio n. 22
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('config.BaseConfig')
    app.register_blueprint(file_upload_bp)
    app.register_blueprint(bank_marketing_bp)
    db.init_app(app)
    db.app = app
    db.create_all()
    return app
Esempio n. 23
0
def setup_app():
    db.init_app(application)

    api = Api(application)

    api.add_resource(UserCreateResource, '/user', methods=['POST'])
    api.add_resource(UserLoginResource, '/login', methods=['POST'])
    api.add_resource(UserProfileResource, "/profile", methods=['GET'])

    return application
Esempio n. 24
0
def setup_app():
    app = Flask(__name__)
    app.config.update(
        GOOGLE_LOGIN_CLIENT_ID=settings.GOOGLE_LOGIN['CLIENT_ID'],
        GOOGLE_LOGIN_CLIENT_SECRET=settings.GOOGLE_LOGIN['CLIENT_SECRET'],
        GOOGLE_LOGIN_REDIRECT_URI=settings.GOOGLE_LOGIN['REDIRECT_URI'],
        GOOGLE_LOGIN_SCOPES='email',
        SECRET_KEY='hackathing_secret')
    db.init_app(app)
    return app, GoogleLogin(app=app)
Esempio n. 25
0
def create_app(config="config.ini"):
    app = Flask(__name__, static_url_path='/static')
    app.config.from_object(__name__)
    if os.path.exists(config):
        app.config.from_pyfile(config)
    else:
        print("The app does not have a config.ini file")
    # Define the WSGI application object
    db.init_app(app)
    return app
Esempio n. 26
0
 def setUp(self):
     self.app = create_app()
     self.app_context = self.app.app_context()
     self.app_context.push()
     self.client = self.app.test_client
     self.data = demo_data
     self.auth_data = auth_data
     db.init_app(self.app)
     Migrate(self.app, db)
     logging.disable(logging.CRITICAL)
Esempio n. 27
0
def create_app(is_test=False):
    app = Flask(__name__, instance_relative_config=True)

    setup_initializers(app, is_test)

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

    app.logger.info("Server started")
    return app
Esempio n. 28
0
def create_app(is_test=False):
    app = Flask(__name__, instance_relative_config=True)
    init_setup(app)
    CORS(app)
    register_routes(app)
    db.init_app(app)
    ma.init_app(app)
    Migrate(app, db)
    init_errorhandler(app)
    init_log(app)
    return app
Esempio n. 29
0
def create_app():
    app = Flask(__name__)
    dbPath = DB_PATH
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(dbPath)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
    db.init_app(app)

    app.register_blueprint(api_blueprint)

    return app
Esempio n. 30
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    cache.init_app(app)
    db.init_app(app)
    api = Api()
    Api_1_0(api)
    api.init_app(app)
    CORS(app, supports_credentials=True)
    # print(app.url_map)
    return app
Esempio n. 31
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)
    login_manager.init_app(app)

    app.register_blueprint(home_blueprint)
    app.register_blueprint(category_blueprint)
    app.register_blueprint(quiz_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(api_blueprint, url_prefix='/api/v1.0')

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

    return app
Esempio n. 32
0
import logging
import os
import re

from flask import Flask, request, abort
from flask.ext.markdown import Markdown

from app.db import db, DataSet, Vote
from app.route import routes


app = Flask(__name__)
app.config.from_object('app.settings')
Markdown(app)

db.init_app(app)
db.app = app
db.create_all()
app.register_blueprint(routes)

app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)


@app.before_request
def before_request():
    if any(re.match(re.escape(ip).replace('\*', '\d+'), request.access_route[-1])
           for ip in os.environ.get('BAN_IPS', '').split(',')):
        abort(403)