Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Having Trouble with DRF in multi-threaded production enviornment. #218

Open
kardeepak77 opened this issue Apr 25, 2024 · 0 comments
Open

Comments

@kardeepak77
Copy link

Stack: Django, DRF, Gunicorn, PostgreSql ( All latest as of Aapril, 2024)

I have implemented multi-tenancy changes as suggested on -

from django_multitenant.fields import *
from django_multitenant.models import *
class Store(TenantModel):
tenant_id = 'id'
name = models.CharField(max_length=50)
address = models.CharField(max_length=255)
email = models.CharField(max_length=50)

class Product(TenantModel):
store = models.ForeignKey(Store)
tenant_id='store_id'
name = models.CharField(max_length=255)
description = models.TextField()
class Meta(object):
unique_together = ["id", "store"]
class Purchase(TenantModel):
store = models.ForeignKey(Store)
tenant_id='store_id'
product_purchased = TenantForeignKey(Product)

'default': {
'ENGINE': 'django_multitenant.backends.postgresql',
......
}

2)For DRF made changes - as per - https://django-multitenant.readthedocs.io/en/latest/django_rest_integration.html

All works fine in development where I am using Django wsgi without Gunicorn.

However, In production I am using Gunicorn with 3 working threads for Django wsgi.
I observed following behavior -

  1. I can successfully login with user [email protected] by calling auth/user/create endpoint which returns JWT token.
  2. Logging in with another user e.g. [email protected] by calling auth/user/create endpoint results in error.

I observed that select query generated against postgresql for 1) has SQL WHERE clause just for the user name.
However, select query generated for 2) has SQL WHERE clause that is filtering by 2 filters -
i) tenant_id of user [email protected]
2) user name [email protected]

Not sure why tenant_id filter is inserted for login call.

Current observation is -
django_multitenant.middlewares.MultitenantMiddleware
isn't calling unset_current_tenant()
Should it call though to avoid above issue?

The unsetting of the tenant is essential because of how webservers work
Since the tenant is set as a thread local, the thread is not killed after the request is processed
So after processing of the request, we need to ensure that the tenant is unset
Especially required if you have public users accessing the site

 This is also essential if you have admin users not related to a tenant.

Any guidance?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant