Best way to validate your Database model in Python

Validate your models with code that is elegant and easy to maintain

On this example i will show how to validate faster and cleaner with orator bottle and Python, you could use flask or Django but in the example I’m using BottlePy.

When I started using Python for the backend of my projects, I landed into a problem that the phoenix framework for elixir and mongoose for nodeJS had solved a long time ago.

It’s a lot better to validate your request data for a new insert on the database from the model instead of the controller so I built a simple library that along orator creates and easy way to maintain your validations with a clean syntax.

from orator import Model, SoftDeletes
from orator_validator import Validator

On this simple example I validate that the user send name, last_name, if they didn’t and error will raise letting you know that it’s required, also you can’t use regex type of validation, because we all can’t agree to what is the best regex for email validates. Just put the one you prefer.

This leaves you with a fast to program environment for the controllers i just do this to handle the errors and create a new user.

from bottle import (
request, abort, error
)

The problem that I encounter after using this new library was, that the updates where taking more time, than the inserts so I updated the library to validate on updates to.

from orator import Model, SoftDeletes
from orator_validator import Validator

On the validate Update function I have the same options as validate for create, but the main difference between them it’s that here I have a guarded parameter, when you activate the flag, if the user tries to update that part of the model it will raise and error because it’s forbidden.

Also the function_callback works like a trigger if the user sends the value it will trigger the callback the good part about this is that you have all the power of Python, and in most cases you will not required to use cron jobs if the api is well thought out.

The update controller look like this

def update_one(self, item_data_id):
'''
This function is dedicated to update the item_data to match some
other data

To install the library just

$ pip install orator-validator

The github repo if you want to report and issue or make a pr is.

Web developer trying to make a living out of it