Exemple #1
0
def create_app():

    app = Flask(__name__,
                static_folder='./frontend/dist/static',
                template_folder='./frontend/dist')
    app.register_blueprint(api_blueprint, url_prefix='/api')

    app.config.from_object('backend.config.Config')
    db.init_app(app)
    ma.init_app(app)

    return app
Exemple #2
0
def create_app():
    app = Flask(__name__)
    DB_PATH = os.environ.get('DB_PATH', '/home/david/tanya.db')
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_PATH}'
    db.init_app(app)

    api = Api(app)
    api.add_resource(Payload, '/')
    api.add_resource(CSVExport, '/csv')

    if not Path(DB_PATH).exists():
        with app.app_context():
            db.create_all()
    return app
Exemple #3
0
def create_app(test_config=None):
    """
    Creates the application and register all resources to it.

    :param test_config: optional config for Flask for testing purposes, default is None
    :return: Created application
    """
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        ROOT_DIR=os.path.join(app.root_path, '../'),
        TEST_UPLOAD_FOLDER=os.path.join(app.root_path, "../tests/test_files"),
        SECRET_KEY=os.urandom(24),
        DATABASE=os.path.join(app.instance_path, 'backend.sqlite'),
        UPLOAD_FOLDER=os.path.join(app.root_path, '../files'),
        MAX_CONTETN_LENGTH=5 * 1024 * 1024,
        ALLOWED_EXTENSIONS={'png', 'jpeg', 'jpg', 'gif', 'bmp'},
        CORS_ORIGINS=["https://spenderschlender.3ef.de/", "http://localhost"]
    )
    CORS(app, resources={r"/api/*": {"origins": app.config['CORS_ORIGINS']}})

    if test_config is None:
        app.config.from_pyfile('config.py', silent=True)  # load the instance config if exists
    else:
        app.config.from_mapping(test_config)  # load test config

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

    db.init_app(app)

    cfg_parser: configparser.ConfigParser = configparser.ConfigParser()
    cfg_parser.read("backend_config.ini")
    if "Sentry" in cfg_parser.sections():
        sentry_sdk.init(
            cfg_parser["Sentry"]["URI"],
            integrations=[FlaskIntegration(), SqlalchemyIntegration()]
        )

    Path(app.config['UPLOAD_FOLDER']).mkdir(parents=True, exist_ok=True)

    for blueprint in BLUEPRINTS:
        app.register_blueprint(blueprint)

    return app
Exemple #4
0
def create_app(config_object: object = None) -> Flask:
    app = Flask(__name__,
                static_folder=static_dir,
                template_folder=template_dir)

    if not config_object:
        logging.warn('No configuration specified, defaulting to basic config')
        app.config.from_object(BasicConfig)

    # Register all routes and setup CORS
    app.register_blueprint(basic_routes)
    CORS(app)

    # Initialize db
    db.init_app(app)
    db.app = app

    return app
Exemple #5
0
def create_app(test_config=None):
    """
    Creates the application and register all resources to it.

    :param test_config: optional config for Flask for testing purposes, default is None
    :return: Created application
    """
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY=os.urandom(24),
        DATABASE=os.path.join(app.instance_path, 'backend.sqlite'),
        UPLOAD_FOLDER=os.path.join(app.root_path, '../files'),
        MAX_CONTETN_LENGTH=5 * 1024 * 1024,
        ALLOWED_EXTENSIONS={'png', 'jpeg', 'jpg', 'gif', 'bmp'})
    CORS(app)
    # ToDo: for production add real cors-options

    if test_config is None:
        app.config.from_pyfile(
            'config.py', silent=True)  # load the instance config if exists
    else:
        app.config.from_mapping(test_config)  # load test config

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

    db.init_app(app)

    Path(app.config['UPLOAD_FOLDER']).mkdir(parents=True, exist_ok=True)

    for blueprint in BLUEPRINTS:
        app.register_blueprint(blueprint)

    return app
Exemple #6
0
def create_app(config_class=Config):
    app = Flask(__name__, static_folder='../frontend/dist/static', template_folder='../frontend/dist')
    app.url_map.strict_slashes = False
    app.config.from_object(config_class)

    api_bp = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(api_bp)
    api.add_namespace(maintenance_namespace)
    api.add_namespace(history_namespace)
    api.add_namespace(bike_namespace)
    api.add_namespace(training_namespace)
    api.add_namespace(setup_namespace)
    api.add_namespace(coach_namespace)
    api.add_namespace(email_namespace)
    api.add_namespace(session_namespace)
    api.add_namespace(laptime_namespace)
    api.add_namespace(sparepart_namespace)
    api.add_namespace(sparepartitem_namespace)
    api.add_namespace(tire_namespace)

    app.register_blueprint(api_bp)
    app.register_blueprint(index_bp)
    app.register_blueprint(favicon_bp)
    app.register_blueprint(assets_bp)

    db.init_app(app)
    ma.init_app(app)
    migrate.init_app(app, db)

    CORS(app)

    app.cli.add_command(create_tables)
    app.cli.add_command(drop_tables)
    app.cli.add_command(clear_tables)

    return app
Exemple #7
0
def create_app():
    from flask import Flask
    from config import SECRET_KEY, DB_URI, RABBIT_URL, UPLOAD_DIR
    log("app.py:CreateApp", "Started..")
    app = Flask(__name__)
    app.config['DEBUG'] = True
    app.config['USE_RELOADER'] = False
    app.config['SQLALCHEMY_DATABASE_URI'] = DB_URI
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SECRET_KEY'] = SECRET_KEY

    # Even though we don't set a remember_me cookie, if anyone figured out how to create one it'd be bad news. We need
    # to make sure we won't accept a remember me cookie, so we set the name of the cookie we're looking for to
    # something random at startup. Probably a better way to do this, but this works for now.
    app.config['REMEMBER_COOKIE_NAME'] = secrets.token_urlsafe(64)

    log("app.py:CreateApp", "Initializing DB..")
    from backend.database import db
    db.init_app(app)

    log("app.py:CreateApp", "Creating API..")
    from flask_restful import Api
    api = Api(prefix='/api/v1')

    # REST imports
    from apis.rest.agent import AgentEndpoint
    from apis.rest.agent_commands import AgentCommandEndpoint
    from apis.rest.agent_checkin import AgentCheckinEndpoint
    from apis.rest.agent_task import AgentTaskEndpoint
    from apis.rest.agent_type import AgentTypeEndpoint
    from apis.rest.console import ConsoleAgentEndpoint, ConsoleTaskEndpoint
    from apis.rest.error_message import ErrorMessageEndpoint
    from apis.rest.faction_file import FactionFileEndpoint, FactionFileDownloadEndpoint, FactionFileBytesEndpoint
    from apis.rest.ioc import IOCEndpoint
    from apis.rest.payload import PayloadEndpoint, PayloadFileEndpoint
    from apis.rest.staging import StagingEndpoint
    from apis.rest.transport import TransportEndpoint
    from apis.rest.user import LoginEndpoint, ChangePasswordEndpoint, ApiKeyEndpoint, UserEndpoint, \
        UserRoleEndpoint

    # Agent REST endpoints
    log("app.py:CreateApp", "Registering Endpoints..")
    api.add_resource(AgentEndpoint, '/agent/', '/agent/<int:agent_id>/')
    api.add_resource(AgentCheckinEndpoint,
                     '/agent/<string:agent_name>/checkin/')
    api.add_resource(AgentTypeEndpoint, '/agent/type/',
                     '/agent/type/<int:agent_type_id>/')
    api.add_resource(ConsoleAgentEndpoint, '/agent/<int:agent_id>/console/')
    api.add_resource(AgentCommandEndpoint, '/agent/<int:agent_id>/commands/')

    # User REST endpoints
    api.add_resource(LoginEndpoint, '/login/')
    api.add_resource(UserEndpoint, '/user/', '/user/<int:user_id>/')
    api.add_resource(ChangePasswordEndpoint, '/user/<int:user_id>/password/')
    api.add_resource(ApiKeyEndpoint, '/user/<int:user_id>/apikey/',
                     '/user/<int:user_id>/apikey/<int:api_key_id>/')
    api.add_resource(UserRoleEndpoint, '/user/role/',
                     '/user/role/<int:user_role_id>/')

    # Task REST endpoints
    api.add_resource(AgentTaskEndpoint, '/task/', '/task/<int:agent_task_id>/')
    api.add_resource(ConsoleTaskEndpoint, '/task/<int:agent_task_id>/console/')

    # Faction FIle Endpoint
    api.add_resource(FactionFileEndpoint, '/file/',
                     '/file/<string:faction_file_name>')
    api.add_resource(FactionFileDownloadEndpoint,
                     '/file/<string:faction_file_name>/download/')
    api.add_resource(FactionFileBytesEndpoint,
                     '/file/<string:faction_file_name>/bytes/')

    # Misc REST endpoints
    api.add_resource(ErrorMessageEndpoint, '/errors/',
                     '/errors/<int:error_message_id>')
    api.add_resource(IOCEndpoint, '/ioc/', '/ioc/<int:ioc_id>/')
    api.add_resource(PayloadEndpoint, '/payload/',
                     '/payload/<int:staging_config_id>/')
    api.add_resource(PayloadFileEndpoint, '/payload/<int:payload_id>/file/')
    api.add_resource(StagingEndpoint, '/staging/',
                     '/staging/<string:payload_name>/<string:staging_id>/')
    api.add_resource(TransportEndpoint, '/transport/',
                     '/transport/<int:transport_id>/')

    api.init_app(app)

    log("app.py:CreateApp", "Setting up CORS..")
    from flask_cors import CORS
    CORS(app, supports_credentials=dev)

    log("app.py:CreateApp", "Setting up Cache..")
    from backend.cache import cache
    cache.init_app(app)

    log("app.py:CreateApp", "Setting up Login Manager..")
    from models.user import login_manager, ApiSessionInterface
    login_manager.init_app(app)

    # Disable Session Cookies
    log("app.py:CreateApp", "Updating Session Interface..")
    app.session_interface = ApiSessionInterface()

    log("app.py:CreateApp", "Setting up socketio..")
    # You can add extra logging around socketio by setting the following options here: logger=True, engineio_logger=True
    socketio.init_app(app,
                      host='0.0.0.0',
                      manage_session=False,
                      message_queue=RABBIT_URL,
                      channel="ConsoleMessages",
                      cors_allowed_origins="*")

    from backend.rabbitmq import rabbit_consumer
    rabbit_consumer.socketio = socketio
    socketio.start_background_task(target=rabbit_consumer.process_data_events)

    # Check Upload Dir
    if not os.path.exists(UPLOAD_DIR):
        os.makedirs(UPLOAD_DIR)
    log("app.py:CreateApp", "Finished.")
    return app
Exemple #8
0
from flask import Flask, Blueprint
from flask_restful import Api
from flask_sqlalchemy import SQLAlchemy

from backend.database import db, uri
from backend.resources.generators.create_db import create_db

from backend.resources.version import Version

app = Flask(__name__)

# DB
app.config["SQLALCHEMY_DATABASE_URI"] = uri()
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db.init_app(app)

# API
blueprint = Blueprint('api', __name__, url_prefix='/api')
api = Api(blueprint)

# Add api paths here
api.add_resource(Version, '/version')

app.register_blueprint(blueprint)


if __name__ == "__main__":

    create_db(app, db)

    app.run(host="0.0.0.0")
Exemple #9
0
def register_api(app):
    """Register restful api. 可以在这里导入api或者直接在api文件里用api.route"""
    api.init_app(app)
    db.init_app(app)