Created
April 16, 2021 19:12
-
-
Save dlederle/c9b702455db73d509e10222d4610afe4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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