django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" when fetching data from database
PaulleDemon opened this issue · comments
django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" when fetching data from database
This happens when trying to fetch through channels after deployment to the AWS Linux-2 server. Please go through till the end
I am performing Authentication through JWT so I have the below piece of code:
# source: https://github.com/joshua-hashimoto/django-channels-jwt-auth-middleware
class JWTAuthMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
close_old_connections()
try:
if(jwt_token_list := parse_qs(scope["query_string"].decode("utf8")).get('token', None)):
jwt_token = jwt_token_list[0]
jwt_payload = self.get_payload(jwt_token)
user_credentials = self.get_user_credentials(jwt_payload)
user = await self.get_logged_in_user(user_credentials)
scope['user'] = user
print("FINAL USER: ", user)
else:
scope['user'] = AnonymousUser()
except (InvalidSignatureError, KeyError, ExpiredSignatureError, DecodeError) as e:
print("Error: ", e)
return await self.app(scope, receive, send)
def get_payload(self, jwt_token):
payload = jwt_decode(
jwt_token, settings.SECRET_KEY, algorithms=["HS256"])
return payload
def get_user_credentials(self, payload):
user_id = payload['user_id']
return user_id
async def get_logged_in_user(self, user_id):
user = await self.get_user(user_id)
print("RETURNED USER: ", user)
return user
@database_sync_to_async
def get_user(self, user_id):
try:
return User.objects.get(id=user_id) # This is primary key for user model
except User.DoesNotExist:
return AnonymousUser()
def JWTAuthMiddlewareStack(app):
return JWTAuthMiddleware(AuthMiddlewareStack(app))
I am able to get the model and everything seems to work fine until it reaches the below code in get_user
method which is decorated with database_sync_to_async
:
User.objects.get(id=user_id) # This is primary key for user model
which then throws the below error:
Traceback (most recent call last):
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner
return func(*args, **kwargs)
File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory
Is the server running locally and accepting connections on that socket?
I am sure it is not a problem with my configuration because the data is being queried without any error and displayed to the front-end. This happens when trying to use async in channels. Any idea why?
Sorry This was my bad. My environment variables was not being loaded in AWS