My mutation contains a function which calls an API to send SMS. Since this function's execution may take some time, and its result doesn't have anything to do with what the mutation returns (It does not have to be send back to the client); I prefer to run it asynchronously. So that the mutation gets executed as fast as possible.
Here's my code:
class MyMutation(graphene.Mutation):
class Arguments:
phone = graphene.String(required=True)
success = graphene.Boolean()
@classmethod
def mutate(cls, root, info, phone):
...
...
myfunction() #The client should not wait for this function's execution.
return MyMutation(success=True)
note: myfunction is NOT an async function. And I prefer to keep it that way.
I couldn't find a proper way to do this in django-graphene's docs.
CodePudding user response:
You need to use other methods to run async function, you can use any of the following:
- django-background-tasks: Simple and doesn't require a worker
- python-rq: Great for simple async tasks
- celery: A more complete solution
CodePudding user response:
Thanks for your answer. I wanted to see if there was any other way than using packages like celery as you mentioned.
So I installed celery with redis and made some initial configurations. I declared myfunction in a file called tasks.py and called it from the mutation:
from .tasks import myfunction
class MyMutation(graphene.Mutation):
class Arguments:
phone = graphene.String(required=True)
success = graphene.Boolean()
@classmethod
def mutate(cls, root, info, phone):
...
...
myfunction().delay() #now this function is called asynchronously
return MyMutation(success=True)
Everything works smoothly.