Data Providers / Parametrized tests in Python

Take as example a simple validator function: it is usually a pure function, simple input data structure and boolean return value. Writing tests for a validator can create a lot of boilerplate and repetitive code. A solution for simpler test structure are data providers and parametrized tests. In e.g. JavaScript / node.js or PHP you usually use the term “data provider” whereas in Python “parametrized” is used. Below you can find an example for parametrized tests for an is_valid_email validator.

Continue reading “Data Providers / Parametrized tests in Python”

Modern architecture for a CRUD-Application in Django without an SPA-Frontend

Django is an opinionated framework. It recommends a structure for how to build the application and as a developer you should follow. However, from a frontend perspective it is very traditional with the strict differentiation of views, templates and styles – in contrast to SPA-technologies like Angular2+, React or Vue which uses a component-approach.

If you have a more or less pure CRUD-application, it can make sense to rely on Django completely instead of programming an SPA-Frontend. Django provides a lot of features out of the box in a good structured manner. BUT the strict separation most often lead to complex views and templates after some time with a lot of violations of the Single Responsibility Principle, although at the beginning everything seems fine.

In this article, I will show an alternative Django-structure on how to implement a component-approach.

Continue reading “Modern architecture for a CRUD-Application in Django without an SPA-Frontend”

Django (SQL/”Model”) Performance Optimization

Django makes it easy to write code, which performs bad, since it is automatically executing SQL statements when you are handling models. If you don’t know about the details behind that, you can easily end up executing thousands of queries.

def get_books_by_author():
    books = Book.objects.all()
    result = defaultdict(list)    
    for book in books:
        author = book.author
        title_and_author = '{} by {}'.format(
            book.title,
            author.name
        )
        result[book.library_id].append(title_and_author)    return result

This will execute for each book an author query! Which means 1 query for books and n queries for n books!

books = Book.objects.all().select_related('author')

This will add “author” into the Book.objects.all() query and you just execute one query!

However, select_related only works for one-to-many and one-to-one. Many to one relations can be optimized with prefetch_related().

Continue reading “Django (SQL/”Model”) Performance Optimization”