Search code examples
djangogitwebserver

How does Django keep using the correct files when I checkout a Git branch?


How does Django and/or my webserver keep straight which files it should be using when I switch Git branches?

My understanding is that when I checkout a branch in Git that the actual file system is modified. Is this true? If yes, how does Django and the webserver keep the files in tact that existed when I started the server?

For Example:


Create views.py on master branch

return HttpResponse("<h1>Hello world!</h1>")

Start server (using daphne):

daphne -b 0.0.0.0 -p 9000 my_app.asgi:application

my app output:

Hello world!

Make modifications in views.py (development branch)

return HttpResponse("<h1>Thanks for Visting!</h1>")

Page refresh

Output does not change:

Hello world!

Bring down server

Ctrl + C

Start server (using daphne):

daphne -b 0.0.0.0 -p 9000 my_app.asgi:application

New Output

Thanks for Visting!


I understand hot reloading is a feature, but how does Django and the web server avoid using the modified files on the new branch?


Solution

  • The issue here is that your views.py file is only being read once, the first time the module is imported. After that, Python won't look at that file on disk anymore, so your changes won't have any effect.

    More generally, any web server should have a well-defined way of updating its content. Unless it's been explicitly designed to update itself when the underlying file system changes, you shouldn't expect it to work in that situation.

    What will happen with Python, specifically, is that the code will be loaded from the filesystem once, when the module is imported, and then not touched again. So if you update the filesystem while the Python process is running, modules that have already been imported will be using the old code while newly imported modules will use the new code. (For more detail on Python's caching of modules, see this question.)

    For development purposes it's common to use a web server that automatically restarts itself when it detects changes to the filesystem. That's what Django's development server does. However, it's hard to do perfectly, since the web server can't necessarily figure out every file that the code might depend on. It's also not always appropriate to simply restart, since that will close existing TCP connections.

    Because of such complexities, production deployment usually works differently. It could involve an explicit shut down and restart, or might involve spinning up a new server with the new code while waiting for the connections on the old server to be closed. In any case, it will depend on the specific, documented way that the web server is meant to be used.