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∼

相关推荐
正经教主10 分钟前
【FDE系列】阶段2:Day 35:Python + SQL — 工单接入 MySQL + 本周收官
人工智能·python·fde
Xiu Yan10 分钟前
Python 数据分析:Pandas Series 零基础入门教程
python·jupyter·pycharm·numpy·pandas
心易行者15 分钟前
Python在线运行+SQLite数据库实战:0成本搭个人数据后台,5个场景直接套用
前端·网络·人工智能·python
逆向编程1 小时前
QGIS地图投影(CRS坐标参照系)设置
开发语言
数据杂坛1 小时前
【Python程序开发系列】实例方法、类方法(@classmethod)、静态方法(@staticmethod)有什么区别
python·课程设计·python语法
free-elcmacom1 小时前
发际线警告!手撕《C陷阱与缺陷》终极 BOSS:signal 函数与 typedef 魔法
c语言·开发语言·visual studio code·visual studio
程序员阿鹏1 小时前
简单介绍一下软引用
java·开发语言·jvm·数据结构·后端
正经教主1 小时前
【FDE系列】阶段2:Day 31:SQL 基础 — 增删改查一把梭
人工智能·python·fde
leihefeng1 小时前
PX04-用 Python 读 Excel 画折线图,还能直接插回 Excel 文件
python·excel
Mr.朱鹏1 小时前
Docker三剑客实战指南:Docker、Dockerfile 和 Docker Compose
python·docker·devops·dockerfile