Example #1
0
def create_app():   # We could pass a config object here
    app = Flask(__name__)
    app.debug = os.environ.get('TIMERBOARD_PRODUCTION', True)
    app.config.from_envvar("TIMERBOARD_SETTINGS")
    with open(os.environ["TIMERBOARD_SETTINGS"]) as fh:
        app.myconfig = json.loads(fh.read())
    app.config["SQLALCHEMY_DATABASE_URI"] = app.myconfig["SQLALCHEMY_DATABASE_URI"]
    # Register template filters here
    # app.add_template_filter(some_method)

    #app.config.from_object(config)
    #app.config.from_pyfile(config_filename)

    app.secret_key = os.urandom(24)
    assets.init_app(app)
    login_manager.init_app(app)

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

    from users.views import mod as users_blueprint
    from assets import mod as assets_blueprint
    from login import mod as login_blueprint
    app.register_blueprint(users_blueprint)
    app.register_blueprint(assets_blueprint)
    app.register_blueprint(login_blueprint)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        app.db.session.remove()

    return app
Example #2
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
Example #3
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
Example #4
0
File: run.py Project: gamegos/cesi
def create_app(cesi):
    from api.v2 import register_blueprints

    app = Flask(
        __name__,
        static_folder="ui/build",
        static_url_path="",
        template_folder="ui/build",
    )
    app.config["SQLALCHEMY_DATABASE_URI"] = cesi.database
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    app.secret_key = os.urandom(24)

    db.init_app(app)

    app.add_url_rule("/", "index", lambda: render_template("index.html"))
    app.add_url_rule(
        "/api/version",
        "version",
        lambda: jsonify(status="success", version=__version__),
    )

    @app.errorhandler(404)
    @app.errorhandler(400)
    def _(error):
        return jsonify(status="error", message=error.description), error.code

    register_blueprints(app)

    return app
Example #5
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()
Example #6
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
Example #7
0
def create_app():
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://postgres:123456@127.0.0.1:15432"
    db.init_app(app)
    migrate = Migrate(app,db)

    app.register_blueprint(api)

    return app
Example #8
0
def temp_db_context(uri="sqlite:///:memory:", echo=False):
    from flask import Flask

    app = Flask("dummy")
    app.config["SQLALCHEMY_DATABASE_URI"] = uri
    app.config["SQLALCHEMY_ECHO"] = echo
    db.init_app(app)
    with app.app_context():
        yield db
def setup():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "1"
    app.config["CSRF_ENABLED"] = False
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///"

    db = SQLAlchemy(app)
    admin = Admin(app)

    return app, db, admin
Example #10
0
def create_app(name=None, config=None):
    """Create the Flask application."""
    name = 'invenio_kwalitee' if name is None else name
    app = Flask(name, template_folder="templates", static_folder="static",
                instance_relative_config=True)

    # Load default configuration
    app.config.from_object("invenio_kwalitee.config")

    # Load invenio_kwalitee.cfg from instance folder
    app.config.from_pyfile("invenio_kwalitee.cfg", silent=True)
    app.config.from_envvar("INVENIO_KWALITEE_CONFIG", silent=True)
    app.config.update(config or {})

    # Create instance path
    if not os.path.exists(app.instance_path):
        os.makedirs(app.instance_path)

    # Setting up the database
    database = os.path.join(app.instance_path,
                            app.config.get("DATABASE_NAME", "database"))
    database = "{0}.db".format(database)
    app.config["DATABASE"] = database
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///{0}".format(database)
    from .models import db, init_app
    init_app(app)
    if not os.path.exists(database):
        db.create_all()

    # Setting up RQ
    from .worker import init_app
    init_app(app)

    # Setting up the views
    app.url_map.converters['sha'] = ShaConverter
    from . import views
    app.add_url_rule("/", "index", views.index, methods=["GET"])
    app.add_url_rule("/<account>/", "account", views.account, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/", "repository", views.repository,
                     methods=["GET"])
    app.add_url_rule("/<account>/<repository>/commits/<sha:sha>/", "commit",
                     views.commit, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/branches/<sha:sha>/<path:branch>",
                     "branch_status", views.branch_status, methods=["GET"])
    app.add_url_rule("/<account>/<repository>/branches/<path:branch>", "branch",
                     views.branch, methods=["GET"])
    app.add_url_rule("/payload", "payload", views.payload, methods=["POST"])
    # legacy
    app.add_url_rule("/status/<sha>", "status", views.status, methods=["GET"])

    if app.debug:
        from werkzeug.debug import DebuggedApplication
        app.wsgi_app = DebuggedApplication(app.wsgi_app, evalex=True)

    return app
Example #11
0
def app(blueprint, db, request):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URI", "sqlite://")
    app.config["CACHE_TYPE"] = "simple"
    app.secret_key = "secret"
    app.register_blueprint(blueprint, url_prefix="/login")
    db.init_app(app)
    # establish app context
    ctx = app.app_context()
    ctx.push()
    request.addfinalizer(ctx.pop)
    return app
Example #12
0
def create_app(database_connection):
    app = Flask("Distributed Cuckoo")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_connection
    app.config["SECRET_KEY"] = os.urandom(32)

    app.register_blueprint(ApiBlueprint, url_prefix="/api")
    app.register_blueprint(ApiBlueprint, url_prefix="/api/v1")

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

    return app
Example #13
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        super(FlaskTestBase, self).setUp()

        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///%s" % DB["filename"]
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()
Example #14
0
def create_app(test=False):
    app = Flask(__name__)
    app.config["ADMIN_EMAIL"] = "admin@todos.com"
    app.config["ADMIN_PASSWORD"] = "123456"

    if test:
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
        app.config["SQLALCHEMY_ECHO"] = True
    else:
        db_path = os.path.join(app.root_path, "todos.db")
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_path
    db.init_app(app)

    bp_api = Blueprint('api', __name__, static_folder='static')
    api.init_app(app, blueprint=bp_api, docs=__doc__)
    auth.init_api(api, fn_user_role=fn_user_role)

    api.add_resource(Todos)
    api.add_resource(User)
    api.add_resource(Permission, auth=auth)
    api.add_resource(ApiInfo, api=api)

    def make_view(filename):
        return lambda *args, **kwargs: app.send_static_file(filename)
    for url, filename in url_views:
        end = os.path.splitext(filename)[0]
        app.route(url, endpoint=end)(make_view(filename))

    app.before_first_request(before_first_request)
    app.register_blueprint(bp_api, url_prefix='/api')

    gen = Gen(api)
    gen.resjs('static/js/res.js')
    gen.resdocs('static/resdocs.html', resjs='/static/js/res.js',
                bootstrap='/static/css/bootstrap.min.css')
    gen.permission('static/permission.html', resjs='/static/js/res.js',
                   bootstrap='/static/css/bootstrap.min.css',
                   vuejs='/static/js/vue.js')
    return app
Example #15
0
def create_app(uri):
    """ dynamically create the app """
    app = Flask(__name__, static_url_path="", static_folder="./static")
    app.config["SQLALCHEMY_DATABASE_URI"] = uri
    init_engine(app.config["SQLALCHEMY_DATABASE_URI"])

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    import landing

    app.register_blueprint(landing.app)
    return app
Example #16
0
File: app.py Project: tsh/workload
def create_app():

    basedir = os.path.abspath(os.path.dirname(__file__))
    db_path = os.path.join(basedir, "data.sqlite")

    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL") or "sqlite:///" + db_path

    db.init_app(app)

    app.secret_key = "super secret key"
    app.config["SESSION_TYPE"] = "filesystem"
    app.config["SECRET_KEY"] = "top-secret!"
    return app
Example #17
0
    def test_mixer(self):
        from flask import Flask
        from flask_mixer import Mixer
        from .models import db, User

        app = Flask(__name__)
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///:memory:"
        db.init_app(app)
        mixer = Mixer(session_commit=True)
        mixer.init_app(app)

        with app.test_request_context():

            db.create_all()

            node = mixer.blend("tests.models.Node")
            self.assertTrue(node.id)
            self.assertFalse(node.parent)

            role = mixer.blend("tests.models.Role")
            self.assertTrue(role.user)
            self.assertEqual(role.user_id, role.user.id)

            user = mixer.blend(User)
            self.assertTrue(user.id)
            self.assertTrue(user.username)
            self.assertEqual(user.score, 50)
            self.assertTrue(user.created_at)
            self.assertTrue(user.profile)
            self.assertEqual(user.profile.user, user)

            user = mixer.blend(User, username="test")
            self.assertEqual(user.username, "test")

            role = mixer.blend("tests.models.Role", user__username="test2")
            self.assertEqual(role.user.username, "test2")

            users = User.query.all()
            role = mixer.blend("tests.models.Role", user=mixer.random)
            self.assertTrue(role.user in users)

            profile = mixer.blend("tests.models.Profile")
            user = mixer.blend(User, profile=profile)
            self.assertEqual(user.profile, profile)

            user = mixer.blend(User, score=mixer.random)
            self.assertNotEqual(user.score, 50)

            user = mixer.blend(User, username=lambda: "callable_value")
            self.assertEqual(user.username, "callable_value")
Example #18
0
def create_app(database_uri="sqlite://"):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = database_uri
    app.config["SECRET_KEY"] = "not secure"
    db.init_app(app)
    datastore = SQLAlchemyDatastore((Address, Location, Asset), db.session, exclude_pks=False)
    admin_blueprint = admin.create_admin_blueprint(datastore)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    db.create_all(app=app)

    @app.route("/")
    def go_to_admin():
        return redirect("/admin")

    return app
def create_app(database_uri="sqlite://"):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = database_uri
    app.config["SECRET_KEY"] = "seeeeecret"

    db.init_app(app)
    admin_blueprint = admin.create_admin_blueprint((User, Post, Category), db.session)
    app.register_blueprint(admin_blueprint, url_prefix="/admin")
    db.create_all(app=app)

    @app.route("/")
    def go_to_admin():
        return redirect("/admin")

    return app
Example #20
0
def create_app():
    app = Flask(__name__, static_url_path="/app", static_folder="static")
    app.debug = True
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://localhost:5432/m2m"
    app.config["SQLALCHEMY_ECHO"] = False
    configure_blueprints(app)
    configure_extensions(app)
    configure_error_handlers(app)
    with app.app_context():
        messagebusctl.run()

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

    return app
Example #21
0
def create_app(database_connection):
    app = Flask("Distributed Cuckoo")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_connection
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config["SECRET_KEY"] = os.urandom(32)

    restapi = DistRestApi(app)
    restapi.add_resource(NodeRootApi, "/node")
    restapi.add_resource(NodeApi, "/node/<string:name>")
    restapi.add_resource(StatusRootApi, "/status")

    db.init_app(app)

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

    return app
Example #22
0
    def create_app(self):
        app = Flask(__name__)
        app.secret_key = "A0Zr98j/3yX R~XHH!jmN]LWX/,?RT"

        # absolute path gets around annoying cwd difference here & in fixtures
        db_uri = "sqlite:///" + os.getcwd() + "/tests.db"
        app.config["SQLALCHEMY_DATABASE_URI"] = db_uri
        principals = Principal(app)

        from models import db

        db.init_app(app)
        self.db = db

        self.sync = Minisync(self.db)

        return app
def create_app(**config):
    app = Flask("iatilib.frontend")

    app.config.update(config)

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

    db.app = app  # don't understand why I need to this
    db.init_app(app)

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

    from .api1 import api

    app.register_blueprint(api, url_prefix="/api/1")
    return app
Example #24
0
File: dist.py Project: 3van/cuckoo
def create_app(database_connection):
    app = Flask("Distributed Cuckoo")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_connection
    app.config["SECRET_KEY"] = os.urandom(32)

    restapi = DistRestApi(app)
    restapi.add_resource(NodeRootApi, "/node")
    restapi.add_resource(NodeApi, "/node/<string:name>")
    restapi.add_resource(TaskRootApi, "/task")
    restapi.add_resource(TaskApi, "/task/<int:task_id>")
    restapi.add_resource(ReportApi,
                         "/report/<int:task_id>",
                         "/report/<int:task_id>/<string:report>")
    restapi.add_resource(StatusRootApi, "/status")

    db.init_app(app)

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

    return app
Example #25
0
def make_app():
    """Initializes the mcdemo application"""
    static_folder = os.path.join(ROOT, "static")
    template_folder = os.path.join(ROOT, "templates")
    from mcdemo import config

    app = Flask(__name__, static_folder=static_folder, template_folder=template_folder)
    app.config.update(config.CONFIG)
    app.config["SQLALCHEMY_DATABASE_URI"] = config.CONFIG["DB_URL"]
    app.config["SQLALCHEMY_BINDS"] = {"admin": config.CONFIG["DB_URL_ADMIN"]}
    db.init_app(app)
    handler = make_colored_stream_handler()
    getLogger("werkzeug").addHandler(handler)
    getLogger("werkzeug").setLevel(INFO)
    getLogger("sqlalchemy").addHandler(handler)
    getLogger("sqlalchemy").setLevel(INFO if app.debug else WARN)

    app.logger.handlers = []
    app.logger.addHandler(handler)
    routes.register(app)
    return app
Example #26
0
def create_app(create_db=False):
    """Creates an app by registering blueprints in the modules directory
    and loading the configuration

    """

    app = Flask(__name__)
    app.secret_key = os.urandom(24)
    register_blueprints(app, "modules", ["modules"])

    app.config["SQLALCHEMY_DATABASE_URI"] = conf.DB
    # Maximum 3Mo pour les images
    app.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024

    db.init_app(app)
    db.app = app

    if create_db:
        db.create_all()

    return app
Example #27
0
def create_app(uri):
    """ dynamically create the app """
    app = Flask(__name__, static_url_path="/static", static_folder="./static")
    # app.config.from_pyfile(config)
    app.config["SQLALCHEMY_DATABASE_URI"] = uri
    init_engine(app.config["SQLALCHEMY_DATABASE_URI"], pool_recycle=3600)
    app.secret_key = "\xda\xe0\xff\xc8`\x99\x93e\xd0\xb9\x0e\xc9\xde\x84?q" "\x9e\x19\xc0\xa1\xa7\xfb\xd0\xde"
    login_manager.init_app(app)
    oauth.init_app(app)

    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db_session.remove()

    @app.before_request
    def before_request():
        g.user = current_user
        g.api_url = API_URL

    @app.errorhandler(401)
    def unauthorized_error_handle(error=None):
        """ handle all unauthorized_errors with redirect to login """
        return redirect(url_for("auth.login"))

    import core.views
    import auth.views
    import user.views
    import product.views
    import artist.views
    import video.views

    # app.register_blueprint(landing.app)
    app.register_blueprint(core.views.core)
    app.register_blueprint(auth.views.auth, url_prefix="/auth")
    app.register_blueprint(user.views.user, url_prefix="/user")
    app.register_blueprint(product.views.product, url_prefix="/product")
    app.register_blueprint(artist.views.artist, url_prefix="/artist")
    app.register_blueprint(video.views.video, url_prefix="/video")

    return app
Example #28
0
def app():
    """Create Flask app"""
    static_folder = os.path.join(ROOT, "static")
    template_folder = os.path.join(ROOT, "templates")
    from pystil import config

    if not config.FROZEN:
        print "Config MUST be frozen before pystil init"
        sys.exit(1)
    app = Flask(__name__, static_folder=static_folder, template_folder=template_folder)
    app.config.update(config.CONFIG)
    app.config["SQLALCHEMY_DATABASE_URI"] = config.CONFIG["DB_URL"]
    db.init_app(app)

    if app.config["LOG_FILE"]:
        basicConfig(filename=app.config["LOG_FILE"], filemode="w", level=INFO)

    handler = make_colored_stream_handler()
    getLogger("werkzeug").addHandler(handler)
    getLogger("werkzeug").setLevel(INFO)
    getLogger("sqlalchemy").addHandler(handler)
    getLogger("sqlalchemy").setLevel(WARN)

    app.logger.handlers = []
    app.logger.addHandler(handler)

    if not app.config.get("DEBUG", True) and app.config.get("LDAP_HOST", False) and app.config.get("LDAP_PATH", False):
        from pystil.ldap_ import auth_route

        route = auth_route(app)
    else:
        route = app.route

    init_events(app)
    register_data_routes(app, route)
    register_common_routes(app, route)
    register_admin_routes(app, route)
    return app
Example #29
0
def get_app(database_uri, exclude_tables=None, user_models=None, reflect_all=True):
    """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
    """
    app = Flask("sandman2")
    app.config["SQLALCHEMY_DATABASE_URI"] = database_uri
    db.init_app(app)
    admin = Admin(app, base_template="layout.html")
    _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)
    return app
Example #30
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