Esempio n. 1
0
def create_app(config_objects):
    app = Flask(__name__)

    for config_object in config_objects:
        app.config.from_object(config_object)

    bcrypt.init_app(app)
    login_manager.init_app(app)
    #login view can be specified in settings but defaults to auth.login
    login_manager.login_view = app.config.get('AUTH_LOGIN_VIEW','auth.login')
    login_manager.login_message = app.config.get('AUTH_LOGIN_MESSAGE',None)
    mongo.init_app(app)
    
    from photoback.auth import views as auth
    from photoback.general import views as general
    from photoback.photos import views as photos
    from photoback.opentok import views as opentok
    from photoback.calendar import views as calendar
    from photoback.settings import views as settings


    app.register_blueprint(auth.blueprint)
    app.register_blueprint(general.blueprint)
    app.register_blueprint(photos.blueprint)
    app.register_blueprint(opentok.blueprint)
    app.register_blueprint(calendar.blueprint)
    app.register_blueprint(settings.blueprint)
    return app
def create_app(database):
    global app
    
    # create our little application :)
    app = Flask(__name__)
    app.config.from_object(config)
    app.secret_key = config.SECRET_KEY

    # db import
    from libs.db import init_connection

    # db setup
    if database: init_connection(database)

    # presenters
    from presenters.home import home

    # register modules
    app.register_blueprint(home)

    # template filters
    @app.template_filter('test_format')
    def test_format(input):
        return input[::-1]

    return app
def create_app(config):
    """create flaks app object"""

    # Initialize the App:
    app = Flask(__name__)
    from config import configurations
    app.config.from_object(configurations[config])
    configurations[config].init_app(app)
    app.logger.addHandler(app.config.get('LOG_HANDLER'))
    app.logger.info('App is starting!')

    db.init_app(app)

    # Register the Main Views:
    from .views import api
    app.register_blueprint(api, url_prefix='/api/v1')

    @app.after_request
    def after_request(resp):
        for q in get_debug_queries():
            if q.duration > app.config.get('DB_QUERY_TIMEOUT'):
                app.logger.warning(
                    'SLOW DB STATEMENT: {0}\n\tParameters: {1}\n\tDuration: {2}\n\tContext: {3}'.
                    format(q.statement, q.parameters, q.duration, q.context))
        return resp

    return app
Esempio n. 4
0
    def test_collect(self):
        from tempfile import mkdtemp
        from flask import Flask, Blueprint
        from flask_collect import Collect
        from os import path as op

        app = Flask(__name__)

        blueprint = Blueprint(
            'test1', __name__, static_folder='static1',
            static_url_path='/static/test1')
        app.register_blueprint(blueprint)

        blueprint = Blueprint('test2', __name__, static_folder='static2')
        app.register_blueprint(blueprint)

        static_root = mkdtemp()

        app.config['COLLECT_STATIC_ROOT'] = static_root

        collect = Collect(app)
        collect.collect(verbose=True)

        self.assertTrue(op.exists(op.join(static_root, 'test1', 'test.css')))
        self.assertTrue(op.exists(op.join(static_root, 'js', 'test.js')))
        self.assertTrue(op.exists(op.join(static_root, 'app.css')))

        app.config['COLLECT_STORAGE'] = 'flask.ext.collect.storage.test'
        collect = Collect(app)
        test = collect.collect(verbose=True)
        self.assertTrue(len(test), 2)
Esempio n. 5
0
    def setUp(self):
        self.engine = Engine("op1", "op2")
        self.engine.op1.setup(in_name="in", out_name="middle", required=False)
        self.engine.op2.setup(in_name="middle", out_name="out")

        self.engine.op1.set(OptProductEx())
        foisdouze = OptProductEx("foisdouze")
        foisdouze.force_option_value("factor", 12)
        self.engine.op2.set(foisdouze, OptProductEx())

        egn_view = EngineView(self.engine, name="my_egn")
        egn_view.add_input("in", Numeric(vtype=int, min=-5, max=5))
        egn_view.add_input("middle", Numeric(vtype=int))
        print(self.engine.needed_inputs())
        egn_view.add_output("in")
        egn_view.add_output("middle")
        egn_view.add_output("out")

        api = ReliureAPI()
        api.register_view(egn_view)

        app = Flask(__name__)
        app.config['TESTING'] = True
        app.register_blueprint(api, url_prefix="/api")
        self.app = app.test_client()
Esempio n. 6
0
def create_app(app=None, config_file=None):

    if not app:
        app = Flask(__name__, template_folder="views")

    # Config files
    app.config.from_pyfile("config/base.py")
    if config_file:
    	app.config.from_pyfile("config/{}.py".format(config_file))

    # Extensions
    Foundation(app)
    admin = Admin(app, name='Bolsa de Trabajo', template_mode='bootstrap3')

    """
    CONTROLADORES 
    """
    # Blueprints
    app.register_blueprint(frontend)    

    # Admin Views
    admin.add_view(AdminSkillView(Skill, db.session))
    admin.add_view(AdminStudentView(Student, db.session))
    admin.add_view(AdminCompanyView(Company, db.session))

    return app
Esempio n. 7
0
def lte(app: Flask):
    for blueprint in app.blueprints.values():
        blueprint.jinja_loader = jinja2.ChoiceLoader([
            jinja2.FileSystemLoader(os.path.join(get_root_path('flask_admin_lte'), 'templates/lte')),
            blueprint.jinja_loader,
        ])
    app.register_blueprint(Blueprint('admin_lte', __name__, static_folder='static', static_url_path='/static/lte'))
Esempio n. 8
0
class RootREST:

    def __init__(self, host, run_flask, port):
        self.host = host
        self.port = port
        self.run_flask = run_flask
        self.app = Flask(__name__)
        CORS(self.app,
             resources={
                 r'/*': {
                     'origins': '*',
                     'headers': ['Content-Type']
                 }
             }
        )
        #blueprintRest = BlueprintRest()
        self.app.register_blueprint(bp, url_prefix='/blueprint')
        #self.app.register_blueprint(Blueprint('blueprint', __name__), url_prefix='/blueprint')

        # Root service.
        @self.app.route('/')
        def landing():
            return core.landing_message()

        # Run Flask.
        if self.run_flask:
            self.app.run(host=self.host, port=self.port)
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app_ = Flask(__name__, instance_path=instance_path)
    app_.config.update(
        FILES_REST_PERMISSION_FACTORY=lambda *a, **kw: type(
            'Allow', (object, ), {'can': lambda self: True}
        )(),
        SECRET_KEY='CHANGE_ME',
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite://'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        TESTING=True,
    )
    app_.register_blueprint(files_rest_blueprint)
    InvenioDB(app_)
    InvenioRecords(app_)
    InvenioFilesREST(app_)
    InvenioIndexer(app_)
    search = InvenioSearch(app_)
    search.register_mappings('records-files', 'data')

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Esempio n. 10
0
def create_app():
    setup_config(sys.argv[1], 'dnsdb-updater', conf_dir=os.path.dirname(os.path.dirname(__file__)))
    log.error('This host belong to host group %s' % CONF.host_group)

    app = Flask(__name__)
    app.config['SECRET_KEY'] = CONF.etc.secret_key

    from dns_updater.utils.updater_util import check_necessary_options
    check_necessary_options()

    @app.route("/healthcheck.html", methods=['GET'])
    def health_check():
        try:
            return render_template('healthcheck.html')
        except TemplateNotFound:
            abort(404)

    @app.context_processor
    def default_context_processor():
        result = {'config': {'BASE_URL': CONF.web.base_url}}
        return result

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

    return app
Esempio n. 11
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    # 初始化一些flask扩展库,依赖于flask的app上下文环境
    db.init_app(app)
    # 初始化bootstrap
    bootstrap.init_app(app)
    # 初始化登陆管理
    login_manager.init_app(app)
    # 初始化邮件
    mail.init_app(app)
    # 初始化moment
    moment.init_app(app)
    # 附加路由和自定义的错误页面
    app_dir = os.path.join(root_dir, 'app')
    # 逐个执行各个路由映射脚本,添加到route_list中
    for routes in os.listdir(app_dir):
        rou_path = os.path.join(app_dir, routes)
        if (not os.path.isfile(rou_path)) and routes != 'static' and routes != 'templates':
            __import__('app.' + routes)
    # 从route_list中引入蓝图
    for blueprints in route_list:
        if blueprints[1] != None:
            app.register_blueprint(blueprints[0], url_prefix = blueprints[1])
        else:
            app.register_blueprint(blueprints[0])
    #返回app实例,让外部模块继续使用
    return app
Esempio n. 12
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.register_blueprint(main_blueprint)
    Misaka(app, tables=True, wrap=True)
    cache.init_app(app)
    return app 
Esempio n. 13
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    bcrypt.init_app(app)
    assets.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix="/auth")
    # from .holon import holon as holon_blueprint
    # app.register_blueprint(holon_blueprint, url_prefix="/holons")

    css = Bundle(
        'stylesheets/lib/*.css',
        Bundle('stylesheets/app.scss', filters="sass", output="gen/_app.css"),
        output='gen/app.css')
    assets.register('css_all', css)

    js = Bundle(
        Bundle('js/common/lib/core/*.js', 'js/common/lib/*.js', output="gen/_packed.js"),
        Bundle('js/common/*.js', 'js/common/services/*.js', 'js/common/directives/*.js', output="gen/_packed2.js"),
        Bundle('js/*.js', 'js/controllers/*.js', output="gen/_packed3.js"),
        filters="rjsmin",
        output='gen/packed.js')
    assets.register('js_all', js)

    app.config["APP_TIMESTAMP"] = time.ctime(os.path.getmtime("app"))

    return app
 def test_non_blueprint_rest_error_routing(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restful.Api(blueprint)
     api.add_resource(HelloWorld(), '/hi', endpoint="hello")
     api.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye")
     app = Flask(__name__)
     app.register_blueprint(blueprint, url_prefix='/blueprint')
     api2 = flask_restful.Api(app)
     api2.add_resource(HelloWorld(), '/hi', endpoint="hello")
     api2.add_resource(GoodbyeWorld(404), '/bye', endpoint="bye")
     with app.test_request_context('/hi', method='POST'):
         assert_false(api._should_use_fr_error_handler())
         assert_true(api2._should_use_fr_error_handler())
         assert_false(api._has_fr_route())
         assert_true(api2._has_fr_route())
     with app.test_request_context('/blueprint/hi', method='POST'):
         assert_true(api._should_use_fr_error_handler())
         assert_false(api2._should_use_fr_error_handler())
         assert_true(api._has_fr_route())
         assert_false(api2._has_fr_route())
     api._should_use_fr_error_handler = Mock(return_value=False)
     api2._should_use_fr_error_handler = Mock(return_value=False)
     with app.test_request_context('/bye'):
         assert_false(api._has_fr_route())
         assert_true(api2._has_fr_route())
     with app.test_request_context('/blueprint/bye'):
         assert_true(api._has_fr_route())
         assert_false(api2._has_fr_route())
 def test_api_delayed_initialization(self):
     blueprint = Blueprint('test', __name__)
     api = flask_restful.Api()
     api.init_app(blueprint)
     app = Flask(__name__)
     app.register_blueprint(blueprint)
     api.add_resource(HelloWorld, '/', endpoint="hello")
Esempio n. 16
0
def create_app(**kwargs):
    app = Flask(__name__)

    # config
    app.config['git_root'] = kwargs.get('git_root', '/tmp/test/')

    # apply overrides passed to app factory
    for k, v in kwargs.iteritems():
        app.config[k] = v

    if app.config.get('ignore_auth', False):
        from .auth import KeyAuthContext
        app.no_auth_user = KeyAuthContext()
        app.no_auth_user.can_provision = True
        app.no_auth_user.can_create_repos = True
        app.no_auth_user.can_read_repo = lambda x: True
        app.no_auth_user.can_modify_repo = lambda x: True
        app.no_auth_user.is_repo_admin = lambda x: True
        app.no_auth_user.save()

    # routes
    from .routes import web as storage_container
    app.register_blueprint(storage_container, url_prefix='')

    return app
Esempio n. 17
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(config)
    app.register_blueprint(v1, url_prefix='/api/v1')
    app.register_blueprint(v2, url_prefix='/api/v2')
    app.register_blueprint(qtoken, url_prefix='/api/qtoken')
    return app
Esempio n. 18
0
def create_app(config_name = 'default'):
    app = Flask(__name__, static_folder='static', static_url_path='')
    app.config.from_object(config[config_name])
    app.debug = True
    config[config_name].init_app(app)

    db.init_app(app)

    # attach routes and custom error pages here
    from hacer.api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

    @app.route('/')
    def index():
        return app.send_static_file('index.html')

    # start discovery server
    with app.app_context():
        from discovery import run_discovery_server
        app.discovery_thread = Thread(target=run_discovery_server, kwargs={ "Session": scoped_session(sessionmaker(bind=db.engine)) })
        app.discovery_thread.daemon = True
        app.discovery_thread.start()

    app.before_request(create_before_request(app))
    return app
Esempio n. 19
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. appname.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

    #init the cache
    cache.init_app(app)

    #init SQLAlchemy
    db.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().iteritems():
        assets_env.register(name, bundle)

    # register our blueprints
    from controllers.main import main
    app.register_blueprint(main)

    return app
Esempio n. 20
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)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    
    #注册蓝本
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)


    #注册 auth蓝本
    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    #url_prefix='/auth' 是可选参数,如果使用了,所有的路由都要加止前缀
    #上面这个URL就变成了:  http://127.0.0.1:5000/auth/login

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

    login_manager.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)

    # Attach routes and custom error pages here

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

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

    from .reg import reg as reg_blueprint
    app.register_blueprint(reg_blueprint, url_prefix='/reg')

    from .company import company as company_blueprint
    app.register_blueprint(company_blueprint, url_prefix='/company')
    return app

    from .jobs import jobs as job_blueprint
    app.register_blueprint(job_blueprint, url_prefix='/jobs')
Esempio n. 22
0
def init_blueprints(app: Flask) -> None:
    """
    :param app: Current application instance
    :type app: Flask
    """
    enabled_blueprints = app.config.get('ENABLED_BLUEPRINTS', [])

    for blueprint in enabled_blueprints:
        try:
            blueprint_obj = import_string(blueprint['path'])

            if not isinstance(blueprint_obj, VulykModule):
                raise ImportError(
                    'Wrong blueprint type: {}'.format(blueprint_obj))

            blueprint_obj.configure(blueprint.get('config', {}))

            app.register_blueprint(
                blueprint_obj, url_prefix='/{}'.format(blueprint['url_prefix'])
            )

            app.logger.info('Blueprint {} loaded successfully.'.format(
                blueprint['path'])
            )
        except (ImportError, KeyError) as e:
            app.logger.warning('Cannot load blueprint {}: {}.'.format(
                blueprint.get('path'), e)
            )
Esempio n. 23
0
def createApp(configfile=None):
    # We are using the "Application Factory"-pattern here, which is described
    # in detail inside the Flask docs:
    # http://flask.pocoo.org/docs/patternslo/appfactories/

    app = Flask(__name__)

    # Install our Bootstrap extensioappappn
    Bootstrap(app)

    # Our application uses blueprints as well; these go well with the
    # application factory. We already imported the blueprint, now we just need
    # to register it:
    app.register_blueprint(frontend)

    app.config.from_object('config')

    # Because we're security-conscious developers, we also hard-code disabling
    # the CDN support (this might become a default in later versions):
    app.config['BOOTSTRAP_SERVE_LOCAL'] = True

    setApp(app)
    initModuleRegisters()

    # We initialize the navigation as well
    nav.init_app(app)
    return app
Esempio n. 24
0
def create_app(config_name):
    """ Create and configure our Flask application. Configuration pulled from
        configure.py. This method invoked by manage.py.
    """
    # Patch FLOAT_REPR since it is not exposed. This encodes all float values
    # to precision 3
    json.encoder.FLOAT_REPR = lambda o: format(o, '.3f')

    # Create and configure application. Default template directory will be in
    # apps/fantasy/templates. Other blueprints can define their own folder.
    #
    app = Flask(__name__, template_folder="apps/fantasy/templates")
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Configure the database
    db.init_app(app)

    # Initialize the cache
    # cache_init_app(app)

    # Initialize flask-mail
    mail.init_app(app)

    # Use StormPath for user authentication.
    stormpath_manager.init_app(app)

    # Add the API
    from apps.fantasy import fantasy_bp
    app.register_blueprint(fantasy_bp)

    # Configure logging
    setup_logging()

    return app
Esempio n. 25
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    #? 不理解为何这些扩展函数会有init_app()方法
    # config[config_name].init_app(app)是自定义的静态方法,目前为空
    # 下面几个是Flask扩展带有的init_app方法
    # xxx.init_app(app) 和 xxx = XXX(app)的效果是一样的吗
    #  一般来说,XXX(app)会调用init_app方法,但不一定是都是这样
    bootstrap.init_app(app)
    mail.init_app(app)
    moment.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    # 附加路由和自定义的错误界面
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint) 
    # 注册蓝本

    from .auth import auth as auth_blueprint 
    app.register_blueprint(auth_blueprint, url_prefix = '/auth')
    # url_prefix 是可选参数,如果使用了这个参数,注册后蓝本中定义的所有路由都会加上指定的前缀,如本例中,完整的 URL 就变成了 http://localhost:5000/auth/login。

    return app
Esempio n. 26
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    bootstrap.init_app(app)

    db.init_app(app)
    security.init_app(app, user_datastore)
    toolbar.init_app(app)

    log_level = os.environ.get('LOG_LEVEL', 'INFO')
    logger = logging.getLogger(__name__)
    logger.setLevel(logging_map[log_level])
    stream = logging.StreamHandler()
    stream.setLevel(logging_map[log_level])
    logger.addHandler(stream)

    if config_name in ('docker', 'development', 'production'):
        sentry.init_app(app, logging=True, level=logging.INFO)
        app.wsgi_app = ProxyFix(app.wsgi_app)

    from app.celery import celery
    celery.conf.update(app.config)

    from .main import main
    app.register_blueprint(main)

    from .admin import admin
    admin.init_app(app)

    from .api_0_1 import api as api_0_1_blueprint
    app.register_blueprint(api_0_1_blueprint, url_prefix='/api/0.1')

    return app
Esempio n. 27
0
def create_app(config_filemane):
  """Application factory
  """
  # define the WSGI application object
  flask_app = Flask(__name__)

  # configuration
  flask_app.config.from_object(config_filemane)

  # initialize the database
  db.init_app(flask_app)

  # blueprints
  from app.users import users_blueprint
  from app.trips import trips_blueprint
  flask_app.register_blueprint(users_blueprint)
  flask_app.register_blueprint(trips_blueprint)

  # flask-restful
  from app.users import UserListAPI, UserAPI
  from app.trips import TripListAPI, TripAPI
  api = Api(prefix='/api/v0')
  api.add_resource(UserListAPI, '/users', endpoint='users')
  api.add_resource(UserAPI, '/users/<id>', endpoint='user')
  api.add_resource(TripListAPI, '/trips', endpoint='trips')
  api.add_resource(TripAPI, '/trips/<int:id>', endpoint='trip')
  api.init_app(flask_app)

  cors = CORS(resources={r'/api/v0/*': {'origins': '*'}})
  cors.init_app(flask_app)

  return flask_app
Esempio n. 28
0
def test_content_type(sign_func):
    responses.add(responses.GET, "https://flask.atlassian.net/")

    app = Flask(__name__)
    app.secret_key = "anything"
    app.debug = True
    backend = MemoryBackend({
        "oauth_token": "faketoken",
        "oauth_token_secret": "fakesecret",
        "oauth_session_handle": "fakehandle",
        "oauth_expires_in": "157680000",
        "oauth_authorization_expires_in": "160272000",
    })
    jira_bp = make_jira_blueprint(
        "https://flask.atlassian.net",
        consumer_key="fakekey",
        backend=backend,
    )
    app.register_blueprint(jira_bp)

    @app.route("/test")
    def api_request():
        jira_bp.session.get("/")
        return "success"

    resp = app.test_client().get("/test")
    headers = responses.calls[0].request.headers
    assert "Content-Type" in headers
    assert headers["Content-Type"] == "application/json"
Esempio n. 29
0
 def create_app(self):
     app = Flask('test')
     app.register_blueprint(blueprint, url_prefix='/bbg')
     app.config['DEBUG'] = True
     app.config['TESTING'] = True
     app.config['PRESERVE_CONTEXT_ON_EXCEPTION'] = True
     return app
Esempio n. 30
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)
    db.init_app(app)
    moment.init_app(app)
    pagedown.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 .article import article as article_blueprint
    app.register_blueprint(article_blueprint, url_prefix="/article")

    from .picture import picture as picture_blueprint
    app.register_blueprint(picture_blueprint, url_prefix="/picture")

    from .map import map as map_blueprint
    app.register_blueprint(map_blueprint, url_prefix="/map")

    return app
Esempio n. 31
0
	restore = Restore(rbd, snap)
	status = restore.mount()
	if status is None:
		return send_json({'success': False, 'path': None}, code=500)
	else:
		status = status.replace('/tmp/', '')
		return send_json({'success': True, 'path': status})


@app.route('/unmap/<rbd>/<snap>/')
def unmap(rbd, snap):
	restore = Restore(rbd, snap)
	restore.umount()
	return send_json({'success': True})


@app.route('/mapped/')
def mapped():
	data = get_mapped(extended=False)
	result = []
	for tree in data:
		result.append(prepare_tree_to_json(tree))
	return send_json(result)


auto_bp = Blueprint('auto_bp', __name__)
# FIXME: use config or something
AutoIndexBlueprint(auto_bp, browse_root='/tmp/')

app.register_blueprint(auto_bp, url_prefix='/explore')
Esempio n. 32
0
def create_app(test_config=None):

    SWAGGER_URL = ''  # URL for exposing Swagger UI (without trailing '/')
    # Our API url (can of course be a local resource)
    API_URL = '/static/swagger.json'

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_mapping(SECRET_KEY='TODO dev')

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route('/headers', methods=["GET"])
    def headers():
        """
    Returns the https headers of the request
    """
        try:
            return json.dumps({k: v for k, v in request.headers}), 200
        except Exception as e:
            return {
                "code": 400,
                "type": e.__class__.__name__,
                "description": str(e)
            }, 400

    @app.route('/sobol', methods=["GET"])
    def sobol():
        """
    Returns a Sobol sequence
    """
        try:
            # deferring to swagger/schema for validity means that
            # - the schema must "know" the validity ranges of the arguments to sobolSequence
            # - the function itself may be better at providing a meaningful error message
            # - passing invalid values to the API directly will still fail, and possibly badly
            dim = int(request.args["dimension"])
            if dim < 1 or dim > 1111:
                raise ValueError(
                    "Sobol dimension %d is outside the valid range [1,1111]" %
                    dim)
            len = int(request.args["length"])
            if len < 1 or len > 1048576:
                raise ValueError(
                    "Sobol sequence length %d is outside the valid range [1,1048576]"
                    % len)
            return json.dumps(hl.sobolSequence(dim, len).tolist()), 200
        except Exception as e:
            return {
                "code": 400,
                "type": e.__class__.__name__,
                "description": str(e)
            }, 400

    # e.g. [1.1,2.2,3.3,4.4]
    @app.route('/integerise', methods=["POST"])
    def integerise():
        """
    Returns the closest integer array to the supplied non-integer data (with integer marginal sums), preserving the marginal sums
    """
        try:
            # json cant (de)serialise np.array
            array = np.array(json.loads(request.get_data())).astype(float)
            result = hl.integerise(array)
            # if a string throw it
            if isinstance(result, str):
                raise ValueError(result)
            if isinstance(result, dict) and "result" in result:
                result["result"] = result["result"].tolist()
                return json.dumps(result), 200

        except Exception as e:
            return {
                "code": 400,
                "type": e.__class__.__name__,
                "description": str(e)
            }, 400

    # Call factory function to create our blueprint
    swaggerui_blueprint = get_swaggerui_blueprint(
        SWAGGER_URL,  # Swagger UI static files will be mapped to '{SWAGGER_URL}/dist/'
        API_URL,
        config={'app_name': "Prototype App Service"})

    # Register blueprint at URL
    # (URL must match the one given to factory function above)
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

    return app
Esempio n. 33
0
    app.config['DEBUG_TB_PROFILER_ENABLED'] = True
    toolbar = DebugToolbarExtension(app)


# Jinja add-ons
@app.before_request
def before_request():
    g.config = config
    g.request_start_time = time.time()
    g.request_time = lambda: "%.3fs" % (time.time() - g.request_start_time)


@app.template_filter('ctime')
def timectime(s):
    dt = datetime.datetime.fromtimestamp(s)
    return dt.strftime('%d-%m-%Y %H:%M')


# Connect blueprints
import src.controllers.static
import src.controllers.index
import src.controllers.table

app.register_blueprint(src.controllers.static.bp)
app.register_blueprint(src.controllers.index.bp)
app.register_blueprint(src.controllers.table.bp, url_prefix='/table')


if __name__ == '__main__':
    app.run()
Esempio n. 34
0

@app.route('/')
def get_index():
    try:
        response = geoip_reader.city('18.62.0.1')  # request.remote_addr)
        init_lat = response.location.latitude
        init_lon = response.location.longitude
    except geoip2.errors.AddressNotFoundError:
        init_lat = 0
        init_lon = 0
    return render_template('index.html', init_lat=init_lat, init_lon=init_lon)


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

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

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

app.jinja_env.globals.update(len=len)
app.jinja_env.globals.update(min=min)
app.jinja_env.globals.update(max=max)


@app.after_request
def after_request(response):
    if response.headers['Content-Type'].find('image/') == 0:
Esempio n. 35
0
File: app.py Progetto: ibra86/common
import os

from routes.products.route import products
from routes.supermarkets.route import supermarkets

from flask import Flask, render_template

app = Flask(__name__)

app.register_blueprint(products)
app.register_blueprint(supermarkets)

SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY


@app.route('/')
@app.route('/home')
def home():
    return render_template("index.html", var_list=['Products', 'Supermarkets'])


@app.errorhandler(404)
def page_not_found(error):
    return render_template('err_404.html'), 404


if __name__ == '__main__':
    app.run(debug=True)
Esempio n. 36
0
from fava.core.charts import FavaJSONEncoder
from fava.core.helpers import FavaAPIException
from fava.help import HELP_PAGES
from fava.json_api import json_api
from fava.serialisation import serialise
from fava.util import slugify, resource_path, setup_logging, send_file_inline
from fava.util.date import Interval
from fava.util.excel import HAVE_EXCEL

setup_logging()
app = Flask(  # pylint: disable=invalid-name
    __name__,
    template_folder=resource_path("templates"),
    static_folder=resource_path("static"),
)
app.register_blueprint(json_api, url_prefix="/<bfile>/api")

app.json_encoder = FavaJSONEncoder
app.jinja_options["extensions"].append("jinja2.ext.do")
app.jinja_env.trim_blocks = True
app.jinja_env.lstrip_blocks = True

app.config["HAVE_EXCEL"] = HAVE_EXCEL
app.config["HELP_PAGES"] = HELP_PAGES
app.config["ACCOUNT_RE"] = ACCOUNT_RE

REPORTS = [
    "_context",
    "balance_sheet",
    "commodities",
    "events",
Esempio n. 37
0
                 components={'sql': {}})

simple = Module('simple', __name__, template_folder='templates')
simple.label('Simple module')
@simple.route('/')
@simple.menu('Hello world')
def hello():
    return render_template('hello.html')

@simple.route('/mnau')
@simple.menu('Mnau!')
@simple.local_menu('Mnau')
@simple.access(lambda **kwa: False)
def mnau():
    return render_template('hello.html')
app.register_blueprint(simple)

widgets = Module('widgets', __name__, template_folder='templates')
widgets.label('Widgets')

table_data = [("%d-1" % i, "%d-2" % i, "%d-3" % i) for i in range(100)]

@widgets.route('/widgets/table')
@widgets.menu('Simple table')
def simple_table():
    t = PlainTable("simple_table",
                   ("Column 1", "Column 2", "Column 3"),table_data)
    return single_view(t,
                       layout='fluid')

tree_data = [TreeGridItem(("foo", "Foo"), 
Esempio n. 38
0

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)
CORS(app)
app_setting = os.environ['APP_SETTINGS']
app.config.from_object(app_setting)

# This hook ensures that a connection is opened to handle any queries
# generated by the request.
@app.before_request
def _db_connect():
    mysql_db.connect()
    #mysql_db.execute_sql('SET time_zone="America/Sao_Paulo";')

# This hook ensures that the connection is closed when we've finished
# processing the request.
@app.teardown_request
def _db_close(exc):
    if not mysql_db.is_closed():
        mysql_db.close()

#register client routers
app.register_blueprint(home_route)
app.register_blueprint(auth_route)
app.register_blueprint(dealer_route)
app.register_blueprint(purchase_route)
Esempio n. 39
0
####################
#### extensions ####
####################

bcrypt.init_app(app)

db.init_app(app)

migrate = Migrate(app, db)

###################
### blueprints ####
###################
from .routes.routes_general import route_path_general
app.register_blueprint(route_path_general, url_prefix='/api')

###################################
### global http configurations ####
###################################
from .utils.responses import response_with, BAD_REQUEST_400, SERVER_ERROR_404, SERVER_ERROR_500, \
    NOT_FOUND_HANDLER_404


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


@app.errorhandler(400)
def bad_request(e):
from flask import Flask
from flask.ext.babel import Babel
from flask_bower import Bower
from app import configurator
from app.cache import cache
from flask.ext.cors import CORS

app = Flask(__name__, template_folder="templates")
cors = CORS(app)
babel = Babel(app)
bower = Bower(app)
load = configurator.get("modules")("load")
cache.init_app(app, config={'CACHE_TYPE': 'simple'})

if "capitains-ahab" in load:
    from Ahab import ahab
    app.register_blueprint(ahab)

from joth import joth

app.register_blueprint(joth)

from app import views
Esempio n. 41
0
def register_blueprints(app: Flask):
    app.register_blueprint(auth_bp)
    app.register_blueprint(monitor_bp)
    app.register_blueprint(dashboard_bp)
    app.register_blueprint(developer_bp)

    app.register_blueprint(oauth_bp, url_prefix="/oauth")
    app.register_blueprint(oauth_bp, url_prefix="/oauth2")

    app.register_blueprint(discover_bp)
    app.register_blueprint(api_bp)
Esempio n. 42
0
from flask import Flask
from templates.python.views import home_blueprint, map_blueprint

app = Flask(__name__, static_folder='./public', template_folder="./static")

# register the blueprints
app.register_blueprint(home_blueprint)
app.register_blueprint(map_blueprint)
Esempio n. 43
0
def create_app():
    app = Flask(__name__, static_folder='static')
    app.register_blueprint(
        v1.bp,
        url_prefix='/v1')
    return app
Esempio n. 44
0
if is_production:
    origin = cors_origin_prod_re
else:
    origin = cors_origin_dev_re

resources = {
    '*': {
        'origins': origin,
    }
}

cors = CORS(app, origins=[origin])


# Test endpoints
@app.route('/', methods=['GET', 'POST'])
def hello_world():
    return jsonify({'Output': 'Hello World'})


# endpoint imports
from app.labs.infinite_scroller import bp as infinite_scroller_bp
app.register_blueprint(infinite_scroller_bp)

from app.cimarron import bp as cimarron_bp
app.register_blueprint(cimarron_bp)

if __name__ == '__main__':
    flaskrun(app)
Esempio n. 45
0
    email = db.Column(db.String(120), unique=True, nullable=False)
    join_date = db.Column(db.DateTime)


class OAuth(OAuthConsumerMixin, db.Model):
    provider_user_id = db.Column(db.String(256), unique=True, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    user = db.relationship(User)


google_bp = make_google_blueprint(scope=["profile", "email"],
                                  redirect_to='login',
                                  storage=SQLAlchemyStorage(OAuth,
                                                            db.session,
                                                            user=current_user))
app.register_blueprint(google_bp, url_prefix="/login")

login_manager = LoginManager(app)


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


@app.route('/')
def index():
    return "<a href='/google'> <h1> Log In </h1> </a>"


@app.route('/google')
Esempio n. 46
0
 def register_blueprint(self, bp):
     Flask.register_blueprint(self, bp)
     self.jinja_loader.loaders[1].mapping[bp.name] = bp.jinja_loader
Esempio n. 47
0
# app.secret_key = '1234657889'
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///quotes.db'
app.config.from_object(BaseConfig)
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login = LoginManager(app)
login.login_view = 'user.login'
login.login_message_category = 'info'

from quotes.categories.routes import category
from quotes.quote.routes import quote
from quotes.main.routes import main
from quotes.errors.routes import error
from quotes.user.routes import user

app.register_blueprint(category)
app.register_blueprint(quote)
app.register_blueprint(main)
app.register_blueprint(error)
app.register_blueprint(user)

# def create_app(config_class=Config):
#     app = Flask(__name__, template_folder='template')
#     app.config.from_object(Config)
#     db.init_app(app)
#     bcrypt.init_app(app)
#     login.init_app(app)
#
#     from quotes.categories.routes import category
#     from quotes.quote.routes import quote
#     from quotes.main.routes import main
Esempio n. 48
0
""" create a application with flask """

import os
from flask import Flask, Blueprint, jsonify, abort
from models import storage
from api.v1.views import app_views
from werkzeug.exceptions import HTTPException
from flask_cors import CORS, cross_origin

app = Flask(__name__)
app.url_map.strict_slashes = False

host = os.getenv('HBNB_API_HOST', '0.0.0.0')
port = os.getenv('HBNB_API_PORT', 5000)

app.register_blueprint(app_views)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
CORS(app, resources={r'/*': {'origins': '0.0.0.0'}})


@app.teardown_appcontext
def close_app(exception):
    """ close the app """
    storage.close()


@app.errorhandler(404)
def handle_error_404(exception):
    """ return a 404 page JSON """
    return jsonify({"error": "Not found"}), 404
Esempio n. 49
0
from flask import Flask
app = Flask(__name__, static_folder='./public', template_folder="./statics")

from templates.hello.views import hello_blueprint
from templates.medium_articles.views import medium_blueprint

# register the blueprints
app.register_blueprint(hello_blueprint)
app.register_blueprint(medium_blueprint)
Esempio n. 50
0
        port=app.config.get("MONGODB_PORT", 27017),
        username=app.config.get("MONGODB_USERNAME", ""),
        password=app.config.get("MONGODB_PASSWORD", ""),
        connect=False,
        tz_aware=True)
logger.info('host{} port{}'.format(app.config.get('MONGODB_HOST'),
                                   app.config.get("MONGODB_PORT", 27017)))

# os.environ['COMPOSE_FILE_PATH'] = '/root/cello/src/agent/docker/_compose_files'
login_manager = LoginManager()
login_manager.init_app(app)

app.logger.setLevel(LOG_LEVEL)
app.logger.addHandler(log_handler)

app.register_blueprint(bp_index)
app.register_blueprint(bp_host_view)
app.register_blueprint(bp_host_api)
app.register_blueprint(bp_cluster_view)
app.register_blueprint(bp_cluster_api)
app.register_blueprint(bp_stat_view)
app.register_blueprint(bp_stat_api)
app.register_blueprint(bp_auth_api)
app.register_blueprint(bp_login)
app.register_blueprint(bp_user_api)
app.register_blueprint(bp_user_view)
app.register_blueprint(front_rest_user_v2)
app.register_blueprint(bp_container_api)
# app.register_blueprint(bp_org_user_api)
app.register_blueprint(bp_organization_api)
admin = os.environ.get("ADMIN", '18888888888')
Esempio n. 51
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    migrate.init_app(app, db)
    login.init_app(app)
    mail.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    babel.init_app(app)

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

    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)

    app.elasticsearch = Elasticsearch([app.config['ELASTICSEARCH_URL']]) \
        if app.config['ELASTICSEARCH_URL'] else None

    app.redis = Redis.from_url(app.config['REDIS_URL'])
    app.task_queue = rq.Queue('microblog-tasks', connection=app.redis)

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

    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)

        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/microblog.log',
                                           maxBytes=10240,
                                           backupCount=10)
        file_handler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                              '[in %(pathname)s:%(lineno)d]'))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('Microblog startup')

    return app
Esempio n. 52
0
from modules.tasks import TaskStatusApi
from modules.tasks import TaskListApi
from modules.tasks import TaskGeneratorApi
from modules.tasks import TaskFileOutputApi
# Endpoint for generic task editing and log retrieval
api.add_resource(TaskApi, '/tasks/<int:task_id>')
# Temporary endpoint to edit the staus of a job (mainly via dashboard)
api.add_resource(TaskStatusApi, '/tasks/<int:task_id>/status')
# Listing of all tasks (usually filtered by job_id)
api.add_resource(TaskListApi, '/tasks')
# Endpoint queried by the managers to obtain new tasks
api.add_resource(TaskGeneratorApi, '/tasks/generate')
# Serves static path to download task files
api.add_resource(TaskFileOutputApi, '/task/file/output/<int:task_id>')

from modules.main import main
from modules.stats import stats

app.register_blueprint(main)
app.register_blueprint(stats, url_prefix='/stats')


@app.errorhandler(404)
def not_found(error):
    response = jsonify({
        'code': 404,
        'message': 'No interface defined for URL'
    })
    response.status_code = 404
    return response
Esempio n. 53
0
session.verify = app.config['VERIFY_CERT']

# Load static assets manifest file, which maps source file names to the
# corresponding versioned/hashed file name.
_manifest_path = app.config.get('ASSET_MANIFEST_PATH')
if _manifest_path:
    with open(_manifest_path, 'r') as f:
        app.config['ASSET_MANIFEST'] = json.loads(f.read())

from .auth.views import auth_blueprint  # pylint: disable=C0413
from .portal_ui_blueprint.views import portal_ui  # pylint: disable=C0413
from .sites.views import sites_blueprint  # pylint: disable=C0413
from .wqx.views import wqx  # pylint: disable=C0413
from . import filters  # pylint: disable=C0413

app.register_blueprint(auth_blueprint, url_prefix='')
app.register_blueprint(portal_ui, url_prefix='')
app.register_blueprint(sites_blueprint, url_prefix='/sites')
app.register_blueprint(wqx, url_prefix='/portal/schemas')


# Set up swagger endpoints
@app.route('/spec')
def spec():
    host = request.url_root.rstrip('/').replace(app.config['WSGI_STR'], '')
    return jsonify(
        swagger(app,
                from_file_keyword="swagger_from_file",
                template={
                    "host": host.replace('http://', ''),
                    "info": {
class APITest(TestCase):
    def setUp(self):
        """We have an app."""
        self.app = Flask('test')
        self.app.register_blueprint(routes.api)
        self.client = self.app.test_client()
Esempio n. 55
0
import os

from math import *
from flask.views import View
from flask import Blueprint, url_for, render_template, request, jsonify, send_from_directory
from flask_login import login_required
import os
import pymongo
from bson import json_util

from app import app
from app_api import app_api
username_password_dir = {"*****@*****.**": "myweb"}

app_main = Flask(__name__)
app_main.register_blueprint(app)
app_main.register_blueprint(app_api)

#app_main.config['SERVER_NAME'] = 'alex.com'

#@app.route('/favicon.ico')
#def favicon():
#    return url_for('static', filename='favicon.ico')
#return send_from_directory(os.path.join(app.root_path, 'static'),
#                           'favicon.ico', mimetype='image/vnd.microsoft.icon')

#with app_main.app_context():
#    app_main.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico'))
#app_main.add_url_rule('/favicon.ico', redirect_to=url_for('static', filename='favicon.ico'))

# config
Esempio n. 56
0
from flask import Flask
from flask_cors import CORS
from Blueprints.TextRankSummarizer import TextRank_Blueprint
from Blueprints.LuhnSummarizer import LuhnSummarizer_Blueprint
from Helpers import APIHelper as API

app = Flask("TS-API")

# Enables cross-origin API requests
CORS(app)

# Register all the blueprints (API endpoints)
app.register_blueprint(TextRank_Blueprint, url_prefix="/textrank")
app.register_blueprint(LuhnSummarizer_Blueprint, url_prefix="/luhn")


@app.route('/')
def index():
    return API.api_response(API.success_code, "Welcome to the Text Summarizer API!")
Esempio n. 57
0
app = Flask(__name__, static_folder='dist')

from decorators import error_handler, logger

app.config['SQLALCHEMY_DATABASE_URI'] = db_URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

ma = Marshmallow(app)

bcrypt = Bcrypt(app)

from controllers import act_cont, order_cont, reaction_cont, user_cont

app.register_blueprint(act_cont.router, url_prefix='/api')
app.register_blueprint(order_cont.router, url_prefix='/api')
app.register_blueprint(reaction_cont.router, url_prefix='/api')
app.register_blueprint(user_cont.router, url_prefix='/api')

## registering your blueprints...
import os


@app.route('/', defaults={'path': ''})  # homepage
@app.route('/<path:path>')  # any other path
def catch_all(path):
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, 'dist/' + path)

    if os.path.isfile(filename):  # if path is a file, send it back
Esempio n. 58
0
def create_app(config_name='default'):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    jwt.init_app(app)
    configure_uploads(app, photos)
    patch_request_class(app)
    # monkey.patch_all()

    from .user import user as user_blueprint
    app.register_blueprint(user_blueprint, url_prefix="/user")

    from .city import city_api as city_blueprint
    app.register_blueprint(city_blueprint, url_prefix="/city")

    from .file import file_api as file_blueprint
    app.register_blueprint(file_blueprint, url_prefix="/file")

    from .consle import consle_api as console_blueprint
    app.register_blueprint(console_blueprint, url_prefix="/consle")

    from .car import car_api as car_blueprint
    app.register_blueprint(car_blueprint, url_prefix='/car')

    from .task import task_api as task_blueprint
    app.register_blueprint(task_blueprint, url_prefix='/task')
    return app
Esempio n. 59
0
# __init__.py file. Contains all the db and app components of the code!
# so let's quickly create some major components of the application
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)

app.config['SECRET_KEY'] = 'mykey'
basedir = os.path.abspath(os.path.dirname(__file__))

db = SQLAlchemy(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(
    basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

migrate = Migrate(app, db)

# lets quickly register our blueprints we created previously
# In order them to work fine, we need to register them underneath the 'db' initialization

from myproject.kittens.views import kittens_blueprint
from myproject.owners.views import owners_blueprint

app.register_blueprint(owners_blueprint, url_prefix='/owners')
app.register_blueprint(kittens_blueprint, url_prefix='/kittens')
Esempio n. 60
0
def create_app(*, config_module_class: str) -> Flask:
    """
    Creates app in function so that flask with flask extensions can be
    initialized with specific config. Here it defines the route of APIs
    so that it can be seen in one place where implementation is separated.

    Config is being fetched via module.class name where module.class name
    can be passed through environment variable.
    This is to make config fetched through runtime PYTHON_PATH so that
    Config class can be easily injected.
    More on: http://flask.pocoo.org/docs/1.0/config/

    :param config_module_class: name of the config
    :return: Flask
    """
    if FLASK_APP_MODULE_NAME and FLASK_APP_CLASS_NAME:
        print(f'Using requested Flask module {FLASK_APP_MODULE_NAME} '
              f'and class {FLASK_APP_CLASS_NAME}', file=sys.stderr)
        class_obj = getattr(
            importlib.import_module(FLASK_APP_MODULE_NAME),
            FLASK_APP_CLASS_NAME
        )

        flask_kwargs_dict = {}  # type: Dict[str, Any]
        if FLASK_APP_KWARGS_DICT_STR:
            print(f'Using kwargs {FLASK_APP_KWARGS_DICT_STR} to instantiate Flask',
                  file=sys.stderr)
            flask_kwargs_dict = ast.literal_eval(FLASK_APP_KWARGS_DICT_STR)

        app = class_obj(__name__, **flask_kwargs_dict)

    else:
        app = Flask(__name__)

    if CORS_ENABLED:
        CORS(app)
    config_module_class = \
        os.getenv('SEARCH_SVC_CONFIG_MODULE_CLASS') or config_module_class
    app.config.from_object(config_module_class)

    if app.config.get('LOG_CONFIG_FILE'):
        logging.config.fileConfig(app.config.get('LOG_CONFIG_FILE'), disable_existing_loggers=False)
    else:
        logging.basicConfig(format=app.config.get('LOG_FORMAT'), datefmt=app.config.get('LOG_DATE_FORMAT'))
        logging.getLogger().setLevel(app.config.get('LOG_LEVEL'))

    logging.info('Creating app with config name {}'
                 .format(config_module_class))
    logging.info('Created app with config name {}'.format(config_module_class))

    api_bp = Blueprint('api', __name__)
    api_bp.add_url_rule('/healthcheck', 'healthcheck', healthcheck)
    api = Api(api_bp)
    # Table Search API
    # TODO: Rename endpoint to be more generic and accept a resource type so that logic can be re-used
    api.add_resource(SearchTableFilterAPI, '/search_table')
    api.add_resource(SearchTableAPI, '/search')

    # User Search API
    api.add_resource(SearchUserAPI, '/search_user')

    # Dashboard Search API
    api.add_resource(SearchDashboardAPI, '/search_dashboard')

    # DocumentAPI
    api.add_resource(DocumentTablesAPI, '/document_table')
    api.add_resource(DocumentTableAPI, '/document_table/<document_id>')

    api.add_resource(DocumentUsersAPI, '/document_user')
    api.add_resource(DocumentUserAPI, '/document_user/<document_id>')

    app.register_blueprint(api_bp)

    if app.config.get('SWAGGER_ENABLED'):
        Swagger(app, template_file=os.path.join(ROOT_DIR, app.config.get('SWAGGER_TEMPLATE_PATH')), parse=True)
    return app