Skip to content

Instantly share code, notes, and snippets.

@dlederle
Created April 16, 2021 19:12
Show Gist options
  • Save dlederle/c9b702455db73d509e10222d4610afe4 to your computer and use it in GitHub Desktop.
Save dlederle/c9b702455db73d509e10222d4610afe4 to your computer and use it in GitHub Desktop.
@contextmanager
def tenant(value):
"""
Context manager for tenants. Used to set and cleanup tennant.
param, value, can be Tenant object or id.
Using the context context manager
```python
with tenant(1):
Profile.objects.get(pk=1)
```
Using it as a decorator
```python
@tenant(1)
def foo():
Profile.object.get(pk=1)
```
"""
previous = getattr(threadlocal, "whitelabel", None)
if isinstance(value, Tenant):
set_tenant(value)
else:
set_tenant_id(value)
try:
yield
finally:
if previous:
set_tenant_id(previous["tenant_id"])
else:
set_tag("tenant", None)
delattr(threadlocal, "whitelabel")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment