How to configure flake8 in Django?

How to configure flake8 in Django?
Photo by Agence Olloweb / Unsplash

Code formatting and hygiene is one of the most crucial aspects of a project, this determines if all your fellow developers love to work on the codebase or they have a frustration look when a new task is given to them. How much so ever the senior folks in the team try to control the hygiene using review process, they are bound to be by-passed if there are not enough automated processes added.

This brings us to the next question what all automation can someone do to make sure that the code hygiene is maintained and people do not by-pass these as per their advantage. In python there are primarily 2 such tools which help us maintain the codebase

Let us discuss how we can configure flake8 to Django repository

  • Install flake8 package to the codebase
  • Add git pre-commit hook to make sure that whenever someone is committing any changes then flake8 is run to verify that the changes are as per the coding guideline set by you.
  • configure .flake8 file to add all the rules or exceptions

Installing flake8 is straightforward by using pip

pip install flake8

One can use different git pre-commit hooks as per their convenience, here we are going to use lefthook to run flake8 every time someone makes a commit on the Django project.

pre-commit:
  parallel: true
  commands:
    flake8_backend_lint:
      root: "backend/" # folder of the code
      glob: "*.py"
      run: flake8 {staged_files} && git add {staged_files}
lefthook.yml

Once the lefthook is configured, every time someone makes a commit then the flake8 would be executed on the files which are edited, this is important for performance, else if you have a large project it might take minutes to make a commit, which would frustrate the developers even more.

flake8 gives you the option to configure on which rules to override and also ignore certain files. For example, you would not want to run flake8 on autogenerated files like the migration files, so you can tell which files to ignore and also have refined control of only ignoring certain rules on certain files. Check the below example where we are updating the max-line length from 79 to 120 and also excluding migrations folder completely while adding specific ignore rules to only certain files.

[flake8]
max-line-length = 120
exclude=*/migrations/*
per-file-ignores =
    ./random_file.py:E501
    ./settings/local.py:F405,F403
    ./settings/prod.py:F405,F403,F401
    ./settings/staging.py:F405,F403
    ./accounts/apps.py:F40
.flake8

Do remember to save this file on the parent directory. You get more rules from the documentation.

Error / Violation Codes — flake8 4.0.1 documentation