예제 #1
0
def create_app(configuration):
    app = Flask('clockit_api')
    app.config.from_object(configuration)

    db.init_app(app)

    Migrate(app, db)

    # from .schemas import ma
    ma = Marshmallow()
    ma.init_app(app)

    from .views import api_bp
    app.register_blueprint(api_bp, url_prefix='/api')

    jwt.init_app(app)

    return app
예제 #2
0
class Database():
    """Database configuration."""
    def __init__(self):
        self.database = SQLAlchemy()
        self.uri = ''
        self.ma = Marshmallow()

    def init_db(self, app):
        """Initialize db."""
        self.init_db_info(POSTGRES)
        app.config['SQLALCHEMY_DATABASE_URI'] = self.uri
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        self.database.init_app(app)  # init flask alchemy
        self.ma.init_app(app)  # init flask marshmellow

    def init_db_info(self, postgres):
        """Init database info."""
        user = postgres['USER']
        pwd = postgres['PW']
        database = postgres['DB']
        url = f'postgresql://{user}:{pwd}@localhost/{database}'
        self.uri = url
        return url

    def get_db(self):
        """Returns database."""
        return self.database

    def get_ma(self):
        return self.ma

    def insert(self, row):
        db = self.get_db()
        try:
            db.session.add(row)
            db.session.commit()
        except Exception as e:
            print(e)
            print('ann error ocurred')
        return row

    def commit_changes(self):
        return self.database.session.commit()
예제 #3
0
def configure_app(app: Flask) -> None:
    """
    The configuration is read from the filename in the "FLASK_SETTINGS_FILENAME"
    environment variable (if it exists) and some other important settings

    Additional settings such as SECRET_KEY and other settings should be added
    accordingly.

    :param Flask app: The Flask app that requires configuring.
    :return: None
    """
    app.config.from_envvar("FLASK_SETTINGS_FILENAME", silent=True)
    app.csrf = flask_seasurf.SeaSurf(app)

    marshmallow = Marshmallow(app)
    marshmallow.init_app(app)

    from .routes import routes
    routes(app)
예제 #4
0
def create_app(config_name):
    global db
    global ma
    global app
    global socketio

    db = SQLAlchemy()
    ma = Marshmallow()

    app = Flask(__name__, instance_relative_config=True)

    ma.init_app(app)

    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    # Creating SocketIO app here so that
    # it can be accessed by views
    socketio = SocketIO(app)

    db.init_app(app)

    from .auth import auth as auth_blueprint
    from .card import card as card_blueprint
    from .collection import collection as collection_blueprint
    from .collection import owned_collection as owned_collection_blueprint
    from .room import room as room_blueprint
    from .loader import loader as loader_blueprint

    app.register_blueprint(auth_blueprint)
    app.register_blueprint(card_blueprint)
    app.register_blueprint(collection_blueprint)
    app.register_blueprint(owned_collection_blueprint)
    app.register_blueprint(room_blueprint)
    app.register_blueprint(loader_blueprint)

    return app
예제 #5
0
db = SQLAlchemy(app)
login_manager = LoginManager(app)
mail = Mail(app)
csrf = CSRFProtect(app)
bcrypt = Bcrypt(app)
ma = Marshmallow(app)

db.init_app(app)
login_manager.init_app(app)
mail.init_app(app)
login_manager.login_view = 'users.login'
login_manager.login_message_category = 'info'
login_manager.session_protection = 'strong'
csrf.init_app(app)
bcrypt.init_app(app)
ma.init_app(app)

from afrilearn.main import main as main_blueprint
from afrilearn.users import users as users_blueprint
from afrilearn.courses import courses as courses_blueprint

app.register_blueprint(main_blueprint)
app.register_blueprint(users_blueprint)
app.register_blueprint(courses_blueprint)

subjects = [
    'english', 'mathematics', 'kiswahili', 'science', 'religious-education',
    'social-studies'
]
예제 #6
0
def test_deferred_initialization():
    app = Flask(__name__)
    m = Marshmallow()
    m.init_app(app)

    assert "flask-marshmallow" in app.extensions
예제 #7
0
class RestLib:
    __slots__ = (
        '_blueprints',
        '_factory',
        '_factory_callback',
        'ma',
    )

    def __init__(self, app=None):
        self._blueprints = []
        self._factory_callback = None
        self._factory = None

        self.ma = Marshmallow()

        if app is not None:
            self.init_app(app)

    @property
    def factory(self):
        if self._factory is None:
            callback = getattr(self, '_factory_callback')

            if callback is None:
                raise RuntimeError('Missing factory_loader.')

            self._factory = callback()()
        return self._factory

    def factory_loader(self, callback):
        """This sets the callback for loading default resource manager."""
        self._factory_callback = callback
        return callback

    def init_app(self, app):
        self.ma.init_app(app)

        app.config.setdefault('RESTLIB_PAGINATION_ENABLED', True)
        app.config.setdefault('RESTLIB_URL_PARAM_LIMIT', 'limit')
        app.config.setdefault('RESTLIB_URL_PARAM_OFFSET', 'offset')
        app.config.setdefault('RESTLIB_PAGINATION_LIMIT', 25)

        factory_class = app.config.setdefault('RESTLIB_FACTORY', None)

        if factory_class is not None:
            self.factory_loader(lambda: import_string(factory_class))

        app.extensions['restlib'] = self

        app.register_error_handler(HTTPException, self.http_exception_handler)
        app.register_error_handler(ValidationError,
                                   self.validation_exception_handler)

    def create_blueprint(self, *args, **kwargs) -> ApiBlueprint:
        bp = ApiBlueprint(*args, **kwargs)
        self._blueprints.append(bp)
        return bp

    def register_blueprints(self, app):
        for bp in self._blueprints:
            app.register_blueprint(bp)

    def http_exception_handler(self, err):
        """Return JSON instead if Content-Type application/json for HTTP errors."""
        # print(err.__dir__())
        # print(err.data)

        if err.code in (400, 422):
            headers = err.data.get('headers', None)
            messages = err.data.get("messages", ["Invalid request."])
            if headers:
                return {"errors": messages}, err.code, headers
            else:
                return {"errors": messages}, err.code

        if request.is_json:
            return ApiError(err.description, err.code).to_response()
        return err

    def validation_exception_handler(self, err):
        if request.is_json:
            return ApiError(err.messages, 422).to_response()
        return err
예제 #8
0
migrate = Migrate()
admin = Admin()
marsh = Marshmallow()


def create_app(config_object):
    app = Flask(__name__)
    app.config.from_object(config_object)
    return app


app = create_app(SETTINGS.get(FLASK_ENV, 'default'))
db.init_app(app)
migrate.init_app(app, db)
admin.init_app(app)
marsh.init_app(app)

from . import models

admin.add_view(ModelView(models.OrgClient, db.session))
admin.add_view(ModelView(models.OrgSector, db.session))
admin.add_view(ModelView(models.OrgPerson, db.session))
admin.add_view(ModelView(models.OrgTeam, db.session))

from .api.resources import (
    OrgClientResource,
    OrgClientListResource,
    OrgSectorResource,
    OrgSectorListResource,
    OrgPersonResource,
    OrgPersonListResource,
예제 #9
0
def create_app():
    from .db import db

    # Models
    from .providers.models import Provider
    from .medicines.models import Medicine
    from .customers.models import Customer
    from .accounts.models import User

    # Views
    from .accounts.views import user_blueprint, auth_blueprint
    from .medicines.views import medicine_blueprint, upload_blueprint
    from .providers.views import provider_blueprint
    from .customers.views import customer_blueprint

    # Common
    from .common.exceptions import InvalidUsage
    from .common.handlers import bad_request_handler, unauthorized_handler
    from .accounts.utils import jwt_identity, identity_loader, DecimalJSONEncoder

    app = Flask(__name__)
    app.json_encoder = DecimalJSONEncoder
    app.config.from_object(environ.get("FLASK_SETTINGS_MODULE"))

    # database and migrations
    db.init_app(app)
    Migrate(app, db)

    # marshmallow
    ma = Marshmallow(app)
    ma.init_app(app)

    # jwt extended
    jwt = JWTManager(app)
    jwt.init_app(app)
    jwt.user_identity_loader(identity_loader)
    jwt.user_loader_callback_loader(jwt_identity)

    # bcrypt
    bcrypt = Bcrypt()
    bcrypt.init_app(app)

    # CORs
    cors = CORS()
    cors.init_app(app)

    # Minio
    storage = Minio(app)
    storage.init_app(app)

    # Swagger
    swagger = Swagger()
    swagger.init_app(app)

    # error handlers
    app.register_error_handler(InvalidUsage, bad_request_handler)
    app.register_error_handler(HTTPStatus.BAD_REQUEST, bad_request_handler)
    app.register_error_handler(HTTPStatus.UNAUTHORIZED, unauthorized_handler)

    # blueprints
    app.register_blueprint(auth_blueprint)  # Authentication
    app.register_blueprint(provider_blueprint)  # Provider
    app.register_blueprint(user_blueprint)  # Users
    app.register_blueprint(customer_blueprint)  # Customers
    app.register_blueprint(medicine_blueprint)  # Medicines
    app.register_blueprint(upload_blueprint)  # Medicines upload

    return app