Beispiel #1
1
def get_app(database_uri, exclude_tables=None, user_models=None, reflect_all=True, read_only=False):
    """Return an application instance connected to the database described in
    *database_uri*.

    :param str database_uri: The URI connection string for the database
    :param list exclude_tables: A list of tables to exclude from the API
                                service
    :param list user_models: A list of user-defined models to include in the
                             API service
    :param bool reflect_all: Include all database tables in the API service
    :param bool read_only: Only allow HTTP GET commands for all endpoints
    """
    app = Flask("sandman2")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_uri
    app.config["SANDMAN2_READ_ONLY"] = read_only
    db.init_app(app)
    admin = Admin(app, base_template="layout.html", template_mode="bootstrap3")
    _register_error_handlers(app)
    if user_models:
        with app.app_context():
            _register_user_models(user_models, admin)
    elif reflect_all:
        with app.app_context():
            _reflect_all(exclude_tables, admin, read_only)
    return app
Beispiel #2
1
def create_app():
    """
    Creates the Flask app instance

    @return: Flask app
    @rtype: flask.Flask
    """
    from flask import Flask

    app = Flask(__name__)
    # set debug to true so we see error dumps in the browser
    app.debug = settings.APP_DEBUG
    app.secret_key = settings.APP_SECRET_KEY
    app.config["SQLALCHEMY_DATABASE_URI"] = settings.DATABASE[env]["uri"]
    app.config["BASE_URL"] = settings.BASE_URL
    app.config["SQLALCHEMY_ECHO"] = settings.DATABASE[env]["echo"]
    app.config["RECAPTCHA_PUBLIC_KEY"] = settings.RECAPTCHA_PUBLIC_KEY
    app.config["RECAPTCHA_PRIVATE_KEY"] = settings.RECAPTCHA_PRIVATE_KEY
    app.config["SERVER_NAME"] = settings.BASE_URL

    app.jinja_options["extensions"].append("jinja2.ext.loopcontrols")
    my_loader = jinja2.ChoiceLoader(
        [app.jinja_loader, jinja2.FileSystemLoader([os.path.dirname(os.path.abspath(__file__)) + "/static"])]
    )
    app.jinja_loader = my_loader

    return app
Beispiel #3
1
def create_app():
    options = {"port": 0, "unitTesting": False}
    WebConfig.config(options)

    b = Borg()
    app = Flask(__name__)
    app.config["DEBUG"] = True
    app.config["SECRET_KEY"] = b.secretKey
    app.config["SECURITY_PASSWORD_HASH"] = b.passwordHash
    app.config["SECURITY_PASSWORD_SALT"] = b.passwordSalt
    app.config["SQLALCHEMY_DATABASE_URI"] = (
        "mysql://" + b.auth_dbUser + ":" + b.auth_dbPasswd + "@" + b.auth_dbHost + "/" + b.auth_dbName
    )
    b.logger.setLevel(b.logLevel)
    b.logger.debug("Error handlers: {0}".format(app.error_handler_spec))
    app.secret_key = os.urandom(24)
    logger = logging.getLogger("werkzeug")
    logger.setLevel(b.logLevel)
    enable_debug = b.logLevel = logging.DEBUG

    cors = CORS(app)
    db.init_app(app)
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    from main import main as main_blueprint

    app.register_blueprint(main_blueprint)

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

    return app
Beispiel #4
0
def create_app(debug=True):
    """Create an application."""
    app = Flask(__name__)
    app.debug = debug
    app.config["SECRET_KEY"] = "gjr39dkjn344_!67#"
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://anthony:dx9Vzxq6fr@localhost/vpnp"
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]
    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)
    db.init_app(app=app)
    socketio.init_app(app)
    return app
Beispiel #5
0
def create_app():
    app = Flask(__name__, static_folder=static_folder)

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

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

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

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

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

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

    # URL Rules / Blueprints
    from main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    # Admin view
    from admin import create_admin

    create_admin(app)

    return app
Beispiel #6
0
def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # Use prod, or dev database depending on debug mode
    if DEBUG_MODE:
        app.debug = DEBUG_MODE
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + TEST_DB
    else:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + DB
    init_db()
    sms_controller = APIController(username=FLOWROUTE_ACCESS_KEY, password=FLOWROUTE_SECRET_KEY)

    # Attach the Flowroute messaging controller to the app
    app.sms_controller = sms_controller
    return app
Beispiel #7
0
def create_app(database_connection):
    app = Flask("Distributed Cuckoo")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_connection
    app.config["SECRET_KEY"] = os.urandom(32)

    for blueprint, routes in blueprints:
        for route in routes:
            app.register_blueprint(blueprint, url_prefix=route)

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

    # Check whether an alembic version is present and whether
    # we're up-to-date.
    with app.app_context():
        row = AlembicVersion.query.first()
        if not row:
            db.session.add(AlembicVersion(AlembicVersion.VERSION))
            db.session.commit()
        elif row.version_num != AlembicVersion.VERSION:
            sys.exit(
                "Your database is not up-to-date. Please upgrade it " "using alembic (run `alembic upgrade head`)."
            )

    return app
Beispiel #8
0
    def test_flask(self):
        app = Flask(__name__)
        db = SQLAlchemy(app)
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"

        class Cities(db.Model):
            __tablename__ = "users"

            id = Column(Integer, primary_key=True)
            name = Column(String)
            population = Column(Integer)

            def __init__(self, name, population):
                self.name = name
                self.population = population

        app.config["TESTING"] = True
        app = app.test_client()
        db.create_all()

        city = Cities("Cordoba", 1000000)
        db.session.add(city)
        city = Cities("Rafaela", 99000)
        db.session.add(city)
        db.session.commit()

        query_string = '{ "sort": { "population" : "desc" } }'
        results = elastic_query(Cities, query_string)
        assert results[0].name == "Cordoba"
Beispiel #9
0
    def create_app():

        global db, bootstrap, mail, login_manager, moment, pagedown
        app = Flask(__name__)

        from main import main as main_blueprint
        from auth import auth as auth_blueprint
        from admin import admin as admin_blueprint

        app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://flask:gf37888676@172.17.0.25/flask"
        app.config["SQLAlCHEMY_COMMIT_ON_TEARDOWN"] = True
        app.config["FLASK_ADMIN"] = "iamawar3player@163.com"
        app.config["FLASK_MAIL_SUBJECT_PREFIX"] = "[Flasky]"
        app.config["FLASK_MAIL_SENDER"] = "Flasky Admin <iamawar3player@163.com>"
        app.config["MAIL_SERVER"] = "smtp.163.com"
        app.config["MAIL_PORT"] = 25
        app.config["MAIL_USE_TLS"] = False
        app.config["MAIL_USERNAME"] = "iamawar3player@163.com"
        app.config["MAIL_PASSWORD"] = "fan86797121"
        app.config["DEBUG"] = True
        app.config["FLASKY_POSTS_PER_PAGE"] = 10
        app.config["SECRET_KEY"] = "gf37888676"
        app.register_blueprint(main_blueprint)
        app.register_blueprint(auth_blueprint, url_prefix="/auth")
        app.register_blueprint(admin_blueprint, url_prefix="/admin")

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

        return app
def test_flask_sqlalchemy():
    from flask.ext.sqlalchemy import SQLAlchemy as FlaskSQLAlchemy

    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///"
    db = FlaskSQLAlchemy(app)

    class UserMixin(object):
        email = db.Column(db.Unicode(300))

        def __init__(self, login, email):
            self.login = login
            self.email = email
            self.password = "foobar"

    class RoleMixin(object):
        description = db.Column(db.UnicodeText)

    auth = authcode.Auth(SECRET_KEY, db=db, UserMixin=UserMixin, RoleMixin=RoleMixin)
    authcode.setup_for_flask(auth, app)
    User = auth.User

    db.create_all()
    user = User(u"meh", u"text@example.com")
    db.session.add(user)
    db.session.commit()

    assert user.login == u"meh"
    assert user.email == u"text@example.com"
    assert hasattr(user, "password")
    assert hasattr(user, "last_sign_in")
    assert repr(user) == "<User meh>"
Beispiel #11
0
def create_app(root: str, config: str) -> Flask:
    """Create a new Flask application with the provided configuration.

    :param root: The application root module name.
    :param config: The application configuration mode.
    """
    app = Flask(__name__)
    app.config.from_object(CONFIG_PATH_FORMAT % (root, config))

    if app.config["INIT"]["debug"]:
        print(LOG_MODE_DEBUG)
    else:
        print(LOG_MODE_PRODUCTION)

    if app.config["GOOGLECLIENTID"]:
        print(LOG_ID_FORMAT % app.config["GOOGLECLIENTID"])
    else:
        print(LOG_ID_NOT_FOUND)

    # Async socket initialization
    eventlet.monkey_patch()
    socketio.init_app(app)

    # Configuration for mySQL database
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = app.config["DATABASE_URL"].replace("mysql", "mysql+pymysql", 1)
    db.init_app(app)

    # Configuration for login sessions
    app.secret_key = app.config["SECRET_KEY"]
    login_manager.init_app(app)

    # Flask Debug Toolbar
    toolbar.init_app(app)

    # Database migration management
    migrate.init_app(app, db)
    migration_manager(app)

    from .public.views import public
    from .queue.views import queue
    from .admin.views import admin
    from .dashboard.views import dashboard

    BLUEPRINTS = [public, queue, admin, dashboard]

    for blueprint in BLUEPRINTS:
        print(' * Registering blueprint "%s"' % blueprint.name)
        app.register_blueprint(blueprint)

    # subdomain routes with special urls
    app.register_blueprint(admin, url_prefix="/subdomain/<string:queue_url>/admin")
    app.register_blueprint(queue, url_prefix="/subdomain/<string:queue_url>")

    # register error handlers
    app.register_error_handler(401, standard_error)
    app.register_error_handler(404, error_not_found)
    app.register_error_handler(500, error_server)

    return app
Beispiel #12
0
def make_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(base, "site.db")
    app.secret_key = "IShouldntTellAnyoneThisString"
    register_blueprints(app)
    db.init_app(app)
    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 setUp(self):
        _ENGINES.clear()
        _BASES.clear()
        app = Flask(__name__)
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.sqlite"
        db.init_app(app)
        self.app = app
        with app.app_context():
            db.create_all(app=app)
            self.db = db
            self.user = User(username="user", password="password", database_uri="sqlite:///:memory:")
            db.session.add(self.user)
            try:
                db.session.commit()
            except IntegrityError:
                db.session.rollback()
        self.engine = create_engine("sqlite:///:memory:")
        self.base = declarative_base()

        class Blah(self.base):
            __tablename__ = "blah"
            id = Column(Integer, primary_key=True)

        self.model = Blah
        self.base.metadata.create_all(self.engine)
        _ENGINES["sqlite:///:memory:"] = self.engine
Beispiel #15
0
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:
        config_file = _load_config_file()
        app.config.from_pyfile(config_file)
        database_uri = _load_database()
        app.config["SQLALCHEMY_DATABASE_URI"] = database_uri

    _valid_config_file(app)
    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
Beispiel #16
0
def create_app(config=None):
    app = Flask(__name__)

    app.config["SECRET_KEY"] = "129iv3n91283nv9812n3v89q2nnv9iaszv978n98qwe7z897d"
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://postgres@localhost/mooddiaryDb"
    # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/mooddiary.db'

    app.config["DEBUG"] = True
    app.config["LESS_BIN"] = os.path.realpath(os.path.join(os.path.dirname(__file__), "../node_modules/less/bin/lessc"))

    app.config["JWT_EXPIRATION_DELTA"] = timedelta(days=28)
    app.config["JWT_ALGORITHM"] = "HS512"

    app.config["RECAPTCHA_SECRET_KEY"] = "6LdSswwTAAAAADs20eK6NqYaeppxIWm-gJrpto0l"
    app.config["RECAPTCHA_PUBLIC_KEY"] = "6LdSswwTAAAAABTZq5Za_0blmaSpcg-dFcqaGda9"

    if config:
        app.config.from_object(config)

    app.config["ASSETS_DEBUG"] = app.config["DEBUG"]

    db.init_app(app)
    migrate.init_app(app, db)
    assets.init_app(app)
    jwt.init_app(app)

    assets.register("js", js)
    assets.register("css", css)

    app.register_blueprint(main)
    app.register_blueprint(api, url_prefix="/api")
    app.register_blueprint(auth, url_prefix="/auth")

    return app
def create_schema(uri, pkg_name):
    app = Flask("schema generator")
    app.config["SQLALCHEMY_DATABASE_URI"] = uri
    list(load_all_modules(pkg_name))
    db.init_app(app)
    with app.app_context():
        db.create_all()
Beispiel #18
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
        app.logger.disabled = True
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()

        # Ensure that all requests have Content-Type set to "application/json"
        # unless otherwise specified.
        for methodname in ("get", "put", "patch", "post", "delete"):
            # Create a decorator for the test client request methods that adds
            # a JSON Content-Type by default if none is specified.
            def set_content_type(func):
                def new_func(*args, **kw):
                    if "content_type" not in kw:
                        kw["content_type"] = "application/json"
                    return func(*args, **kw)

                return new_func

            # Decorate the original test client request method.
            old_method = getattr(self.app, methodname)
            setattr(self.app, methodname, set_content_type(old_method))
def create_app():
    global app, db, es

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object("annotator.default_settings")
    app.config["SQLALCHEMY_DATABASE_URI"] = app.config["SQLALCHEMY_DATABASE_URI"] % app.instance_path

    app.config.from_pyfile("annotator.cfg", silent=True)
    app.config.from_envvar("ANNOTATOR_CONFIG", silent=True)

    # Configure database
    db.init_app(app)

    # Configure ES
    from . import model

    es = pyes.ES(app.config["ELASTICSEARCH_HOST"])
    model.annotation.configure(es, app.config)

    # Mount controllers
    from annotator import store, user, home

    if app.config["MOUNT_STORE"]:
        app.register_blueprint(store.store, url_prefix=app.config["MOUNT_STORE"])
    if app.config["MOUNT_USER"]:
        app.register_blueprint(user.user, url_prefix=app.config["MOUNT_USER"])
    if app.config["MOUNT_HOME"]:
        app.register_blueprint(home.home, url_prefix=app.config["MOUNT_HOME"])

    @app.before_request
    def before_request():
        g.user = user.get_current_user()

    return app
Beispiel #20
0
def create_app(name):
    # create our little application :)
    app = Flask(name)
    app.config["SQLALCHEMY_DATABASE_URI"] = DATABASE_URI
    app.config.from_object(__name__)
    app.config.from_envvar("FLASKR_SETTINGS", silent=True)
    return app
Beispiel #21
0
def create_app(config=Config()):
    """Flask application factory."""

    app = Flask(__name__)

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

    # override settings by environment variables

    if "DEBUG" in os.environ:
        app.config["DEBUG"] = os.environ["DEBUG"].lower() == "true"

    if "SECRET_KEY" in os.environ:
        app.config["SECRET_KEY"] = os.environ["SECRET_KEY"]

    if "SSL_ENABLE_REDIRECTS" in os.environ:
        app.config["SSL_ENABLE_REDIRECTS"] = os.environ["SSL_ENABLE_REDIRECTS"].lower() == "true"

    if "DATABASE_URL" in os.environ:
        app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]

    db.init_app(app)
    babel = Babel(app)
    login_manager.setup_app(app)
    oid.init_app(app)
    DebugToolbarExtension(app)

    app.register_blueprint(times)

    admin = Admin(app, url_prefix="/admin", title="Admin")
    admin.add_path_security("/", secure_admin_path)
    admin.add_path_security("/auth", secure_admin_auth_path)

    auth_node = admin.register_node("/auth", "auth", "Authentication")
    time_node = admin.register_node("/time_node", "time_node", "Times")

    admin.register_module(UserAdmin, "/users", "users", "Users", parent=auth_node)
    admin.register_module(CompanyAdmin, "/companies", "companies", "Companies", parent=time_node)
    admin.register_module(ProjectAdmin, "/projects", "projects", "Projects", parent=time_node)
    admin.register_module(TaskAdmin, "/tasks", "tasks", "Tasks", parent=time_node)
    admin.register_module(WorkingUnitAdmin, "/times", "times", "Working Times", parent=time_node)

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

    @app.context_processor
    def inject_context():
        version = os.environ.get("VERSION", "devel")
        return dict(user=current_user, now=datetime.now(), version=version)

    @babel.localeselector
    def get_locale():
        if hasattr(current_user, "locale"):
            return current_user.locale
        return request.accept_languages.best_match(["en", "ja", "de"])

    return app
def test_db():
    """Test database backend."""
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI", "sqlite:///test.db")
    FlaskCLI(app)
    InvenioDB(app)
    InvenioRecords(app)

    with app.app_context():
        db.create_all()
        assert "records_metadata" in db.metadata.tables
        assert "records_metadata_version" in db.metadata.tables
        assert "transaction" in db.metadata.tables

    schema = {
        "type": "object",
        "properties": {"title": {"type": "string"}, "field": {"type": "boolean"}, "hello": {"type": "array"}},
        "required": ["title"],
    }
    data = {"title": "Test", "$schema": schema}
    from invenio_records.models import RecordMetadata as RM

    # Create a record
    with app.app_context():
        assert RM.query.count() == 0

        record_uuid = Record.create(data).id
        db.session.commit()

        assert RM.query.count() == 1
        db.session.commit()

    # Retrieve created record
    with app.app_context():
        record = Record.get_record(record_uuid)
        assert record.dumps() == data
        with pytest.raises(NoResultFound):
            Record.get_record(uuid.uuid4())
        record["field"] = True
        record = record.patch([{"op": "add", "path": "/hello", "value": ["world"]}])
        assert record["hello"] == ["world"]
        record.commit()
        db.session.commit()

    with app.app_context():
        record2 = Record.get_record(record_uuid)
        assert record2.model.version_id == 2
        assert record2["field"]
        assert record2["hello"] == ["world"]
        db.session.commit()

    # Cannot commit record without model (i.e. Record.create_record)
    with app.app_context():
        record3 = Record({"title": "Not possible"})
        with pytest.raises(MissingModelError):
            record3.commit()

    with app.app_context():
        db.drop_all()
Beispiel #23
0
def create_app(sqlalchemy_uri=None):
    from .extensions import db, redis_store, regions, configure_uploads, documents, images

    app = Flask(__name__)
    app.config.from_object("APITaxi.default_settings")
    if "APITAXI_CONFIG_FILE" in os.environ:
        app.config.from_envvar("APITAXI_CONFIG_FILE")
    if not "ENV" in app.config:
        app.logger.error("ENV is needed in the configuration")
        return None
    if app.config["ENV"] not in ("PROD", "STAGING", "DEV"):
        app.logger.error(
            """Here are the possible values for conf['ENV']:
        ('PROD', 'STAGING', 'DEV') your's is: {}""".format(
                app.config["env"]
            )
        )
        return None
    # Load configuration from environment variables
    for k in app.config.keys():
        if not k in os.environ:
            continue
        app.config[k] = os.environ[k]
    if sqlalchemy_uri:
        app.config["SQLALCHEMY_DATABASE_URI"] = sqlalchemy_uri

    db.init_app(app)
    redis_store.init_app(app)
    redis_store.connection_pool.get_connection(0).can_read()
    from . import backoffice

    backoffice.init_app(app)
    from . import api

    api.init_app(app)
    from . import documentation

    documentation.init_app(app)
    Bootstrap(app)

    request_started.connect(check_version, app)
    request_finished.connect(add_version_header, app)

    configure_uploads(app, (documents, images))
    from .utils.login_manager import init_app as init_login_manager

    init_login_manager(app)
    from . import demo

    demo.create_app(app)
    for region in regions.values():
        if not region.is_configured:
            region.configure(app.config["DOGPILE_CACHE_BACKEND"])
    from . import tasks

    tasks.init_app(app)

    models_committed.connect_via(app)(commit_signal)
    return app
Beispiel #24
0
def create_app(db_uri="postgresql://@/updatechecker"):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = db_uri
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.debug = getenv("DEBUG")
    app.register_blueprint(blueprint)
    db.init_app(app)
    return app
Beispiel #25
0
 def create_app(self):
     app = Flask(__name__)
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
     app.config["TESTING"] = True
     # app.config['SQLALCHEMY_ECHO'] = True
     app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
     db.init_app(app)
     return app
def get_app():
    app = Flask(__name__)
    CORS(app)
    app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv(
        "MDDB_DSN", "postgresql://httpd_meta@monsoon.pcic.uvic.ca/pcic_meta"
    )
    add_routes(app)
    return app
Beispiel #27
0
 def setUp(self):
     app = Flask("tests", static_url_path="/static")
     app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
     app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:////tmp/test_idb.db"
     db.init_app(app)
     db.app = app
     db.configure_mappers()
     db.create_all()
Beispiel #28
0
def Session():
    # this should make you sad.  Does it make you sad?
    # it should.
    # seriously. it is hard to explain how sad this should make you.
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = sqlalchemyuri
    db = SQLAlchemy(app)
    return db.session
Beispiel #29
0
def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///stress.db"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.init_app(app)
    with app.app_context():
        db.create_all()
    return app
Beispiel #30
0
def webapp(request):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
    app.config["PROPAGATE_EXCEPTIONS"] = True

    db = SQLAlchemy(app)

    class Object(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        field1 = db.Column(db.Integer)
        field2 = db.Column(db.Integer)

    db.create_all()

    @app.route("/objects")
    @paginated_view
    @sorted_view(allowed_fields=["id", "field1"])
    def view_objects():
        return Object.query

    @app.route("/objects_different_renderer")
    @paginated_view(renderer=lambda obj: {"id_value": obj.id})
    def view_objects_different_renderer():
        return Object.query

    @app.route("/objects_limited_page_size")
    @paginated_view(max_page_size=10, default_page_size=5)
    def view_objects_limited_page_size():
        return Object.query

    @app.route("/objects_no_count")
    @paginated_view(max_page_size=10, default_page_size=5, include_count=False)
    def view_objects_no_count():
        return Object.query

    @app.route("/objects_by_field2")
    @paginated_view
    @sorted_view(default="-field2")
    def view_objects_by_field2():
        return Object.query

    num_objects = 100
    field1_values = list(range(num_objects))
    random.shuffle(field1_values)
    field2_values = list(range(num_objects))
    random.shuffle(field2_values)

    for field1_value, field2_value in zip(field1_values, field2_values):
        db.session.add(Object(field1=field1_value, field2=field2_value))

    db.session.commit()

    returned = App(app)
    returned.num_objects = num_objects
    returned.activate()
    request.addfinalizer(returned.deactivate)

    return returned