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

    # Configure logging
    handler = logging.FileHandler(app.config["LOGGING_LOCATION"])
    handler.setLevel(app.config["LOGGING_LEVEL"])
    formatter = logging.Formatter(app.config["LOGGING_FORMAT"])
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

    bootstrap.init_app(app)
    mail.init_app(app)
    db.init_app(app)
    admin.init_app(app)

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .userManagement import userMngmt as userMngmt_blueprint

    app.register_blueprint(userMngmt_blueprint, url_prefix="/userManagement")

    return app
def create_app(config_filepath="resource/config.cfg"):
    app = Flask(__name__)
    # app.config.from_object(__name__)
    # app.config.from_envvar('GRADE_SETTINGS', silent=True)

    # 기본 설정은 GradeServer_Config 객체에 정의되있고 운영 환경 또는 기본 설정을 변경을 하려면
    # 실행 환경변수인 GradeServer_SETTINGS에 변경할 설정을 담고 있는 파일 경로를 설정
    from GradeServer.GradeServer_config import GradeServerConfig

    app.config.from_object(GradeServerConfig)
    app.config.from_pyfile(config_filepath, silent=True)
    # Log
    from GradeServer.GradeServer_logger import Log

    Log.init()

    # SessionInterface 설정.
    from GradeServer.cache_session import RedisCacheSessionInterface

    app.session_interface = RedisCacheSessionInterface()

    # 데이터베이스 처리
    from GradeServer.database import DBManager

    DBManager.init(app.config["DB_URL"])
    DBManager.init_db()

    # 뷰 함수 모듈은 어플리케이션 객체 생성하고 블루프린트 등록전에
    # 뷰 함수가 있는 모듈을 임포트해야 해당 뷰 함수들을 인식할 수 있음
    from GradeServer.controller import *
    from GradeServer.GradeServer_blueprint import GradeServer

    app.register_blueprint(GradeServer)

    return app
def create_app(debug=False):
    app = Flask(__name__, template_folder="template")
    app.config.from_object(BaseConfig)
    if "SITE_SETTINGS" in os.environ:
        app.config.from_envvar("SITE_SETTINGS")
    app.config["DEBUG"] |= True

    app.jinja_env.add_extension(JadeJinja)
    app.jinja_env.autoescape = False  # enable pyjade unescaping

    assets = AssetsEnvironment(app)
    content = MarkupContent(app)

    @app.before_first_request
    def before_first_request():
        pass

    @app.context_processor
    def context_processor():
        return {"base": {"title": "ithz"}}

    assets.register("base_css", "base.css", filters=None, output="{BUILD_PATH}/static/css".format(**app.config))
    assets.register("base_js", "base.js", filters=None, output="{BUILD_PATH}/static/js".format(**app.config))

    for name, bundle in six.iteritems(bundles):
        assets.register(name, bundle)

    for blueprint in blueprints:
        app.register_blueprint(blueprint)
    return app, assets
def register_server():
    app = Flask(__name__)

    settings_entry = os.environ.get("SKELETONS_SETTINGS_ENTRY", "skeletons")
    server_settings = get_config(settings_entry)
    app.config["server_settings"] = server_settings

    app.config["SESSION_COOKIE_NAME"] = server_settings.cookie_name
    app.secret_key = server_settings.secret_key

    app.register_blueprint(greeting_blueprint, url_prefix="/greeting")

    @app.before_request
    def before_request():
        pass

    @app.teardown_request
    def teardown_request(error=None):
        pass

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

    @app.errorhandler(404)
    def page_not_found(e):
        return jsonify({"error": "Invalid API path"}), 404

    @app.errorhandler(HTTPError)
    def http_error(e):
        return jsonify({"error": e.msg}), e.status_code

    return app
def app(request):
    """Flask application fixture."""
    app = Flask("testapp")
    app.config.update(
        TESTING=True, SQLALCHEMY_DATABASE_URI=os.getenv("SQLALCHEMY_DATABASE_URI", "sqlite://"), SERVER_NAME="localhost"
    )
    Babel(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioCollections(app)
    InvenioRecords(app)

    app.register_blueprint(blueprint)

    with app.app_context():
        if str(db.engine.url) != "sqlite://" and not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            if str(db.engine.url) != "sqlite://":
                drop_database(str(db.engine.url))

    request.addfinalizer(teardown)

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

    return app
Beispiel #6
1
def create_app(config="config"):
    """
    Creates a new instance of the web application and registers a couple top-level routes.

    :param config: Object whose attributes will be used as the configuration settings.
    :return: an application instance.
    :rtype: Flask
    """
    app = Flask(__name__)
    app.config.from_object(config)

    from flask.ext.bootstrap import Bootstrap

    Bootstrap(app)

    from users.views import mod as users

    app.register_blueprint(users)
    from booru.views import mod as booru

    app.register_blueprint(booru)

    @app.route("/test")
    def hello_world():
        return "Hello world!"

    @app.errorhandler(404)
    def file_not_found(error):
        # TODO: Log the error.
        return render_template("404.html"), 404

    return app
Beispiel #7
1
def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    if app.config.from_pyfile("settings.conf", silent=True):
        print "Settings loaded from local instance"
    if app.config.from_envvar("RSVP_CONF", silent=True):
        print "Settings loaded from ENVVAR"
    if app.config["DEBUG"]:
        app.debug = True

    log_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
    root_logger = logging.getLogger("werkzeug")
    if app.config["DEBUG"]:
        root_logger.setLevel(logging.DEBUG)
    file_handler = logging.FileHandler("{}/{}".format(app.config["LOGDIR"], "rsvp.log"))
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    from extensions import db
    import models

    db.init_app(app)
    models.create_all(app)

    from views import views_bp

    app.register_blueprint(views_bp)
    return app
Beispiel #8
1
def create_app(config=None):
    """Create an instance of the tentd flask application"""
    app = Flask("tentd")
    app.add_url_rule("/", "home", description)
    app.request_class = Request

    # Load the default configuration values
    import tentd.defaults as defaults

    app.config.from_object(defaults)

    # Load the user configuration values
    if isinstance(config, basestring):
        config = make_config(config)

    if not isinstance(config, dict):
        raise TypeError("Config argument must be a dict or string.")

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

    # Initialise the db for this app
    db.init_app(app)

    # Register the entity blueprints
    for blueprint in (entity, followers, posts):
        app.register_blueprint(blueprint, url_prefix=blueprint.prefix(app))

    return app
Beispiel #9
1
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)
    pagedown.init_app(app)

    if not app.debug and not app.testing and not app.config["SSL_DISABLE"]:
        from flask.ext.sslify import SSLify

        sslify = SSLify(app)

    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")

    return app
Beispiel #10
1
def create_app(configfile=None):
    app = Flask(__name__)

    app.url_map.converters["uuid"] = UUIDConverter

    AppConfig(app)
    Bootstrap(app)
    db.init_app(app)
    app.config["BOOTSTRAP_SERVE_LOCAL"] = True

    if app.config["STORAGE_TYPE"] == "filesystem":
        app.storage = storage.FilesystemStorage(app.config["STORAGE_FS_PATH"], app.config["STORAGE_FS_URL_PREFIX"])
    elif app.config["STORAGE_TYPE"] == "s3":
        import boto

        con = boto.connect_s3(app.config["BOTO_ACCESS_KEY"], app.config["BOTO_SECRET_KEY"])

        bucket = con.get_bucket(app.config["BOTO_BUCKET_NAME"])

        app.storage = storage.BotoStorage(bucket, app.config["BOTO_REDUCED_REDUNDANCY"])
    else:
        raise ValueError("Invalid storage type: {}".format(app.config["STORAGE_TYPE"]))

    app.register_blueprint(frontend)

    return app
Beispiel #11
1
def test_context_local():
    responses.add(responses.GET, "https://google.com")

    # set up two apps with two different set of auth tokens
    app1 = Flask(__name__)
    ghbp1 = make_bitbucket_blueprint(
        "foo1", "bar1", redirect_to="url1", backend=MemoryBackend({"access_token": "app1"})
    )
    app1.register_blueprint(ghbp1)

    app2 = Flask(__name__)
    ghbp2 = make_bitbucket_blueprint(
        "foo2", "bar2", redirect_to="url2", backend=MemoryBackend({"access_token": "app2"})
    )
    app2.register_blueprint(ghbp2)

    # outside of a request context, referencing functions on the `bitbucket` object
    # will raise an exception
    with pytest.raises(RuntimeError):
        bitbucket.get("https://google.com")

    # inside of a request context, `bitbucket` should be a proxy to the correct
    # blueprint session
    with app1.test_request_context("/"):
        app1.preprocess_request()
        bitbucket.get("https://google.com")
        request = responses.calls[0].request
        assert request.headers["Authorization"] == "Bearer app1"

    with app2.test_request_context("/"):
        app2.preprocess_request()
        bitbucket.get("https://google.com")
        request = responses.calls[1].request
        assert request.headers["Authorization"] == "Bearer app2"
Beispiel #12
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 #13
0
def create_app(config):
    if config is None:
        config = "dev"
    if not os.path.isfile(CONFIG_FILE):
        create_config()
    # Create Flask application
    app = Flask(__name__)
    app.config.from_object(configurations[config])

    # set 404 errors to the not_found function
    app.error_handler_spec[None][404] = not_found

    # Init flask extentinons
    db.init_app(app)
    with app.app_context():
        from models import Setting

        try:
            db_version = Setting.db_version()
            if db_version < Setting.DB_VERSION:
                # TODO: Implement settings db upgrade code
                print " * Upgrading the settings database"
        except:
            pass

    from .api_v1 import api_v1

    app.register_blueprint(api_v1)

    return app
def create_app():
    app = Flask(__name__, static_folder="", template_folder="app/admin/templates")
    print app.root_path
    # load config
    app.config.from_object(AdminProdConfig)

    # init extension
    db.init_app(app)

    # init login
    login_manager.login_view = "frontend.login"

    @login_manager.user_loader
    def load_user(id):
        return AdminUser.by_id(id)

    login_manager.init_app(app)

    # init admin
    admin = Admin(name="DD Admin", index_view=HomeView(), url="/admin")
    admin.init_app(app)

    admin.add_view(getAdminUserView())
    admin.add_view(getAdminEmailView())
    admin.add_view(getAdminSellingPostView())
    admin.add_view(getAdminBuyRequestView())
    admin.add_view(getAdminHashtagView())
    admin.add_view(getAdminBugPostView())

    admin.add_view(LogoutView(name="Logout"))

    # register blueprint
    app.register_blueprint(frontend)

    return app
def create_app(settings=None):
    """
    Creates a flask application.

    @param settings: Settings override object.
    @return: The flask application.
    """
    app = Flask(__name__)

    if settings:
        app.config.from_object(settings)
    else:
        args = _generate_args()
        profile = args.pop("profile")
        app.config["DEBUG"] = args.pop("debug")
        config_file = _load_config_file()
        database_uri = _load_database()
        _config_from_config_profile(config_file, profile, app)
        app.config["SQLALCHEMY_DATABASE_URI"] = database_uri

    DB.init_app(app)

    default_controller = __import__("ec2stack.controllers." + "default", None, None, "DEFAULT")
    default_controller = getattr(default_controller, "DEFAULT")
    app.register_blueprint(default_controller)

    return app
def app(request):
    """Flask application fixture."""
    app = Flask("testapp")
    app.config.update(
        TESTING=True, SQLALCHEMY_DATABASE_URI=os.getenv("SQLALCHEMY_DATABASE_URI", "sqlite://"), SERVER_NAME="localhost"
    )
    Babel(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioCollections(app)
    InvenioRecords(app)

    app.register_blueprint(blueprint)

    def teardown():
        with app.app_context():
            db.drop_all()
            current_collections.unregister_signals()

    request.addfinalizer(teardown)

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

    return app
Beispiel #17
0
def create_app(config_obj):
    app = Flask(__name__)
    app.config.from_object(config_obj)
    app.after_request(req_end)
    db.init_app(app)
    app.register_blueprint(blueprint, url_prefix="/library")
    return app
Beispiel #18
0
def create_app(configfile=None):
    # We are using the "Application Factory"-pattern here, which is described
    # in detail inside the Flask docs:
    # http://flask.pocoo.org/docs/patterns/appfactories/

    app = Flask(__name__)

    # We use Flask-Appconfig here, but this is not a requirement
    AppConfig(app)

    # Install our Bootstrap extension
    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)

    # 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

    # We initialize the navigation as well
    nav.init_app(app)

    return app
Beispiel #19
0
def create_app(config_name):
    app = Flask(__name__)
    # Add config
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Init the extensions
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)

    # Add functionality for scss file
    assets.init_app(app)
    # pathes are  to app/static/ directory.
    scss = Bundle("../scss/style.scss", filters="pyscss", output="style.css")
    assets.register("scss_all", scss)

    # Configure the blueprints
    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")

    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)
    from auth import auth as auth_blueprint

    app.register_blueprint(auth_blueprint, url_prefix="/auth")
    from cam import cam as cam_blueprint

    app.register_blueprint(cam_blueprint, url_prefix="/cam")
    from FD import FD as FD_blueprint

    app.register_blueprint(FD_blueprint, url_prefix="/FD")
    from api_5 import api_5 as api_5blueprint

    app.register_blueprint(api_5blueprint, url_prefix="/api_5")
    return app
def base_app():
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    base_app = Flask(__name__, instance_path=instance_path)

    base_app.config.update(
        ACCOUNTS_USE_CELERY=False,
        LOGIN_DISABLED=False,
        SECRET_KEY="testing_key",
        SQLALCHEMY_DATABASE_URI=os.getenv("SQLALCHEMY_DATABASE_URI", "sqlite://"),
        TEST_USER_EMAIL="test_user@example.com",
        TEST_USER_PASSWORD="test_password",
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    Babel(base_app)
    Mail(base_app)
    Menu(base_app)
    InvenioDB(base_app)
    InvenioAccounts(base_app)
    base_app.register_blueprint(accounts_blueprint)

    with base_app.app_context():
        if str(db.engine.url) != "sqlite://" and not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.drop_all()
        db.create_all()

    def teardown():
        drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    return base_app
Beispiel #22
0
 def test_static_folder_from_disk(self):
     bp = BlohgBlueprint("foo", __name__, static_folder="st")
     app = Flask(__name__)
     app.register_blueprint(bp)
     view_func = app.view_functions["foo.static"]
     # poor test, but should be enough :)
     self.assertEquals(view_func.__name__, "send_static_file")
Beispiel #23
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)
    csrf.init_app(app)
    mail.init_app(app)

    from .client import client as client_blueprint

    app.register_blueprint(client_blueprint)

    from .chef import chef as chef_blueprint

    app.register_blueprint(chef_blueprint, url_prefix="/chef")

    from .admin import admin as admin_blueprint

    app.register_blueprint(admin_blueprint, url_prefix="/admin")

    from .auth import auth as auth_blueprint

    app.register_blueprint(auth_blueprint, url_prefix="/auth")

    from .api_1_0 import api as api_1_0_blueprint

    app.register_blueprint(api_1_0_blueprint, url_prefix="/api/v1.0")
    return app
Beispiel #24
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 #25
0
def create_app():
    app = Flask(__name__)
    # config
    app.config.from_object(settings)
    app.config.from_envvar("RANKING_SETTINGS")
    #
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler

        mail_handler = SMTPHandler(
            "127.0.0.1", "aplikacja@rankingkartgraficznych.pl", "kbogus@gmail.com", "Problem z rankingiem gpu"
        )
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    #
    rdata = RData()
    app.extensions["ranking"] = rdata
    #
    if app.debug:
        rdata.toolbar = DebugToolbarExtension(app)
    rdata.admin = Admin(app, url="/kaspvmqweurbvhasdlj")
    # model
    rdata.model = RData()
    rdata.model.db = SQLAlchemy(app)
    from .model import init_app

    init_app(app)
    #
    register_jinja_filters(app)
    # blueprints
    app.register_blueprint(blp_ranking, url_prefix="/")
    app.register_blueprint(blp_seo_stuff, url_prefix="/")
    return app
 def startService(self):
     app = Flask(__name__)
     app.config["UPLOADDIR"] = self.tempDirectory
     app.config["LOGGER"] = self.restUploadServiceLogger
     app.register_blueprint(uploadAPI)
     self.logger.info("Starting Flask with upload directory: " + self.tempDirectory)
     app.run(threaded=True)
Beispiel #27
0
def create_app(config_name):
    app = Flask(__name__)
    """Based on the name passed as argument to
       create_app method, it is used as key to
       get the config object asociated to tha key
       in this case can be DevConfig or ProdConfig classes"""
    app.config.from_object(config[config_name])
    """Pass the object Flask referenced by the variable db
       to the Configuration Class obtained by key"""
    config[config_name].init_app(app)

    """Once the application is created and configured
       the extentions can be initialized. Calling __init_app
       on the extentions that were created earlies completes
       their initialization"""
    bootstrap.init_app(app)
    db.init_app(app)

    """Blueprints registre"""

    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .inventory import inventory as inventory_blueprint

    app.register_blueprint(inventory_blueprint, url_prefix="/inventory")

    return app
Beispiel #28
0
def create_app(config_name):
    app = Flask(__name__)

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

    # logger
    init_app_logger(app)

    # blueprint
    app.register_blueprint(views.home)
    app.register_blueprint(views.account)
    app.register_blueprint(views.admin)
    app.register_blueprint(views.api)
    app.register_blueprint(views.order)

    # database & migrate
    db.init_app(app)
    migrate.init_app(app, db)

    # mail
    mail.init_app(app)

    login_manager.init_app(app)

    bootstrap.init_app(app)
    # print app.extensions['bootstrap']['cdns']

    config_request_handlers(app)
    config_error_handlers(app)

    return app
    def setUp(self):
        app = Flask(__name__)
        self.username = "testing@example.com"
        self.password = "ShowMeTheMoney"

        def is_valid_user(username, password):
            return (username, password) == (self.username, self.password)

        self.tasks = [{"id": 1, "task": "Do the laundry"}, {"id": 2, "task": "Do the dishes"}]

        def get_tasks(request):
            return self.tasks

        api_201409 = Api(version="v1")
        api_201409.register_endpoint(
            ApiEndpoint(
                http_method="GET",
                endpoint="/task/basic",
                handler=get_tasks,
                authentication=BasicAuth(is_valid_user=is_valid_user),
            )
        )

        app.register_blueprint(api_201409)

        app.config["TESTING"] = True
        self.app = app.test_client()
Beispiel #30
0
def create_app(package_dir):
    app = Flask(__name__)
    if not os.path.isdir(package_dir):
        os.makedirs(package_dir)
    app.config["local_file_store"] = PackageStore(package_dir)
    app.register_blueprint(views)
    return app