Modularization
Created by: NotSpecial
Modularizing AMIVAPI
First of all I would recommend reading the docs for flask extension development and application factories. They are short and very informative, showing how extensions for flask can look and how they should be integrated in the app.
Short: Either have an extension class or module, in both ways there should be an init_app
method and if you have a class you should avoid binding it to an app (E.g. app.extension = Extension(app)
should not be done)
For this concept to work together with Eve we need to consider additional points: schema, validation, hooks. (Together with the flask blueprints)
Schema
This is fortunately very easy since Eve provides a method register_resource
which can be used just for this. We can just define the models and schema in the extensions and use this in init_app
The only difficulty are dependencies between sql models. The eve sqlalchemy register_schema
relies on them, so all model classes need to be defined before register_schema
is called. This can be handled easily by putting the schema creating in a method which is called in init_app
. This way everything is imported before correctly.
(See events.py and groups.py)
Validation
Unlike for resources, there is no convenient method to extend the validator. On the other hand I didn't like having to manually combine it before app creation because I wanted to stick to the init_app
concept.
Eve stores a validator class (not instance) in app.validator
. I created a helper in utils.py which creates a new, empty class with the extension class and the current validator class as parents. Using type
this can be handled very nicely:
app.validator = type("Adopted_%s" % validator_class.__name__,
(validator_class, app.validator),
{})
(More info in the python docs)
Hooks & Blueprints
No problem here, they can be added to the app instance in init_app
comfortably.
Status
Every resource (or related resources together) have now their own directory. All resources are now modules.
models.py and schemas.py are gone