openergy / omemdb

A python in-memory relational database.
Mozilla Public License 2.0
0 stars 1 forks source link

validation no error #7

Open Lefort-Antoine opened 1 year ago

Lefort-Antoine commented 1 year ago

hy

Why this code not generating an error

`from omemdb import Db, Record from omemdb.packages.omarsh import Schema, fields, validate, ValidationError

def _insee_validation(str_number):
    if len(str_number) != 5:
        return ValidationError("Insee number is not correct")
    try:
        eval(str_number.lstrip('0'))
    except NameError:
        return ValidationError("Insee number format is not correct.")

class Loc(Record):
    class Schema(Schema):
        pk = fields.String(required=True)
        insee = fields.String(missing=None, validate=_insee_validation)

class AppDb(Db):
    models = [
        Loc
    ]
db = AppDb()
db.loc.add(pk="1", insee="U")

`

The fonction _insee_validation return an error with "U" as input.

Regards

ccruveiller commented 3 months ago

Hi, according marshmallow documentation I would suggest the following way to validate a unique field. In marshmallow>3, the post_load seems to be replaced by the @validates_schema decorator

class Loc(Record):
    class Schema(Schema):
        pk = fields.String(required=True)
        insee = fields.String(missing=None)

        @validates_schema
        def validate_insee(self, data, **kwargs):
            print(len(data["insee"]))
            if len(data["insee"]) != 5:
                raise ValidationError("Insee must be 5 characters", "insee")](url)