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∼

相关推荐
文祐4 分钟前
C语言利用数组计算矩阵乘法
c语言·开发语言·矩阵
matlab代码5 分钟前
Matlab基于主成分分析PCA人脸识别系统(GUI界面)【源码44期】
开发语言·matlab·人脸识别
m0_738120729 分钟前
AI安全实战系列(四):Lab04 Multi-Agent——多智能体攻击分析
服务器·开发语言·人工智能·安全·网络安全·语言模型
Mr__Miss22 分钟前
Java 随机数生成器选型指南:Random、ThreadLocalRandom 与 SecureRandom
java·开发语言·python
Risehuxyc23 分钟前
PHP数据类型
开发语言·php
Wang's Blog27 分钟前
Go-Zero基础入门5: 探究go-zero如何基于gRPC扩展客户端
开发语言·后端·golang·go-zero
zh_xuan28 分钟前
c++ span的用法
开发语言·c++·span
caimouse38 分钟前
KiSystemStartupBootStack 函数分析
开发语言·reactos
CTA量化套保40 分钟前
2026年下半年Python量化入门,先看API如何接进小流程
人工智能·python
薛定猫AI1 小时前
【深度解析】动态多智能体团队:并行规划、开发与验证的 Python 实战
大数据·开发语言·python