在无响应Flask路由的呼叫上放置超时(更新) [英] Place a timeout on calls to an unresponsive Flask route (updated)

查看:705
本文介绍了在无响应Flask路由的呼叫上放置超时(更新)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在Flask应用程序中有一条从外部服务器提取数据的路由,然后将结果推送到前端。外部服务器偶尔会慢或无响应。在路由呼叫上放置超时的最佳方法是什么,如果外部服务器滞后,前端不会挂起?或者在Flask(而不是Apache,nginx等)中有一个更合适的方式来处理这种情况?



我的目标是超时路由呼叫 保持任意长时间的流程像这样的问题:超时问题与铬和烧瓶。选项如websockets运行后台进程/线程,直到它们完成;然而,我想在一段固定的时间过去之后停止一个缓慢的路由呼叫。像函数调用超时 Python超时,但在Flask上下文中。芹菜的任务装饰(并行异步与Python,瓶和芹菜过程)似乎是一个很好的解决方案,但是我不想要大量的依赖关系,只能使用少量的功能。

不完全确定我是否正确的所有这一切,但我的理解是,如果线程(或greenthread)处理该请求使网络呼叫在自己的前台中,并且该呼叫超时,博尔肯管道几乎会发生。但是您可以做的是将一个完全独立的线程脱离网络请求,然后在请求处理代码中调用Thread.join()超时。



http://docs.python.org/2/library/ threading.html#threading.Thread.join



在这一点上,调用Thread.isAlive()(仍然在你的请求处理代码路径中),如果真的,网络呼叫没有及时返回,并且您返回错误状态。



如果它是False - 您需要拥有worker线程使用响应数据更新一些(线程安全)数据结构 - 您可以获得响应数据,并继续前进。


I currently have a route in a Flask app that pulls data from an external server and then pushes the results to the front end. The external server is occasionally slow or unresponsive. What's the best way to place a timeout on the route call, so that the front end doesn't hang if the external server is lagging? Or is there a more appropriate way to handle this situation in Flask (not Apache, nginx, etc)?

My goal is to timeout a route call, not keep an arbitrary long process alive like this SO question: Time out issues with chrome and flask. Options like websockets run background processes/threads until they finish; however, I want to stop a slow route call after some fixed amount of time has elapsed. Like Timeout on a function call and Python Timeout but within a Flask context. Celery's task decorator (Concurrent asynchronous processes with Python, Flask and Celery) seems like a great solution, but I don't want to require a large dependency to only use a small amount of its functionality.

解决方案

Not entirely sure if I'm right about all this, but my understanding is that if the thread (or greenthread) handling the request does the network call in it's own "foreground", and that call times out, the borken pipe is pretty much going to happen. But what you can do is spin off a fully-separate thread that does the network request, then call Thread.join() with a timeout in your request-handling code.

http://docs.python.org/2/library/threading.html#threading.Thread.join

At that point, call Thread.isAlive() (still in your request-handling code path) and if True, the network call didn't return in time, and you return your error state.

If it's False - and you'll need to have the "worker" thread update some (thread-safe) data structure with the response data - you get that response data and go on your way.

这篇关于在无响应Flask路由的呼叫上放置超时(更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆