Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does django detect file changes

Tags:

python

django

I'm trying to watch for changes in .py files, in a directory. I went through existing solution. I'm curious on how django library solves this problem. The development server is restarted on file changes.

like image 670
Gautham Kumaran Avatar asked Mar 31 '17 12:03

Gautham Kumaran


2 Answers

The code can be found in django.utils.autoreload. The autoreloader uses a separate thread that watches any python module that has been imported, and any translation file.

If inotify is available, Django uses that to listen to change events. Otherwise, it checks the timestamps of every file every second. If there are any changes, the process is restarted.

Django's autoreloader may not be the best source of inspiration. Better options may be Watchman (with the appropriate python bindings) or the pure-python alternative Watchdog.

like image 186
knbk Avatar answered Oct 05 '22 02:10

knbk


Fast forward to April 2019:

With django 2.2 pywatchman as part of Watchman will be supported and pyinotify (being unmaintained since mid 2015) is dropped:

If you're using Linux or MacOS and install both pywatchman and the Watchman service, kernel signals will be used to autoreload the server (rather than polling file modification timestamps each second). This offers better performance on large projects, reduced response time after code changes, more robust change detection, and a reduction in power usage.

source: django-admin

When using Watchman with a project that includes large non-Python directories like node_modules, it's advisable to ignore this directory for optimal performance.

See the watchman documentation for information on how to do this.

like image 43
hard Avatar answered Oct 05 '22 02:10

hard