使用celery 和python flask 上传文件

6ss1mwsb  于 2021-06-10  发布在  Redis
关注(0)|答案(0)|浏览(372)

我上传csv文件通过html如下。

<input type="file" name="File Upload" id="txtFileUpload" accept=".csv" />

但是,例如,我直接在api中给出csv路径,并将内容保存到mongodb中。
场景:用户上传一个文件。当响应成功时,用户不应该等待响应,因为上传(大量数据)可能需要几个小时。但无论他何时进入那个页面,都应该看到进度条。
所以我跟着一些东西,我可以用celery 来完成任务。但是,坚持了什么,以wtite icelery 任务,以及如何显示在用户界面的进展。
这是我正在尝试的python代码,

import csv
from pymongo import MongoClient

from flask import Flask, flash, render_template, request, redirect, send_file, url_for, Response
from celery import Celery

app = Flask(__name__)
app.config.from_object("config")
app.secret_key = app.config['SECRET_KEY']

# set up celery client

client = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])

# client.conf.update(app.config)

@client.task
def process(data):
    """ need to send the progress
    """

@app.route('/', methods=['GET'])
def index():
    csvfile = open('sample.csv', 'r')
    reader = csv.DictReader(csvfile)
    client = MongoClient("mongodb+srv://xyz:abc@tsds-dff.mongodb.net/test?retryWrites=true&w=majority")
    # db.Product.drop()
    header = ["Order ID", "Country", "Item Type", "Region"]
    database = client['test']
    collection = database['Products']
    for each in reader:
        row = {}
        for field in header:
            row[field] = each[field]
        print(row)
        collection.insert(row)
    return "success"

if __name__ == '__main__':
    app.run(debug=True)

这是我的配置文件

CELERY_BROKER_URL = 'redis://localhost:6379/0'
CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'

请帮助我如何在后台使用celery 进行上传过程,以及如何在ui中绑定以显示该过程?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题