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∼

相关推荐
xcLeigh1 小时前
编程语言的 AI 友好度排名:Python、JavaScript、TypeScript 谁更适合 AI 辅助
javascript·人工智能·python·ai·typescript·ai编程
Albart5751 小时前
【已解决】ModuleNotFoundError_ No module named ‘xxx’ 模块导入失败终极解决
python·pip·环境配置·后端开发·bug解决·模块报错·python导包失败
Dr.kangder1 小时前
嵌入式总线设备解析——TTE总线应用与实践
开发语言·网络·算法·嵌入式·多任务·同步机制
-银雾鸢尾-2 小时前
C#中的多线程
开发语言·c#
2401_858286112 小时前
OS82.【Linux】设计线程池
java·linux·运维·服务器·开发语言·算法·线程池
数据知道2 小时前
IDOR 不安全的直接对象引用:API 越权实战检测
java·开发语言·网络·安全·网络安全
花酒锄作田2 小时前
Repository 模式在 FastAPI 中的应用
python·fastapi
leisoo80972 小时前
涨停板封板质量打分系统实战:基于本地逐笔数据的Python实现
linux·服务器·python
c238562 小时前
# Mini OJ — 项目详解文档
开发语言·数据库·c++