Pepper your Python 🐍 with lessons from PHP 🐘: Flask Sieve
Pepper your Python 🐍 with lessons from PHP 🐘: Flask Sieve

Pepper your Python 🐍 with lessons from PHP 🐘: Flask Sieve

Some people would say that learning a new programming language is something that you need to start from scratch. I do not agree. As a senior backend developer, one of my favourite things to explore interesting crossovers. And I know I’m not the only one, since developers often cross paths and learn from one another. Flask Sieve is one of those cool things.

Request validation in Laravel (a PHP framework) is very straightforward and easy to do, requiring minimal configuration. It automatically creates intuitive responses and saves a lot of time for developers. In Flask, these validations can be done manually, but you can also leverage a similar smart validation using Flask Sieve by Edward Njoroge.

Here is an example of flask-sieve rules just to require a username and a numeric nonce:

class SomeRequest(FormRequest):
    def rules(self):
        return {
            "username": ["required"],
            "nonce": ["required", "numeric"],
        }

# and in requests
@validate(SomeRequest)
def start_job(request):
    do_stuff()

Without the library, to accomplish a similar result, the code would be something like:

def start_job(request):
    payload = request.json
    username = payload.get("username", None)
    nonce = payload.get("nonce", None)
    errors = {}

    if not username:
        errors["username"] = "username is required"

    if nonce is None:
        errors["nonce"] = "nonce is required"

    if not nonce.isnumeric() and "nonce" not in errors:
        errors["nonce"] = "nonce must be numeric"

    if errors:
        return {"errors": errors}, 400

    do_stuff()

This is just for two simple attributes and a couple of checks! But think about complicated patterns, such as one attribute being required only in the absence of another, complex validation patterns, regexes, attributes required in bulk, nested attributes, standard fields (such as IP addresses, URLs, formatted date or datetimes) etc. Separating the validation also helps with Single Responsibility Principle and reusability, since the same validation rules can be applied to multiple requests, easily.

When in doubt, always rely on experience. Try to work smarter, not harder. If your solution exists in one programming language, you should be able to find it in another.