对的,当成功添加任务到队列时,应该返回 HTTP 状态码 200 表示成功。以下是修改后的代码示例:
# app.py
from flask import Flask, request
from subprocess import Popen
from queue import Queue
from threading import Thread
app = Flask(__name__)
task_queue = Queue()
def execute_task(task):
# 执行外部 Python 脚本
process = Popen(['python', 'external_script.py', task])
process.wait() # 等待外部脚本执行完成
@app.route('/tasks', methods=['POST'])
def add_task():
task = request.form.get('task') # 从 POST 请求中获取任务数据
task_queue.put(task) # 将任务添加到队列中
return 'Task added to the queue', 200
def task_execution():
while True:
if not task_queue.empty():
task = task_queue.get() # 从队列中获取任务
execution_thread = Thread(target=execute_task, args=(task,))
execution_thread.start()
if __name__ == '__main__':
# 启动任务执行线程
execution_thread = Thread(target=task_execution)
execution_thread.start()
# 启动 Flask 应用
app.run()
在这个修改后的代码中,当成功添加任务到队列时,返回的响应中包括了状态码 200。这表示任务成功添加到队列中。