【问题标题】:Flask return "ok" to user and process the data [duplicate]Flask向用户返回“ok”并处理数据[重复]
【发布时间】:2018-03-19 09:07:04
【问题描述】:

我刚开始使用烧瓶,我正在制作一个服务器应用程序来处理一些请求,现在对于 POST 请求部分,它有一个需要一些时间的过程,这意味着我必须让用户继续使用移动应用程序等到我响应他发送的第一个 POST 请求。

是否有某种方式可以让我将OK 返回到移动应用程序并在后台处理数据?

到目前为止我的想法是这样的:-

if request.method=='POST':
    #signal another process ( another python file for example) to start with parameters from the request 
    return "OK"

但我不确定这是最佳做法,还有其他想法吗?

编辑

按照安装 celery 的建议,我已经下载并将它与 redis 一起安装在 Windows 上。我有一个代理工作者 Celery 正在运行,但是当我尝试发出 POST 请求时得到以下信息:

TypeError: ExtractFeatures() takes exactly 2 arguments (1 given)

对于我的带有 redis 配置的 celera:

from flask import Flask
from celery import Celery

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

对于ExtractFeatures() 函数:

def ExtractFeatures(JsonRecieved):
#testing for now sleep for 5 seconds to make sure code executes this 
#function parallel and finishes the request handling
time.sleep(5)
print("finished Extracting Features")

对于 POST 请求:

@app.route('/PostPhotos',methods=['POST'])
def api_PostPhotos():
if request.method=="POST":
    ExtractFeatures.delay(request.json)
return("finished request")

我的期望是在“完成提取特征”之前打印“完成的请求”,但我得到了上面显示的错误。

【问题讨论】:

  • 你需要像 Celery 这样的东西。
  • @DanielRoseman 如果你能帮助我,我添加了一个新的编辑

标签: python flask celery


【解决方案1】:

在 Web 应用程序中实现长时间运行的进程通常不是一个好主意。

典型的解决方案是将消息写入某种类型的队列(SQS、Celery、磁盘上的文件等)并实现单独的工作进程来运行更长的操作。

如果您需要在操作完成时通知用户,您可以为此目的在消息中提供数据,将结果写入另一个队列,并让客户端进程进行检查。

【讨论】:

  • 我现在正在使用 celery 来达到这个目的,但是我还是个初学者,你能帮帮我吗?我用到目前为止得到的信息编辑了这个问题。
猜你喜欢
  • 2014-01-28
  • 2021-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 2022-01-21
相关资源
最近更新 更多