Esempio n. 1
0
def create_app(env):
    """Flask application factory"""

    # initialization the application
    app = Flask(__name__)
    app.config.from_object(app_config[env])

    # binding the database and migrate to the flask app instance
    db.init_app(app)
    migrate.init_app(app, db)

    # Models
    import database.models

    # Views
    app.add_url_rule(
        '/graphql',
        view_func=GraphQLView.as_view(
            'graphql',
            schema=schemas.schema,
            graphiql=True  # for having the GraphiQL interface
        ))

    # root route
    @app.route('/', methods=['GET'])
    def index():
        """Index route for the API"""
        return jsonify(status='Healthy', )

    # return because of test.
    return app
Esempio n. 2
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('settings')
    db.init_app(app)
    migrate.init_app(app, db)

    return app
Esempio n. 3
0
def create_app():
    app = Flask(__name__)
    app.config.from_object('settings')
    db.init_app(app)
    migrate.init_app(app, db)
    _register_blueprint(app)
    _register_error_handler(app)
    return app
Esempio n. 4
0
def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///simple_api.db"
    db.init_app(app)
    migrate.init_app(app)
    db.create_all(app=app)
    _register_blueprint(app)
    return app
Esempio n. 5
0
def create_app():
	app = Flask(__name__)
	app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/user_management.db'
	db.init_app(app)
	db.app = app
	from models import User, Group
	db.create_all()
	migrate.init_app(app,db)
	return app
Esempio n. 6
0
def create_app():
    app = Flask(__name__)
    CORS(app, resource={r"*": {"origins": "*"}})
    _register_blueprint(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    migrate.init_app(app, db)
    _register_blueprint(app)
    return app
Esempio n. 7
0
def create_app():
    app = Flask(__name__)
    _register_blueprint(app)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    migrate.init_app(app, db)
    _register_blueprint(app)
    _register_error_handler(app)
    return app
Esempio n. 8
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(os.environ['APP_SETTINGS'])
    app.config['SQLALCHEMY_DATABASE_URI']=app.config['DATABASE_URI'].replace("s://", "sql://", 1)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    bcrypt.init_app(app)
    jwt.init_app(app)
    CORS(app)
    migrate.init_app(app, db)# this exposes some new flask terminal commands to us!
    return app
Esempio n. 9
0
def create_app():
    app = Flask(__name__)

    app.config.from_object('settings')
    db.init_app(app)
    migrate.init_app(app, db)

    _register_blueprints(app)

    app.register_error_handler(HTTPException, _handle_default_exception)

    return app
Esempio n. 10
0
def register_extensions(app):
    with app.app_context():
        """Logs"""
        logger.init_app(app)
        metrics.init_app(app)
        """ORM"""
        db.init_app(app)
        db.create_all()
        migrate.init_app(app, db)
        from database import image_model

        MetricsRegister.register_defaults()
        """Cache"""
        Cache()
Esempio n. 11
0
def create_app(script_info=None):
    # Instantiate the app
    app = Flask(__name__)
    CORS(app,
         supports_credentials=True,
         resources={r"/api/*": {
             "origins": "*"
         }})  # Set Configuration
    app_settings = os.getenv('APP_SETTINGS')
    app.config.from_object(app_settings)

    db.init_app(app)
    with app.app_context():
        db.create_all()
    migrate.init_app(app, db)
    bcrypt.init_app(app)

    # register blueprints
    app.register_blueprint(users_blueprint)
    app.register_blueprint(cars_blueprint)
    app.register_blueprint(rides_blueprint)

    return app
Esempio n. 12
0

static_url_path = '/static'
app = Flask(__name__, static_url_path=static_url_path)


for extension in [ext.JinjaStatic, ext.JinjaUrl]:
    # pylint: disable=no-member
    app.jinja_env.add_extension(extension)
print(app.env)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = 'development' == app.env
app.secret_key = os.getenv('SECRET_KEY')

db.init_app(app)
migrate.init_app(app)
login_manager.init_app(app)

seeder = FlaskSeeder()
seeder.init_app(app, db)

app.register_blueprint(homePageBp)
app.register_blueprint(competenceBp)
app.register_blueprint(trainingBp)
app.register_blueprint(authenticationBp)
app.register_blueprint(trackBp)


@app.template_filter('date_format')
def filter_datetime(value: datetime, fmt="%Y:%M:%d"):
    return value.strftime(fmt)
Esempio n. 13
0
def init_app(app):
    db.init_app(app)
    migrate.init_app(app, db)
    api.init_app(app)
Esempio n. 14
0
from exceptions import HTTPException, JSONException, errohandler

from flask import Flask

from api.endpoints import api
from apps.user.views import user_blueprint
from apps.views import main_blueprint
from database import db, migrate
from settings import Config
from utils import bcrypt, jwt

app = Flask(__name__)
"""General app config"""
app.config.from_object(Config)
app.url_map.strict_slashes = False
"""Third party configuration"""
db.init_app(app)
api.init_app(app)
migrate.init_app(app, db)
bcrypt.init_app(app)
jwt.init_app(app)
"""Blueprint registration"""
app.register_blueprint(main_blueprint)
app.register_blueprint(user_blueprint)
"""Error handler"""
app.errorhandler(HTTPException)(errohandler)
app.errorhandler(JSONException)(errohandler)
Esempio n. 15
0
def create_app(config: Optional[TmvConfig] = None,
               config_override: Optional[Dict] = None):
    if config is None:
        config = create_tmv_config_from_env()

    if config_override is None:
        config_override = {}
    """ Set up logging
        Logging uses the built-in logging-module, see the Python docs for details.
        If you want to log something, please use one of the following methods,
        depending on the level you want to log.
        logging.debug()
        logging.info()
        logging.warning()
        logging.error()
        logging.critical()

        You can configure from which level log messages get output by modifying
        the parameter `level` in the lines below.

        You can add further handlers (for example for sending e-mails on critical
        errors) to the logging system if you want. Make sure to always log using
        an appropriate level to not clutter the logs with meaningless messages.
    """
    log_level = logging.DEBUG if config.DEV_MODE else logging.WARNING

    logging.basicConfig(
        format="[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
        level=log_level,
        handlers=[logging.StreamHandler()],
    )

    logging.info("Dev mode is " + ("on" if config.DEV_MODE else "off") + ".")

    # Initialize flask app
    app = flask.Flask(
        __name__,
        template_folder=str(BASE_DIR / "tmv" / "templates"),
    )

    app.url_map.strict_slashes = False

    app.config.from_mapping(
        SECRET_KEY=config.SECRET_KEY,
        SQLALCHEMY_DATABASE_URI=config.SQLALCHEMY_DATABASE_URI,
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        TEMP_UPLOADS_FOLDER=str(BASE_DIR / config.TEMP_UPLOADS_FOLDER),
        SECURITY_PASSWORD_SALT=config.SECURITY_PASSWORD_SALT,
        SECURITY_REGISTERABLE=config.SECURITY_REGISTERABLE,
        SECURITY_SEND_REGISTER_EMAIL=False,  # TODO: requires mail setup
        SECURITY_USER_IDENTITY_ATTRIBUTES=["email"],
        SECURITY_PASSWORD_HASH="pbkdf2_sha512",
        SECURITY_TRACKABLE=True,
        SECURITY_FORGOT_PASSWORD_TEMPLATE=
        "security/custom_forgot_password.html",
        SECURITY_LOGIN_USER_TEMPLATE="security/custom_login_user.html",
        SECURITY_REGISTER_USER_TEMPLATE="security/custom_register_user.html",
        SECURITY_RESET_PASSWORD_TEMPLATE="security/custom_reset_password.html",
        SECURITY_CHANGE_PASSWORD_TEMPLATE=
        "security/custom_change_password.html",
        SECURITY_SEND_CONFIRMATION_TEMPLATE=
        "security/custom_send_confirmation.html",
        SECURITY_SEND_LOGIN_TEMPLATE="security/custom_send_login.html",
        OKTA_ORG_BASEURL=config.OKTA_ORG_BASEURL,
        OKTA_CLIENT_ID=config.OKTA_CLIENT_ID,
        OKTA_CLIENT_SECRET=config.OKTA_CLIENT_SECRET,
        AWS_REGION=config.AWS_REGION,
        JIRA_OAUTH_LOC=config.JIRA_OAUTH_LOC,
        JIRA_SERVER=config.JIRA_SERVER,
        JIRA_CONSUMER_KEY=config.JIRA_CONSUMER_KEY,
        JIRA_CONSUMER_SECRET=config.JIRA_CONSUMER_SECRET,
        JIRA_ACCESS_TOKEN=config.JIRA_ACCESS_TOKEN,
        JIRA_ACCESS_SEC=config.JIRA_ACCESS_SEC,
        JIRA_RSA_PEM=config.JIRA_RSA_PEM,
        JIRA_FIELD_SPRINT=config.JIRA_FIELD_SPRINT,
        JIRA_FIELD_STORYPOINTS=config.JIRA_FIELD_STORYPOINTS,
        FLASK_ADMIN_SWATCH="simplex",
        CELERY_BROKER_URL=config.CELERY_BROKER_URL,
        CELERY_RESULT_BACKEND=config.CELERY_RESULT_BACKEND,
    )
    app.config.update(config_override)

    db.init_app(app)
    migrate.init_app(app, db, directory=str(BASE_DIR / "./tmv/migrations/"))

    app.security = Security(app,
                            user_datastore,
                            anonymous_user=CustomAnonymousUser)

    app.oauth = OAuth(app)
    if config.OKTA_ORG_BASEURL:
        app.oauth.register(
            "okta",
            server_metadata_url=(
                config.OKTA_ORG_BASEURL +
                "/oauth2/default/.well-known/openid-configuration"),
            client_kwargs={"scope": "openid profile email"},
        )

    # Create directories if they not already exist.
    FOLDERS_TO_CREATE = {
        app.config["TEMP_UPLOADS_FOLDER"],
    }
    for folder in FOLDERS_TO_CREATE:
        os.makedirs(folder, exist_ok=True)

    # Register flask pages
    # Add your page here by creating a blueprint in /views, importing it and
    #   registering it via `app.register_blueprint`.
    admin.init_app(app)
    app.register_blueprint(user)

    dash_app = dash.Dash(
        __name__,
        server=app,
        # The route to put dash in:
        routes_pathname_prefix=DASHBOARD_PREFIX,
        external_stylesheets=[
            ("https://fonts.googleapis.com/css2?"
             "family=Roboto:wght@300;400;500;700&display=swap"),
        ],
        assets_folder="static/dash",
        assets_url_path="/static/dash",
        suppress_callback_exceptions=True,
        meta_tags=[{
            "name": "viewport",
            "content": "width=device-width, initial-scale=1"
        }],
    )
    dash_app.title = "Team Metrics Visualizer"

    DashFlaskSecurityAuth(dash_app)

    if config.DEV_MODE:
        dash_app.enable_dev_tools()

    # Initialize dashboards.
    # Add your dashboard here by creating an instance and adding it to TABS
    dashboards = [
        TeamHealthCheckDashboardController(),
        LongTermHealthDashboardController(),
        BurnupDashboardController(),
        CumulativeFlowDashboardController(),
        WorktimeDashboardController(),
    ]

    def layout_fn(*args, **kwargs):
        if flask.has_app_context() and flask.has_request_context():
            dash_app._cached_layout = None  # pylint: disable=protected-access
            return layout(dashboards, DASHBOARD_PREFIX)

    dash_app.layout = layout_fn
    init_tabs_for_navbar(dash_app, dashboards, DASHBOARD_PREFIX)

    register_common_callbacks(dash_app)

    return app