@app.route('/tiji', methods=['POST']) def tiji(): dch = request.form.get('dch') name = request.form.get('filename') print(name) folder_name = f"{dch}dianyun" if not os.path.exists(folder_name): os.mkdir(folder_name) for file in request.files.getlist('file'): filename = file.filename file.save(os.path.join(folder_name, filename)) dhs = request.form.getlist('dh') print(len(dhs)) for i in range(len(dhs)): print(dhs[i]) folder_path = os.path.join(folder_name) file_name = f"{name}.laz" if has_file(folder_path, file_name): emit('output', {"code": 200, "msg": "success"}) else: emit('output', {"code": 500, "msg": "fail"}) return jsonify({"code": 200, "msg": "success"}) 这段代码如何改可以在emit发送给前端内容后继续执行,最后再return
时间: 2024-04-15 09:31:13 浏览: 121
为了在调用 `emit` 发送内容给前端后继续执行代码,你可以使用 `background_task` 装饰器来将发送消息的代码块放在后台执行。这样,在发送消息的同时,可以继续执行后续的代码逻辑。最后,使用 `return` 返回最终的响应。
下面是修改后的代码示例:
```python
from flask import Flask, request, jsonify
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/tiji', methods=['POST'])
def tiji():
dch = request.form.get('dch')
name = request.form.get('filename')
print(name)
folder_name = f"{dch}dianyun"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
for file in request.files.getlist('file'):
filename = file.filename
file.save(os.path.join(folder_name, filename))
dhs = request.form.getlist('dh')
print(len(dhs))
for i in range(len(dhs)):
print(dhs[i])
folder_path = os.path.join(folder_name)
file_name = f"{name}.laz"
if has_file(folder_path, file_name):
@socketio.background_task # 使用 background_task 装饰器
def send_message():
emit('output', {"code": 200, "msg": "success"})
send_message() # 调用发送消息的函数
else:
emit('output', {"code": 500, "msg": "fail"})
return jsonify({"code": 200, "msg": "success"})
if __name__ == '__main__':
socketio.run(app)
```
在上述代码中,我们使用 `background_task` 装饰器将发送消息的代码块放在后台执行。这样,发送消息的同时,可以继续执行后续的代码逻辑。最后,使用 `return` 返回最终的响应。
请确保已正确安装 Flask-SocketIO 扩展,并在启动应用程序时使用 `socketio.run(app)`。
希望这可以解决你的问题!如果还有其他疑问,请随时提问。
阅读全文