Created
May 10, 2024 07:23
-
-
Save IlianIliev/7c5e03e9a29335ae5abb4135cc59bba9 to your computer and use it in GitHub Desktop.
gRPC interceptor to manage Django DB connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Handling database connections in gRPC server and Django | |
As explained in the docs -> https://docs.djangoproject.com/en/5.0/ref/databases/#caveats | |
``` | |
If a connection is created in a long-running process, outside of Django’s request-response cycle, the connection will | |
remain open until explicitly closed, or timeout occurs. | |
``` | |
This practically means that all long-running processes are responsible for managing their database connections. | |
The following interceptor provides such functionality for gRPC servers using the Django framework. | |
""" | |
from grpc_interceptor import ServerInterceptor | |
from django.db import close_old_connections | |
class CloseOldDBConnectionInterceptor(ServerInterceptor): | |
""" | |
This interceptor is used to close old database connections if they are not usable e.g. reached the timeout or | |
broken | |
IMPORTANT: Extending `grpc.ServerInterceptor` and implementing the `intercept_service` method | |
causes the interceptor to be executed in a separate thread, thus it has no control on the | |
connections used by the actual handler | |
Using the `grpc_interceptor.ServerInterceptor` and implementing the `intercept` method | |
causes the interceptor to be executed in the same thread as the actual handler | |
thus it has control on the connections used by the actual handler | |
WARNING: Implementing `intercept_service` in the same method causes `intercept` to not be called | |
""" | |
def intercept(self, method, request, context, method_name): | |
close_old_connections() | |
result = method(request, context) | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment