lundi 21 septembre 2020

MongoEngine and WTForm classes: how to avoid duplication business rules when having a MVC pattern

In my flask application, I have two classes. The first one defines the database model (mongoengine)

class Expenses(UserMixin, Document):
    exp_date = DateTimeField(required=True, max_length=10)
    exp_product = StringField(required=True, max_length=200)

And the second one defines a form data as my view (WTForms):

class ExpensesForm(FlaskForm):

    exp_date = WTDateField(
        'Date',
        format='%d/%m/%Y',
        validators=[InputRequired()]
    exp_product = WTStringField(
        'Product',
        validators=[InputRequired()])

I am trying to avoid having two different classes with the same logic. For example, I have to specify that the field exp_product is required in both classes. This can lead to some errors if, for example, I change the required property in one class but forget to change in the other one. Of course, this is a simplified example. It gets worse when I have many fields with many different rules defined.

I think the best solution for that case would be to unify both classes or to apply the Strategy Pattern but I have no idea how to do so.

Aucun commentaire:

Enregistrer un commentaire