Sqlalchemy Error Handling and Custom Validations

I read several questions about this and I don't know yet what is the best solution for this problem. Let's assume we have a model like this:

from sqlalchemy import Column, Integer, String

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    email = Column(String, unique=True)
    fullname = Column(String)
    password = Column(String, nullable=False) 

      

In my controller I want to create a user by validating the parameters and handling sqlalchemy errors to respond to this request.

check validation:

  • email uniqeness
  • password cannot be empty
  • the password must be at least 6 characters.

to check the number 3, we can use the validates decoraor. for first check 2 we can add and commit this user and somehow parse sqlalchemy.exc.SQLAlchemyError error that is raised.

But I really don't like it. because it is so messy and not scalable . some actions like uniqeness need to query db. but checking if the value is null no need to query db and parse sqlAlchemyError.

What's the best way to handle different types of validation?

What's the best way to parse sqlAlchemyError messages and return proper HTTP status codes to clients?

+3


source to share


1 answer


Depending on what you plan to do with your application, you can use the excellent wtforms validation features :

from flask_wtf import Form
from wtforms import StringField, PasswordField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import Length, Required, Email, EqualTo

class FooForm(Form):
    email = EmailField('Email', validators=[Required(),Email()])
    fullname = StringField('Name', validators=[Required(), Length(64)])
    password = PasswordField('Password', validators=[Required(), EqualTo('password2', message='Passwords must match.'), Length(8)])
    password2 = PasswordField('Password (confirm)', validators=[Required(),Length(8)])
    submit = SubmitField('Submit')

      



This is about your user authentication - if something is not compliant it will catch errors before any request is made to the backend. For post uniquenes, I would suggest wrap the sqla transaction in "try: ... except:" to catch the error and issue an appropriate message to the user. Or you can write your own wtforms validator as described here . For example, you can uncheck the ajax request to the server and check if the email address is valid.

+2


source







All Articles