在django-石墨烯突变中异步调用同步函数



我的突变包含一个调用API发送SMS的函数。因为这个函数的执行可能需要一些时间,并且它的结果与突变返回的结果没有任何关系(它不必被发送回客户端);我更喜欢异步运行它。以便尽可能快地执行突变。

下面是我的代码:

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)

注意:myfunction不是async函数。我更愿意保持这种状态。

我在django-graphene的文档中找不到合适的方法。

谢谢你的回答。我想看看是否有其他的方法,而不是像你提到的使用芹菜包。

所以我用redis安装了芹菜,并做了一些初始配置。我在一个名为tasks.py的文件中声明了我的函数并从突变中调用它:

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)

一切顺利。

最新更新