在RESTful Web服务中,服务器花费几分钟的时间进行响应是否可以接受? [英] In a RESTful web service, is it acceptable for the server to take many minutes to respond?

查看:126
本文介绍了在RESTful Web服务中,服务器花费几分钟的时间进行响应是否可以接受?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用flask-restful开发RESTful Web服务.

I am developing a RESTful web service using flask-restful.

客户端需要能够请求服务器执行的作业.这项工作可能需要大约1秒钟到大约1个小时才能完成.通常,预计需要1-5分钟.

The client needs to be able to request a job to be performed by the server. This job can take anywhere from ~1 second to ~1 hour to perform. Generally, it is expected to take 1-5 minutes.

作业完成后,客户端需要下载JSON转储.大小从100KB到100MB不等.

When the job is complete, the client needs to download a JSON dump. Anywhere from 100KB to 100MB in size.

我看到2个选项:

  1. 客户端将作业作为POST请求提交,并且只有在作业完成时服务器才会做出响应.响应包括JSON转储.
  2. 客户端将作业作为POST请求提交,服务器立即响应200 OK.然后,客户端每60秒提交一次GET状态请求.作业完成后,它将提交另一个GET请求以下载JSON转储.

在REST原则下,哪个选项是首选?

Which option is preferred under REST principles?

我在选项1中看到的问题是等待响应时网络中断的可能性.

The problem I see with Option 1 is the possibility of network disruption whilst waiting for the response.

推荐答案

等待几秒钟是绝对不可以.

大多数Web基础结构都不旨在处理如此长的延迟,并且某些代理/负载平衡器可能会超时-即使您的服务器最终产生了响应,也没有人可以读取它.而且,用户会感到无聊,然后开始刷新/取消/无论如何.

Most of the web infrastructure is not designed to handle such long delays, and some proxies/load balancers may timeout - even if your server finally produces the response, no-one will be there to read it. Moreover, the user will get bored and start refreshing/cancelling/whatever.

正如@jonrsharpe在评论中提到的那样,您的服务器应该尽快响应有关正在发生的事情的信息.输入202 Accepted状态代码:

As @jonrsharpe mentioned in the comment, your server should respond as quickly as possible with information on what's happening. Enter 202 Accepted status code:

该请求已被接受进行处理,但是处理尚未完成.该请求最终可能会执行,也可能不会最终执行,因为在实际进行处理时可能会不允许该请求.无法通过这样的异步操作重新发送状态代码.

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.

(摘录自 restapitutorial )

因此在主体或响应头中使用202进行响应,并提供结果的句柄.然后,客户可以轮询给定的位置以查看工作状态并下载结果.

So respond with 202 and a handle to where the results should be - either in body or in response headers. Then the client can poll given location to see the job status and download the results.

如果结果很大,则允许对结果进行HEAD请求也是合理的,以便用户可以轮询HEAD来检查结果是否可用,然后使用GET下载它们,而不会突然出现在投票期间被淹没了.

If the result is big, it's also reasonable to allow HEAD requests on the result, so that the user can poll HEAD to check if the results are available and then download them with GET, without being suddenly flooded during the polling.

这篇关于在RESTful Web服务中,服务器花费几分钟的时间进行响应是否可以接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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