Beispiel #1
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)
Beispiel #2
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'))
Beispiel #3
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()
Beispiel #4
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
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)
 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")
Beispiel #7
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
Beispiel #8
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
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"
Beispiel #10
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
Beispiel #11
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
Beispiel #12
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
Beispiel #13
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
Beispiel #14
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
Beispiel #15
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
Beispiel #16
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)
            )
 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())
Beispiel #18
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
Beispiel #19
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 
Beispiel #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
Beispiel #21
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
Beispiel #22
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')
Beispiel #23
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)
Beispiel #24
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
Beispiel #25
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
Beispiel #26
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
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
Beispiel #28
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
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
Beispiel #30
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