Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@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