예제 #1
0
def create_app():
    # create flask app
    app = Flask(__name__)
    app.config.from_envvar("CONFIG")
    # allow any origin for testing and development environments
    if app.config["TESTING"] or app.config["DEVELOPMENT"]:
        CORS(app)

    # configure logger
    logging.basicConfig(
        format="%(asctime)s %(levelname)s [%(module)s %(lineno)d] %(message)s",
        level=app.config['LOG_LEVEL'])

    # init sqlalchemy db connection
    db.init_app(app)

    # create and init socket server with request handler
    request_handler = RequestHandler()
    sio = create_sio(request_handler)
    sio.init_app(app)

    # init scheduler in case if it's not a testing environment
    if not app.config["TESTING"]:
        SchedulerManager(app, sio)

    app.register_blueprint(auth, url_prefix='/auth')
    app.register_blueprint(data, url_prefix='/data')

    return sio, app
예제 #2
0
def create_app():
    new_app = GwapApp(__name__, static_folder=None)
    GWAAppConfig(new_app)
    GwapErrorHandlerConfig(new_app)
    # ElasticAPM(new_app, logging=True)
    CORS(new_app)
    db.init_app(new_app)

    api = GwapApi(new_app, prefix=f"/gwap/{GWA_KEY}")
    api.add_resource(HealthCheckResource, '/')

    # version 1
    bp_v1 = Blueprint('v1', __name__, url_prefix=f"/gwap/{GWA_KEY}/v1")
    GwapAuth(bp_v1, new_app.logger)
    GwapErrorHandlerConfig(bp_v1)
    api_v1 = GwapApi(bp_v1)
    new_app.register_blueprint(bp_v1)

    for resource_v1 in resources_v1:
        api_v1.add_resource(resource_v1['resource'],
                            *resource_v1['urls'],
                            endpoint=resource_v1['endpoint'],
                            methods=resource_v1['methods'])

    return new_app
예제 #3
0
def initialize_app():
    blueprint = Blueprint('api', __name__, url_prefix=settings.url_prefix)
    api.init_app(blueprint)
    api.add_namespace(geonames_namespace)
    app.register_blueprint(blueprint)

    db.init_app(app)
예제 #4
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='dev', )

    if test_config is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.from_mapping(test_config)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    routes = [client_api]
    for route in routes:
        app.register_blueprint(route.get_blueprint())

    @app.route('/')
    def index():
        return '<div><strong>SuervreuS</strong><br><p>An IoT command processing service</p></div>'

    db.init_app(app)

    return app
예제 #5
0
    def test_create_relationship(self):
        with self.app.app_context():
            from src.database.db import get_db, init_app, distroy_db
            from src.models.survey_model import Survey, SurveyVersion
            
            distroy_db(self.app)
            init_app(self.app)

            current_transaction = get_db().transaction
            with current_transaction:
                test_Survey_1 = Survey(
                    slug="test_survey_1",
                    language="en"
                )
                test_SurveyVersion_1 = SurveyVersion(
                    title="Test Survey 1"
                )
                test_Survey_1.save()
                test_SurveyVersion_1.save()
                rel = test_Survey_1.versions.connect(test_SurveyVersion_1)

            assert len(test_SurveyVersion_1.survey.all()) == 1
            
            pytest.test_Survey_SurveyVersion_rel_1 = rel
            pytest.test_Survey_1 = test_Survey_1
            pytest.test_SurveyVersion_1 = test_SurveyVersion_1
예제 #6
0
def create_app():
    new_app = GwapApp(__name__, static_folder=None)
    GWAAppConfig(new_app)
    # ElasticAPM(new_app, logging=True)
    GwapAuth(new_app)
    CORS(new_app)
    db.init_app(new_app)
    return new_app
예제 #7
0
 def init_db_command():
     """Initialize the database. """
     db.init_app(app)
     # need to trigger SQLite to turn on foreign key support
     connection = DB_ENGINE.connect()
     connection.close()
     db.create_all()
     app.logger.info("Database initialized")
예제 #8
0
def create_minimal_app():
    app = Flask(__name__)
    app.config.from_envvar("CONFIG")
    logging.basicConfig(
        format="%(asctime)s %(levelname)s [%(module)s %(lineno)d] %(message)s",
        level=app.config['LOG_LEVEL'])
    db.init_app(app)
    return app
예제 #9
0
def create_app(env: str = "dev") -> Flask:
    app = Flask(__name__)
    app.config.from_object(config[env])
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False  # warning 뜨는 것
    db.init_app(app)
    init_blueprint(app)
    init_extenstion(app)
    migrate.init_app(app, db)
    return app
예제 #10
0
파일: app.py 프로젝트: A-Kuper/rest_api_2
def create_app():
    app = Flask(__name__)
    app.register_blueprint(ads_bp)
    app.config.from_object('config.Config')
    app.register_blueprint(auth_bp, url_prefix='/auth')
    app.register_blueprint(users_bp, url_prefix='/users')
    app.register_blueprint(colors_bp, url_prefix='/colors')
    app.register_blueprint(cities_bp, url_prefix='/cities')
    app.register_blueprint(images_bp, url_prefix='/images')
    db.init_app(app)
    return app
예제 #11
0
def initialize_app(flask_app):
    flask_app.config.from_object(Config)
    blueprint = Blueprint("swagger_ui", __name__, url_prefix="")

    api.init_app(blueprint)
    api.add_namespace(resources_namespace)
    api.add_namespace(bookings_namespace)
    api.add_namespace(users_namespace)
    api.add_namespace(slots_namespace)
    flask_app.register_blueprint(blueprint)
    register_cli_commands(flask_app)
    db.init_app(flask_app)
예제 #12
0
파일: app.py 프로젝트: cjeustis/bev-web-api
def initialize_app(flask_app):
    configure_app(flask_app)
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)

    # Add endpoint namespaces here so we can navigate to them in a browser
    api.add_namespace(users_namespace)
    # api.add_namespace(recipes_namespace)

    flask_app.register_blueprint(blueprint)
    db.init_app(flask_app)
    with app.app_context():
        db.create_all()
예제 #13
0
def test_db(test_app):
    engine = create_engine('postgresql://localhost/' + TEST_DB)

    if not database_exists(engine.url):
        create_database(engine.url)

    with test_app.app_context():

        db.init_app(test_app)
        db.create_all()

        yield db

    db.drop_all()
def initialize_app(flask_app):
    configure_app(flask_app)

    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)
    api.add_namespace(service_accounts_namespace)
    api.add_namespace(service_channels_namespace)
    api.add_namespace(service_ccs_namespace)
    api.add_namespace(service_settlement_namespace)
    api.add_namespace(service_withdraw_namespace)
    api.add_namespace(service_maintenance_namespace)

    flask_app.register_blueprint(blueprint)

    db.init_app(flask_app)
예제 #15
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)
    if test_config is None:
        app.config.from_mapping(
            SECRET_KEY='dev',
            SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI'),
            SQLALCHEMY_TRACK_MODIFICATIONS=False,
            JWT_SECRET_KEY=os.environ.get('JWT_SECRET_KEY'),
            SWAGGER={
                'title': 'Bookmarks API',
                'uiversion': 3,
            })
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    JWTManager(app)
    CORS(app)

    db.app = app
    db.init_app(app)

    Swagger(app, config=swagger_config, template=template)

    app.register_blueprint(bookmarks)
    app.register_blueprint(auth)

    @app.route('/<short_url>')
    @swag_from('./docs/bookmarks/redirect.yml')
    def redirect_to_url(short_url):
        link = Bookmark.query.filter_by(short_url=short_url).first_or_404()
        link.visits = link.visits + 1
        db.session.commit()
        return redirect(link.url)

    @app.errorhandler(404)
    def page_not_found(e):
        return jsonify({"Error": 'not found'}), HTTP_404_NOT_FOUND

    @app.errorhandler(500)
    def page_not_found(e):
        return jsonify({"Error": 'Issue on server occurred'
                        }), HTTP_500_INTERNAL_SERVER_ERROR

    return app
예제 #16
0
파일: __init__.py 프로젝트: mm/wswp
def create_app(config='src.config.DevConfig'):
    """Main application factory for WSWP. Will set up all config params,
    load up environment variables and bind things as needed (i.e. binding
    the app object to SQLAlchemy)

    Returns an application object.
    """

    # Our config classes make use of environment variables, so load
    # those first:
    if find_dotenv():
        load_dotenv()

    app = Flask(__name__)
    app.config.from_object(config)

    if app.config['ADMIN_OFF']:
        app.logger.info("Note: admin endpoints have been disabled!")

    # Configure Sentry logging. The DSN is read from the SENTRY_DSN
    # env variable, and the environment is read from the
    # SENTRY_ENVIRONMENT variable
    if config != 'src.config.TestConfig':
        # We don't want to initialize Sentry in testing -- it'd kill the logs
        sentry_sdk.init(integrations=[FlaskIntegration()],
                        traces_sample_rate=0.5)

    from src.database import db
    from src.schema import ma
    db.init_app(app)
    from src.model import Activity, Submission
    migrate = Migrate(app, db)
    ma.init_app(app)

    # Register cross-origin resource sharing and rate limiting modules:
    cors.init_app(app)
    limiter.init_app(app)

    # Associate all handlers of the Flask logger instance:
    for handler in app.logger.handlers:
        limiter.logger.addHandler(handler)

    app.register_blueprint(api, url_prefix='/v1')
    app.register_blueprint(cli_bp)

    return app
예제 #17
0
def create_app():

    app = Flask(__name__)

    # CORS対応
    CORS(app)

    # DB設定を読み込む
    app.config.from_object('config.Config')
    db.init_app(app)

    app.register_blueprint(weapon_router, url_prefix='/api')
    app.register_blueprint(skill_router, url_prefix='/api')
    app.register_blueprint(effect_router, url_prefix='/api')
    app.register_blueprint(category_router, url_prefix='/api')
    app.register_blueprint(power_router, url_prefix='/api')
    app.register_blueprint(weapon_type_router, url_prefix='/api')
    app.register_blueprint(impact_router, url_prefix='/api')
    app.register_blueprint(rarity_router, url_prefix='/api')
    app.register_blueprint(calculation_router, url_prefix='/api')
    app.register_blueprint(phantom_router, url_prefix='/api')
    return app
예제 #18
0
def init_db(app):
    db.init_app(app)
예제 #19
0
 def drop_db_command():
     """Drop the database. """
     db.init_app(app)
     db.drop_all()
     app.logger.info("Database dropped")
예제 #20
0
def create_app(mode="production",
               static_path="./static",
               templates_path="./templates",
               instance_path="./instance") -> Flask:
    import os
    from .utils.verify_user_constraints import verify
    from warnings import warn
    from werkzeug.utils import ImportStringError
    app = Flask(__name__)
    CORS(app)
    # configuring application
    app.config.from_object("configs.default_settings")

    if mode == "development":
        app.config.from_object("configs.development_settings")
    else:
        if mode != "production":
            warn("FLASK_ENV was set as an unrecognized value, " +
                 "application is falling back on production mode")
        try:
            app.config.from_object("configs.production_settings")
        except ImportStringError:
            pass

    # call in the verify function to validate application configuration
    verify(app)

    # If the secret key is none or the mode is production then we need to get the secret key from an environment variable
    if app.config.get('SECRET_KEY') is None or mode == "production":
        if os.environ.get("APP_SECRET_KEY") is None:
            if mode == "production":
                raise ValueError(
                    "APP_SECRET_KEY must be set as an environment " +
                    "variable for production environments")
            else:
                raise ValueError(
                    "SECRET_KEY was not set in the settings thus must be " +
                    "provided in the APP_SECRET_KEY environment variable")
        app.config['SECRET_KEY'] = os.environ['APP_SECRET_KEY']
    # if the environment variable is not none we overide any configuration
    elif os.environ.get('APP_SECRET_KEY') is not None:
        app.config['SECRET_KEY'] = os.environ['APP_SECRET_KEY']

    # for database uri if there is a database
    """
    if app.config.get("DATABASE_URI") is None or mode == "production":
        if os.environ.get('APP_DATABASE_URI') is None:
            if mode == "production":
                raise ValueError(
                    "APP_DATABASE_URI must be set as an " +
                    "environment variable for production environments")
            else:
                raise ValueError(
                    "DATABASE_URI was not set in the settings " +
                    "thus must be provided in the " +
                    "APP_DATABASE_URI environment variable")

        app.config['DATABASE_URI'] = os.environ['APP_DATABASE_URI']
    elif os.environ.get("APP_DATABASE_URI") is not None:
        app.config['DATABASE_URI'] = os.environ['APP_DATABASE_URI']
    """

    # getting the absolute value for the static_path, template_path and instance_path
    if not os.path.isabs(static_path):
        static_path = os.path.abspath(static_path)
    if not os.path.isdir(static_path):
        raise FileNotFoundError(
            f'static folder was not able to be found {static_path}'
        )

    app.static_folder = static_path

    if not os.path.isabs(templates_path):
        templates_path = os.path.abspath(templates_path)
    if not os.path.isdir(templates_path):
        raise FileNotFoundError('templates folder was not able to be found')

    app.template_folder = templates_path

    if not os.path.isabs(instance_path):
        instance_path = os.path.abspath(instance_path)
    if not os.path.isdir(instance_path):
        os.mkdir(instance_path)

    app.instance_path = instance_path
    
    from src.database.db import init_app, distroy_db, init_db
    # initialise the app-database configurations
     
    init_app(app)

    from src.api import register_api_routes
    
    # register the api routes
    register_api_routes(app)

    from src.views import register_view_routes

    # register the view routes
    register_view_routes(app)
    
    # you can register some cli commands to be used with the flask command
    """
    @app.cli.command("init-db")
    def initialise_database():
        init_db(app)

    @app.cli.command("teardown-db")
    def distroy_database():
        distroy_db(app)
    """
    return app
예제 #21
0
#!/usr/bin/python3

import os
import json
from flask import Flask
from config import Config
from src.database import db
from src.database import Board, Post

fake_app = Flask(__name__)
fake_app.config.update(Config.FLASK_CONFIG)
db.init_app(fake_app)

with fake_app.app_context():
    db.drop_all()
    db.create_all()

    board_data = None
    with open(os.path.join(Config.PROJECT_ROOT_DIR, 'board-list.json'), "r") as f:
        board_data = json.loads(f.read())

    for board in board_data:
        new_board = Board(
            title=board.get("title"),
            short=board.get("short")
        )
        db.session.add(new_board)
    db.session.commit()

    genesis_post = Post(
        head="GENESIS_POST",
예제 #22
0
파일: app.py 프로젝트: x0rzkov/fitcrack
                400))

    publicEndpoint = getattr(app.view_functions[request.endpoint].view_class,
                             'is_public', False)
    if not publicEndpoint and request.method != 'OPTIONS':
        login_valid = current_user.is_authenticated
        if not login_valid:
            abort(401)
    return


@app.after_request
def bake_cookies(response):
    "just a workaround"
    if (response.headers.get('Set-Cookie')):
        response.headers['Set-Cookie'] += '; SameSite=Lax'
    return response


def main():
    app.run(host='0.0.0.0', port=5000, threaded=False)


initialize_app(app)
login_manager.init_app(app)

db.init_app(app)

if __name__ == "__main__":
    main()
예제 #23
0
def create_app(mode="production",
               static_path="./static",
               templates_path="./templates",
               instance_path="./instance") -> Flask:
    import os
    # from .utils.celery_maker import make_celery
    # from .utils.fileChecker import fileChecker
    from .utils.verify_user_constrains import verify
    from src.database.db import init_app, distroy_db, init_db
    from warnings import warn
    from werkzeug.utils import ImportStringError
    app = Flask(__name__)
    # configuring application
    app.config.from_object("configs.default_settings")

    if mode == "development":
        app.config.from_object("configs.development_settings")
    else:
        if mode != "production":
            warn("FLASK_ENV was set as an unrecognized value, " +
                 "application is falling back on production mode")
        try:
            app.config.from_object("configs.production_settings")
        except ImportStringError:
            pass

    # call in the verify function to validate application configuration
    verify(app)

    # if the secret key is none or the mode is production
    # we want to get the secret key from the environment variable
    if app.config.get('SECRET_KEY') is None \
            or mode == "production":
        if os.environ.get("SURVISTA_SECRET_KEY") is None:
            if mode == "production":
                raise ValueError(
                    "SURVISTA_SECRET_KEY must be set as an environment " +
                    "variable for production environments")
            else:
                raise ValueError(
                    "SECRET_KEY was not set in the settings thus must be " +
                    "provided in the SURVISTA_SECRET_KEY environment variable")
        app.config['SECRET_KEY'] = os.environ['SURVISTA_SECRET_KEY']
    elif os.environ.get('SURVISTA_SECRET_KEY') is not None:
        app.config['SECRET_KEY'] = os.environ['SURVISTA_SECRET_KEY']

    if app.config.get("NEOMODEL_DATABASE_URI") is None \
            or mode == "production":
        if os.environ.get('SURVISTA_NEOMODEL_DATABASE_URI') is None:
            if mode == "production":
                raise ValueError(
                    "SURVISTA_NEOMODEL_DATABASE_URI must be set as an " +
                    "environment variable for production environments")
            else:
                raise ValueError(
                    "NEOMODEL_DATABASE_URI was not set in the settings " +
                    "thus must be provided in the " +
                    "SURIVISTA_NEOMODEL_DATABASE_URI environment variable")

        app.config['NEOMODEL_DATABASE_URI'] = \
            os.environ['SURVISTA_NEOMODEL_DATABASE_URI']
    elif os.environ.get("SURVISTA_NEOMODEL_DATABASE_URI") is not None:
        app.config['NEOMODEL_DATABASE_URI'] = \
            os.environ['SURVISTA_NEOMODEL_DATABASE_URI']

    if not os.path.isabs(static_path):
        static_path = os.path.abspath(static_path)
    if not os.path.isdir(static_path):
        raise FileNotFoundError(
            f'static folder was not able to be found {static_path}')

    app.static_folder = static_path

    if not os.path.isabs(templates_path):
        templates_path = os.path.abspath(templates_path)
    if not os.path.isdir(templates_path):
        raise FileNotFoundError('templates folder was not able to be found')

    app.template_folder = templates_path

    if not os.path.isabs(instance_path):
        instance_path = os.path.abspath(instance_path)
    if not os.path.isdir(instance_path):
        os.mkdir(instance_path)

    app.instance_path = instance_path

    init_app(app)

    @app.cli.command("init-db")
    def initialise_database():
        init_db(app)

    @app.cli.command("teardown-db")
    def distroy_database():
        distroy_db(app)

    # Celery configuration area
    return app