1 year ago
#212622
kametguler
What is the most effective validation method on Flask?
First of all, I try to make an Rest-API with Flask MongoEngine. I create a model which is;
class Project(db.Document):
name = db.StringField(validation=validate_project_name)
created_at = db.DateTimeField()
updated_at = db.DateTimeField()
def save(self, *args, **kwargs):
if not self.created_at:
self.created_at = datetime.datetime.now()
self.updated_at = datetime.datetime.now()
return super(Project, self).save(*args, **kwargs)
def __str__(self):
return self.name
and I also created a Form ;
ProjectForm = model_form(Project, exclude=["created_at", "updated_at"])
and also the custom validation is ;
def validate_project_name(name, min=5, max=25):
if len(name) <= min or len(name) >= max:
raise ValidationError(
f"Proje adı en az {min} en fazla {max} karakter olabilir!"
)
return True
I want to validate with ProjectFrom when i send the data which I get from request body that's why i prepare that code ;
@project.route("/create", methods=["POST"])
def create_project():
data = MultiDict(request.json)
form = ProjectForm(data, meta={"csrf": False})
if form.validate():
if Project(name=form.data["name"]).save():
## will take create action
return True
else:
return Response({form.errors}, status=400)
It returns true when i request but when i change de data on request.body it still returns true where do i mistake can someone help me and explain the logic. Or Should i create a middleware for the validation also i tried that. and i created something. But i don't know is it the best way. Thanks in advance...
Middleware that i tried to validate data;
def creation_project_validation(func):
@wraps(func)
def decorated_function(*args, **kwargs):
if request.method == "POST":
data = request.json
if data.get("name") is None:
return Response({"Name is required field!"}, status=400)
if validate_project_name(data.get("name")):
return Response(
{"Karakter uzunluğu istenilen şekilde değil!"}, status=400
)
return func(*args, **kwargs)
else:
Response("Method not allowed", status=405)
return decorated_function
flask
flask-wtforms
flask-mongoengine
0 Answers
Your Answer