Gautham Kumaran
Gautham Kumaran

Reputation: 441

How does django detect file changes

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.

Upvotes: 9

Views: 4710

Answers (2)

knbk
knbk

Reputation: 53669

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.

Upvotes: 8

hard
hard

Reputation: 103

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.

Upvotes: 5

Related Questions