Skip to content

Instantly share code, notes, and snippets.

@burningsky250
Created January 8, 2019 19:39
Show Gist options
  • Save burningsky250/ed425706a8048d25737ead707777efd6 to your computer and use it in GitHub Desktop.
Save burningsky250/ed425706a8048d25737ead707777efd6 to your computer and use it in GitHub Desktop.
django mysql thread-safety analyse

The ConnectionHandler is not a connection -- it only handles connections. It does so in a perfectly thread-safe manner by storing them on self._connections, which is a thread.local instance. The ConnectionHandler overrides getitem to support thread-local connections. When you access connections['default'], it looks if the default attribute exists on self._connections, which is a thread local. If it does, that would be the connection to the default database for the current thread. If it doesn't, it'll create a new one and set it on self._connections. Other threads won't be able to access this connection, since it's set on a thread local object. In the end it pretty much comes down to the public API. Setting a ConnectionHandler on a thread-local object would work as well, but the public API would be more complicated than it currently is, since user code would manually need to check if the handler for the current thread exists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment