Django and Application State

Posted 1 year, 8 months ago | Originally written on 16 Aug 2022

Ever since I started writing applications in Django, one of the things that has perennially troubled me is the lack of awareness that Django apps have for application state. There is no interface by which a developer can express application state. While the framework does a remarkable job of capturing the various entities involved in working with individual model objects, routing HTML requests and rendering markup, most applications work with groups of model objects optionally handing related resources such as files on disk. The number of valid states by which groups of entities can exist in is the application state and is independent of the interaction handling (i.e., url routing and view rendering). Such a application state interface would somehow (I honestly have no clue) take in sets of models and resources and have a way to declaratively making, managing and reporting the application's state. With such an arrangement, it will be very easy to write robust code while maintaining clean views, rather than littering get() and post() methods with lots of branches, making the code unreadable.

My proposal would be a set of State classes defined in a state.py module within each app or possibly at project level. These states would then be dependent on sets of models and resources, which could be provided with attributes which retrieve individual objects or related objects using some parameters at runtime. Based on the values of one or more attributes as well as the contents of resources, the particular State subclass would then route to another state or perform some required action e.g. update some other model or move individual items between resources etc.

Imagine with me the following:

from django.states import State
from django.core.files.storage import FileSystemStorage
from . import models
class Start(State):
    author = models.Author
    publication = models.Publication
    file_source = FileSystemStorate(location="/path/to/some/folder")
    file_dest = FileSystemStorate(location="/path/to/other/folder")                
      
    def evaluate(self, *args, **kwargs):
        """Method that performs evaluation of the state"""

This is so raw because I don't even know what a State object returns!

Having such a state-management means that we can test the application independent of the view handling in order to guarantee correct state transitions.