对未响应的Flask路由的呼叫设置超时(已更新) [英] Place a timeout on calls to an unresponsive Flask route (updated)

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

问题描述

我目前在Flask应用程式中有一个路径,可从外部伺服器撷取资料,然后将结果推送至前端。外部服务器偶尔会慢或无响应。什么是在路由调用上设置超时的最佳方法,以便前端不会挂起,如果外部服务器滞后?或者有更合适的方法来处理Flask中的这种情况(不是Apache,nginx等)?

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)?

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

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 Python 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.

推荐答案

不完全确定我是否对所有这一切,但我的理解是,如果线程(或greenthread)处理请求做网络调用它自己的前台,并且该调用超时,borken管道几乎要发生。但你可以做的是分离一个完全独立的线程执行网络请求,然后调用Thread.join()在请求处理代码超时。

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.Thin.join

此时,调用Thread.isAlive()(仍然在请求处理代码路径中),如果真的,网络调用没有及时返回,并返回错误状态。

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.

如果它是False - 你需要有worker线程使用响应数据更新一些(线程安全的)数据结构 - 获取响应数据并继续。

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天全站免登陆