简体   繁体   English

Flask:进行非阻塞请求调用

[英]Flask: making a non-blocking requests call

Flask==2.0 (+uwsgi processes=5, threads=20) Python: 3.9 Flask==2.0 (+uwsgi 进程=5, 线程=20) Python: 3.9

I have a route that will accept a message and re-direct this message to other API(s) based on the type of message.我有一个将接受消息并根据消息类型将此消息重定向到其他 API 的路由。 Let's say there are 4 types of messages with 4 matching downstream APIs.假设有 4 种类型的消息和 4 个匹配的下游 API。 The request is made using requests library and downstream API will return a response that my route will need to return to the client (so I need to wait for the response).该请求是使用requests库发出的,下游 API 将返回我的路由需要返回给客户端的响应(因此我需要等待响应)。

The issue is sometimes one of the downstream APIs can have an issue exhibiting high latency.问题有时是下游 API 之一可能会出现高延迟问题。 This has an undesired result as this makes my application slow and impact other message types.这会产生不希望的结果,因为这会使我的应用程序变慢并影响其他消息类型。

Is there a way to make these requests calls non-blocking so the slow downstream API responses don't slow down the whole app?有没有办法使这些请求调用非阻塞,因此缓慢的下游 API 响应不会减慢整个应用程序的速度? I read the flask async guide and from my understanding you can get real benefit if you're making multiple requests calls within a single route which isn't the case for me, it's always a single request.我阅读了烧瓶异步指南,据我了解,如果您在单个路由中发出多个请求调用,您可以获得真正的好处,这对我来说并非如此,它始终是一个请求。

Async requests to your downstream API could provide some relief in your case, I believe:我相信,对您的下游 API 的异步请求可以为您提供一些缓解:

Async is beneficial when performing concurrent IO-bound tasks, but will probably not improve CPU-bound tasks.异步在执行并发 IO-bound 任务时很有用,但可能不会改善 CPU-bound 任务。

Consider also using a queueing mechanism (such as background tasks in flask, or something more fully fledged such as RabbitMQ).还可以考虑使用排队机制(例如烧瓶中的后台任务,或者更成熟的东西,例如 RabbitMQ)。

Final words - also consider defining timeout for your requests.最后的话 - 还考虑为您的请求定义超时。

https://flask.palletsprojects.com/en/2.1.x/async-await/ https://flask.palletsprojects.com/en/2.1.x/async-await/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM