python在flask中的请求数据“无限流”

文章目录

一、问题描述

在flask请求中,有个需求是让调用方一直调接口,并立马返回,而接口方缓存请求,依次执行。

二、解决方案

python 复制代码
from flask import Flask, request, jsonify
from queue import Queue
import threading

app = Flask(__name__)
request_queue = Queue()

def process_requests():
    while True:
        if not request_queue.empty():
            request_data = request_queue.get()
            # 在这里处理请求数据,可以调用相应的函数进行处理
            print("Processing request:", request_data)
            # 在这里处理完请求后,可以返回响应给客户端,也可以不返回
        else:
            # 如果队列为空,等待一段时间后继续检查
            # 这里可以根据实际需求调整等待时间
            threading.Event().wait(1)

@app.route('/receive_request', methods=['POST'])
def receive_request():
    request_data = request.json
    # 将请求数据放入队列中
    request_queue.put(request_data)
    return jsonify({'message': 'Request received and queued.'})

if __name__ == '__main__':
    # 启动一个线程来处理请求
    request_handler_thread = threading.Thread(target=process_requests)
    request_handler_thread.start()
    # 启动 Flask 应用
    app.run(debug=True)

注意: 需要注意的是,request_queue.get()之后队列里的值就直接推出了,不用显式推出。

以上就可以做到讲请求立刻返回,接口缓存请求内容自我"消化"。Enjoy~

∼ O n e p e r s o n g o f a s t e r , a g r o u p o f p e o p l e c a n g o f u r t h e r ∼ \sim_{One\ person\ go\ faster,\ a\ group\ of\ people\ can\ go\ further}\sim ∼One person go faster, a group of people can go further∼

相关推荐
唐叔在学习6 分钟前
就算没有服务器,我照样能够同步数据
后端·python·程序员
曲幽2 小时前
FastAPI流式输出实战与避坑指南:让AI像人一样“边想边说”
python·ai·fastapi·web·stream·chat·async·generator·ollama
Flittly2 小时前
【从零手写 AI Agent:learn-claude-code 项目实战笔记】(1)The Agent Loop (智能体循环)
python·agent
vivo互联网技术4 小时前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习
敏编程5 小时前
一天一个Python库:virtualenv - 隔离你的Python环境,保持项目整洁
python
喝茶与编码7 小时前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone77397 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户8356290780517 小时前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python
用户962377954488 小时前
🚀 docx2md-picgo:Word 文档图片一键上传图床工具
python·markdown