python-3.x - 线程在 Django 中被阻塞 - Python
问题描述
在过去的 4 个小时里,我一直在尝试理解 django 的线程。似乎没有任何效果。我想让网站在前台运行,让后端与线程上的其他一些设备通信。我希望线程在网站启动时启动,但是当我调用线程直到线程结束时程序卡住了。你知道修复它的方法吗?请我需要帮助。
urls.py 文件
def add(x, y):
i=0
while i < 100000000:
x += y
i += 1
def postpone(function):
t = threading.Thread(target=function, args=(1,))
t.setDaemon(True)
t.start()
return 0
print("Before thread")
postpone(add(4,4))
print("After thread")
在 while 循环完成之前,服务器不会启动。
感谢阅读,希望有人知道答案。
解决方案
add
在线程启动之前调用函数,但您需要add
作为参考传递。
# decomposition
# first, add gets called
r = add(4,4)
# then the result is passed to func `postpone`
postpone(r)
# postpone accept a function and args, which eventually get passed to the function
def postpone(function, *args):
t = threading.Thread(target=function, args=args)
t.setDaemon(True)
t.start()
return 0
print("Before thread")
# pass func as a reference, also send args to the postpone func also
postpone(add, 4,4)
print("After thread")
推荐阅读
- python - 如何在python中提取图像上的彩色区域并变形为所需的大小?
- sql - 如何在 PostgreSQL 中对递归查询进行排序
- corda - 在 Corda 中使用 Account Framework 时使用 SyncKeyMappingFlow 时出错
- google-apps-script - 使用 Google Apps 脚本创建 Google Analytics 4 属性
- r - R闪亮:填写提示用户并支持自动填充功能的表单时不需要的反应
- python - 分配给类变量时如何修复pylint的未使用私有成员?
- javascript - 在 JS 中将 00 转换为 12
- c++ - 在 for 循环中的 2D 网格迷宫中显示周期
- apache - 如何在 apache 内部配置 mod_qos 以防止 DoS 攻击?
- bash - inotifywait - 仅在每秒保存时重新启动 ghci