返回后运行命令python

问题描述 投票:0回答:3

我遇到过这个问题,我想要返回一些内容并在之后调用另一个函数(在python中)

继承我目前的代码:

def new_user(request):
'''Takes a request and enters it in the database IF that wallet id is not in the database! '''
data = request.body
if data != '':
    user_info = eval(data)
    if type(user_info) != type({}):
       ... more code here ...
                send_email(vCode)
                return HttpResponse(response)

我想在返回响应后调用send_email。我在这里尝试了一些事情: - 在另一个函数中调用new_user和send_email但是我需要返回某种HttpResponse(所以我不能在不返回它的情况下调用new_user)所以这不起作用 - 试图屈服一个请求,不能在yield -tried线程之后调用另一个函数,有一个类似的问题 - 当前尝试asyncio但我遇到了问题,还有什么我可以做的吗?

python django asynchronous return
3个回答
1
投票

我知道实现这一目标的唯一方法是在另一个线程中运行该函数。你说你已经尝试过,但没有成功,但没有提供你尝试过的例子。下面是一个应该有效的代码示例

import threading
...
def new_user(request):
'''Takes a request and enters it in the database IF that wallet id is not in the database! '''
data = request.body
if data != '':
    user_info = eval(data)
    if type(user_info) != type({}):
       ... more code here ...
                task = threading.Thread(target=send_email, args=(vCode,))
                task.daemon = True
                task.start()
                return HttpResponse(response)

注意:您需要将此线程标记为daemon,以便python不会在关闭之前等待它加入。由于您在代码完成后将其旋转以运行,因此这是必要的步骤。

另一个选择是使用某种任务队列并将其发送出去处理,你也说你正在尝试用asyncio。在更大的应用程序中,这将是更好的选择。


0
投票

在您的函数Return之后,您无法在同一视图中执行额外的代码。我的电子邮件必须在retunr之后发送,你可以从你的函数返回一个重定向return redirect(new_view_to_send_email)到一个发送电子邮件的新函数。


-2
投票

你可以使用lamda

lambda: return HttpResponse(response),
        send_email(vCode)
© www.soinside.com 2019 - 2024. All rights reserved.