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∼

相关推荐
一个天蝎座 白勺 程序猿27 分钟前
Python爬虫(47)Python异步爬虫与K8S弹性伸缩:构建百万级并发数据采集引擎
爬虫·python·kubernetes
XiaoMu_0012 小时前
基于Django+Vue3+YOLO的智能气象检测系统
python·yolo·django
honder试试2 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky3 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
心本无晴.3 小时前
Python进程,线程
python·进程
ponnylv3 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人3 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
Jayden_Ruan4 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊4 小时前
启动文件Startup_vle.c
c语言·开发语言
VBA63374 小时前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言