如何从Vue.js前端向Django Rest Framework API发送对象列表?
Vue.js 向API发送数组实现多任务并发处理
核心实现思路
直接将条目数组作为请求体发送给API,后端接收后通过多线程(如Python的threading、Java线程池等)并行处理每个条目,避免逐个请求带来的耗时问题。
具体代码实现
1. Vue.js前端发送请求
以下分别给出axios和原生fetch的实现示例:
用axios发送请求
// 在Vue组件中引入并使用axios import axios from 'axios'; export default { methods: { async sendItemsForProcessing() { // 构造待处理的条目数组 const items = [ { "1": "item1" }, { "2": "item2" }, { "3": "item3" } // 可添加更多条目 ]; try { // 发送POST请求,将数组作为请求体 const response = await axios.post('/api/process-items', items, { headers: { 'Content-Type': 'application/json' } }); console.log('处理完成:', response.data); // 此处添加处理成功后的UI更新逻辑 } catch (error) { console.error('请求失败:', error); // 此处添加错误提示逻辑 } } } };
用原生fetch发送请求
async sendItemsForProcessing() { const items = [ { "1": "item1" }, { "2": "item2" }, { "3": "item3" } ]; try { const response = await fetch('/api/process-items', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(items) }); const result = await response.json(); console.log('处理完成:', result); } catch (error) { console.error('请求失败:', error); } }
2. 后端接收与多线程处理示例(Python Flask)
后端需先接收数组,再启动多线程并行处理每个条目:
from flask import Flask, request, jsonify import threading app = Flask(__name__) def process_single_item(item): # 编写单个条目的处理逻辑,比如根据条目内容执行对应命令 key = next(iter(item.keys())) value = item[key] print(f"处理条目 {key}: {value}") # 替换为实际业务处理代码 @app.route('/api/process-items', methods=['POST']) def process_items(): items = request.get_json() threads = [] # 为每个条目创建独立线程 for item in items: thread = threading.Thread(target=process_single_item, args=(item,)) threads.append(thread) thread.start() # 可选:等待所有线程处理完成后再返回结果 for thread in threads: thread.join() return jsonify({"status": "success", "message": "所有条目处理完成"}) if __name__ == '__main__': app.run(debug=True)
注意事项
- 请求头设置:必须指定
Content-Type: application/json,确保后端能正确解析JSON格式的数组。 - 线程安全:后端多线程处理时需注意资源竞争问题,比如操作数据库或共享文件时要加锁。
- 结果返回:若需返回每个条目的处理结果,后端可收集线程执行结果后统一返回;若无需同步等待,也可先返回任务启动状态,后续通过轮询或WebSocket获取处理进度。
内容的提问来源于stack exchange,提问作者Anna M
相关产品推荐
相关产品推荐

