Skip to content

Instantly share code, notes, and snippets.

@menecio
Created September 7, 2019 10:17
Show Gist options
  • Save menecio/e01ac908549c54892c53d906761b28ec to your computer and use it in GitHub Desktop.
Save menecio/e01ac908549c54892c53d906761b28ec to your computer and use it in GitHub Desktop.
database_sync_to_async borrows from channels
from django.db import close_old_connections
from asgiref.sync import SyncToAsync
class DatabaseSyncToAsync(SyncToAsync):
"""
SyncToAsync version that cleans up old database connections when it exits.
"""
def thread_handler(self, loop, *args, **kwargs):
close_old_connections()
try:
return super().thread_handler(loop, *args, **kwargs)
finally:
close_old_connections()
# The class is TitleCased, but we want to encourage use as a callable/decorator
database_sync_to_async = DatabaseSyncToAsync
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment