search

Validatorian

Nov 18, 2024 am 06:43 AM

Validatorian

Validations are a method of ensuring that our databases only receive the type of information that is appropriate for each attribute. After all, we wouldn't want a surprise type of data to find it's way into our code and cause unexpected behavior. Fortunately, SQLAlchemy has a package that makes validations quick and easy!

Let's look at some simple examples. Imagine we have a simple model, Sandwich. Here we have already initialized our database and are importing it from a configuration file.

from config import db

class Sandwich(db.Model):
    __tablename__ = 'sandwiches'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    description = db.Column(db.String)
    price = db.Column(db.Float)

If we want to add validations to any of these attributes, we'll need to import the validations package first.

from sqlalchemy.orm import validates

And then, write our function with the '@validates' decorator inside the model.

    @validates('name')
    def validate_name(self, key, value):
        if not value:
            raise ValueError('Name cannot be empty.')
        if type(value) != str:
            raise ValueError('Name must be a string.')
        return value

So what's going on here? Let's break it down. The @validates is a decorator that lets our ORM know to pass any values received with the key of 'name' through our validation function before adding them to the database. The value we return is what is finally given to our database. The "key" argument is the key that is being evaluated, in this case 'name', the value is the value of that key, so the actual name(hopefully in text) that we are trying to add. So here we are checking to make sure that the name attribute passed in is not empty, and that is in in fact a string. If not, we raise an error.

We can also run multiple attributes through the same decorator by adding them to it's arguments.

    @validates('name', 'description')
    def validate_text(self, key, value):
        if not value:
            raise ValueError(f'{key} cannot be empty.')
        if type(value) != str:
            raise ValueError(f'{key} must be a string.')
        return value

This function validates our name and description attributes, but we won't usually have the same validations to perform on different attributes. Depending on how different and how many validations we have we can do it a couple of different ways. We can run a separate validator for our other attributes, let's add a length validation for our description and price validations too:

    @validates('name')
    def validate_name(self, key, value):
        if not value:
            raise ValueError('Name cannot be empty.')
        if type(value) != str:
            raise ValueError('Name must be a string.')
        return value

    @validates('description')
        def validate_description(self, key, value):
        if not value:
            raise ValueError('Description cannot be empty.')
        if type(value) != str:
            raise ValueError('Description must be a string.')
        if not 10 



<p>Or, we can keep the same validator for both and use the key argument passed in to adjust which validations are run for each attribute.<br>
</p>

<pre class="brush:php;toolbar:false">    @validates('name', 'description', 'price')
    def validate(self, key, value):
        if key != 'price:
            if not value:
                raise ValueError(f'{key} cannot be empty.')
            if type(value) != str:
                raise ValueError(f'{key} must be string.')
            if key == 'description':
                if not 10 



<p>Hmm, this is a little messy, let's refactor into 2 separate validators.<br>
</p>

<pre class="brush:php;toolbar:false">    @validates('name', 'description')
    def validate_text(self, key, value):
       if not value:
            raise ValueError(f'{key} cannot be empty.')
        if type(value) != str:
            raise ValueError(f'{key} must be string.')
        if key == 'description':
            if not 10 



<p>That's better! Here's our completed model:<br>
</p>

<pre class="brush:php;toolbar:false">from sqlalchemy.orm import validates
from config import db

class Sandwich(db.Model):
    __tablename__ = 'sandwiches'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    description = db.Column(db.String)
    price = db.Column(db.Float)

    @validates('name', 'description')
    def validate_text(self, key, value):
        if not value:
            raise ValueError(f'{key} cannot be empty.')
        if type(value) != str:
            raise ValueError(f'{key} must be string.')
        if key == 'description':
            if not 10 



<p>That's it! Validations are one easy tool to make sure your databases stay right and proper.</p>


          

            
        

The above is the detailed content of Validatorian. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the alternatives to concatenate two lists in Python?What are the alternatives to concatenate two lists in Python?May 09, 2025 am 12:16 AM

There are many methods to connect two lists in Python: 1. Use operators, which are simple but inefficient in large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use the = operator, which is both efficient and readable; 4. Use itertools.chain function, which is memory efficient but requires additional import; 5. Use list parsing, which is elegant but may be too complex. The selection method should be based on the code context and requirements.

Python: Efficient Ways to Merge Two ListsPython: Efficient Ways to Merge Two ListsMay 09, 2025 am 12:15 AM

There are many ways to merge Python lists: 1. Use operators, which are simple but not memory efficient for large lists; 2. Use extend method, which is efficient but will modify the original list; 3. Use itertools.chain, which is suitable for large data sets; 4. Use * operator, merge small to medium-sized lists in one line of code; 5. Use numpy.concatenate, which is suitable for large data sets and scenarios with high performance requirements; 6. Use append method, which is suitable for small lists but is inefficient. When selecting a method, you need to consider the list size and application scenarios.

Compiled vs Interpreted Languages: pros and consCompiled vs Interpreted Languages: pros and consMay 09, 2025 am 12:06 AM

Compiledlanguagesofferspeedandsecurity,whileinterpretedlanguagesprovideeaseofuseandportability.1)CompiledlanguageslikeC arefasterandsecurebuthavelongerdevelopmentcyclesandplatformdependency.2)InterpretedlanguageslikePythonareeasiertouseandmoreportab

Python: For and While Loops, the most complete guidePython: For and While Loops, the most complete guideMay 09, 2025 am 12:05 AM

In Python, a for loop is used to traverse iterable objects, and a while loop is used to perform operations repeatedly when the condition is satisfied. 1) For loop example: traverse the list and print the elements. 2) While loop example: guess the number game until you guess it right. Mastering cycle principles and optimization techniques can improve code efficiency and reliability.

Python concatenate lists into a stringPython concatenate lists into a stringMay 09, 2025 am 12:02 AM

To concatenate a list into a string, using the join() method in Python is the best choice. 1) Use the join() method to concatenate the list elements into a string, such as ''.join(my_list). 2) For a list containing numbers, convert map(str, numbers) into a string before concatenating. 3) You can use generator expressions for complex formatting, such as ','.join(f'({fruit})'forfruitinfruits). 4) When processing mixed data types, use map(str, mixed_list) to ensure that all elements can be converted into strings. 5) For large lists, use ''.join(large_li

Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version