Issue
I had been facing this error that prompted;
Operational Error: Server gone away
in my Django project. This happended when I submitted the Django user creation form. I used the connection.close method from django.db and the problem got resolved.
I rewrote the registerview class as follows.
class registerView(CreateView):
form_class = UserCreationForm
template_name = 'register.html'
def get(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse:
if (self.request.user.is_authenticated):
return redirect('home')
return super().get(request, *args, **kwargs)
def get_success_url(self) -> str:
return '/login'
def post(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse:
try:
connection.connection.ping()
return super().post(request, *args, **kwargs)
except Exception:
connection.close()
return super().post(request, *args, **kwargs)
The problem is solved but I don't understand why this is happening. The connection.close() method is meant to close the connection.
Solution
For posterity sake, I will share some background first.
I used the connection.close method from django.db and the problem got resolved.
Your solution does work and it was actually the recommended solution when this issue was first raised.
- RECOMMENDED SOLUTION: close the connection with from django.db import connection; connection.close() when you know that your program is going to be idle for a long time.
- CRAPPY SOLUTION: increase wait_timeout so it's longer than the maximum idle time of your program.
—-Django issues. Ticket #21597. Comment 29. Resolution -> wontfix
The problem is solved but I don't understand why this is happening. The
connection.close()
method is meant to close the connection.
After you close the connection and then use the post()
method of the super()
class to complete your request instead, Django knows to automatically open a new connection to the Database [Django docs] in that function call, which it then uses.
except Exception:
connection.close()
return super().post(request, *args, **kwargs) # opens a new connection to the database here
So while you closed the old connection, a new connection got opened for you automatically without your very effort.
I would recommend setting CONN_HEALTH_CHECKS
to True
. It can be used to improve the robustness of connection reuse and prevent these errors you are getting when a connection has been closed by the database server.
Answered By - Chukwujiobi Canon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.