-
Notifications
You must be signed in to change notification settings - Fork 0
Models and Schemas
The models and schemas are stored in the models folder
Models are made with sqlalchemy(read for more info), there are only two change in sqlalchemy models. They are inheriting from Standard and creating a method called changes:
- changes method
- inherit from standard
In this line db (sqlalchemy instance), ma (marshmallow instance) and Standard (Class) are imported
Model class must inherit from db.Model(read about sqlalchemy) and Standard
Create fields (sqlalchemy)
The changes method receives a json as a parameter:
Json key values are assigned to the columns of the database:
Take any action on the data, In the example the password is encrypted
The constructor receives as a parameter a json and call the changes method; this to avoid doing repetitive code
The changes method will serve to insert data in json format both to create a new record (init method) and to modify it (changes method)
The Standard class is found in the file _int_.py
The class helps us to save, update or delete data, all the models created must inherit from it for its correct operation, below it is shown how to use it in different contexts.
The schemes are made with marshmallow (read for more)
In this case the id is not defined in the schema because it is autoincrement,the other fields are defined depending on the type of data they will store, additionally marshmallow provides more varied data types to achieve better validations.
password will not show in json output for client, that's why load_only is set to True
In the meta class, the fields displayed to the client are defined in the fields variable, but if a field was previously defined as load only, it will not be displayed.
This process will do for each model you create!
In this example we have 5 models, which are inherited in classes inside database_init.py
Use in any url context, the examples use the model shown above, but you can use it with any model that follows the structure already stated
An object is created from the model, the model is passed as a parameter a json with all the data expected by the model
The save method returns true if the data was successfully saved
the changes method receives as a parameter a json with the new values for the register(put method)
Save the changes (the save method is already explained in the previous chapter)
The delete method returns true if the data was successfully deleted
Note: You may want to validate the json, this is covered in the Routes chapter. For data serialization use marshmallow.