maciej-gol / tenant-schemas-celery

MIT License
175 stars 36 forks source link

Support needed: getting information of tenant in scheduled task #89

Closed smaxx1337 closed 1 year ago

smaxx1337 commented 1 year ago

hey, this is not a bug. I just need some help because I am currently stuck.

My goal is to have a periodic task where reminder email gets sent if a certain condition is met. However, the mail contains information of the tenant, such as the tenant name, tenant.domain_url.

Normally, I get those by checking "request.tenant.name" or "request.tenant.domain_url". But in a periodic task there is no request object that I can access obviously.

Basically, my current tasks.py looks like this. See comment where I am stuck:


@app.task
def send_offer_reminder_in_schema(*args, **kwargs):
    seven_days_ago = timezone.now() - timedelta(minutes=5)
    offers = Offer.objects.filter(created_at__lte=seven_days_ago, reminder_sent=False)
    for offer in offers:
        try:
            recipient = offer.customer.user.email
            # TODO: get tenant name and so on to put it into mail_context. HOW?
            mail_context = {}
            html_message = render_to_string('crm_tenant/emails/offer_reminder_mail.html', mail_context)
        except Exception as e:
            pass

@app.task
def send_offer_reminder_in_all_schemas():
    for tenant in get_tenant_model().objects.exclude(schema_name='public'):
        with tenant_context(tenant):
            send_offer_reminder_in_schema.delay(tenant=tenant)

I tried passing the tenant like this: send_offer_reminder_in_schema.delay(tenant) but then I get a lot of errors, such as "kombu.exceptions.EncodeError: Object of type Client is not JSON serializable".

How can I get the tenant info in the task?

maciej-gol commented 1 year ago

Heya! I'm currently away from computer :( The closest you might get to what you want is

This should work for you. Let me know if you have more questions.

smaxx1337 commented 1 year ago

Thank you very much for the hint! I have managed to get the tenant infos successfully by doing following:

from django.db import connection

@app.task(bind=True)
def send_offer_reminder_in_schema(self, *args, **kwargs):
    seven_days_ago = timezone.now() - timedelta(minutes=5)
    offers = Offer.objects.filter(created_at__lte=seven_days_ago, reminder_sent=False)
    for offer in offers:
        try:
            # NEW
            tenant = self.get_tenant_for_schema(connection.schema_name)
            print(tenant.name)

            recipient = offer.customer.user.email

            mail_context = {}
            html_message = render_to_string('crm_tenant/emails/offer_reminder_mail.html', mail_context)

        except Exception as e:
            passs

I will close this issue as it is solved. Thank you very much for your help. Have a nice day!