某些功能应在Web服务器上异步运行.发送电子邮件或数据后处理是典型的用例.
编写装饰器函数以异步运行函数的最佳(或最pythonic)方法是什么?
我的设置很常见:Python,Django,Gunicorn或Waitress,AWS EC2标准Linux
例如,这是一个开始:
from threading import Thread
def postpone(function):
def decorator(*args, **kwargs):
t = Thread(target = function, args=args, kwargs=kwargs)
t.daemon = True
t.start()
return decorator
Run Code Online (Sandbox Code Playgroud)
所需用法:
@postpone
def foo():
pass #do stuff
Run Code Online (Sandbox Code Playgroud) python django multithreading decorator python-multithreading
我有一个Django网站,一个页面有一个按钮(或链接),点击它将启动一个有点长时间运行的任务.显然,我想将此任务作为后台任务启动,并立即将结果返回给用户.我想使用一种简单的方法实现这一点,这种方法不需要我安装和学习像Celery这样的全新消息传递架构.我不想用芹菜!我只想使用一种简单的方法,我可以设置并在接下来的半小时左右运行.是不是有简单的方法在Django中执行此操作而无需添加(另一个)第三方程序包?
我有一个关于如何从模板HTML按钮调用视图函数的问题?像一个onclick功能?这是模板:
<input id="submit" type="button" onclick="xxx" method="post" value="Click" />
Run Code Online (Sandbox Code Playgroud)
而views.py是:
def request_page(request):
...do something...
return render_to_response("/directory.html", {})
Run Code Online (Sandbox Code Playgroud)
非常感谢你.
这是我的代码:
class EmailThread(threading.Thread):
def __init__(self, subject, html_content, recipient_list):
self.subject = subject
self.recipient_list = recipient_list
self.html_content = html_content
threading.Thread.__init__(self)
def run (self):
msg = EmailMultiAlternatives(self.subject, self.html_content, EMAIL_HOST_USER, self.recipient_list)
#if self.html_content:
msg.attach_alternative(True, "text/html")
msg.send()
def send_mail(subject, html_content, recipient_list):
EmailThread(subject, html_content, recipient_list).start()
Run Code Online (Sandbox Code Playgroud)
它不发送电子邮件.我能做什么?
假设我需要请求多个服务器做出响应
def view_or_viewset(request):
d1 = request_a_server() # something like requests.get(url, data)
d2 = request_b_server()
d3 = request_c_server()
d4 = do_something_with(d3)
return Response({"foo1": d1, "foo2": d2, "foo3": d3, "foo4": d4})
Run Code Online (Sandbox Code Playgroud)
我正在为每个请求执行同步请求,我想一定有更好的方法来处理这种情况。
(如果任务很长,我会使用 celery,但事实并非如此,仍然执行多个同步请求似乎不对)
处理这个问题的推荐范例(?)是什么?
我期待使用asyncor aioHttpand yield(?)
我的问题被标记为可能重复,并且那里的答案建议使用线程..我认为手动处理线程是应该避免的(根据我过去在 c++ 中使用多线程的经验)
然后我发现/sf/answers/1673142411/ request-future 在这里似乎很有希望..