我有一个 Python Web 应用程序,用户上传图像,代码从该图像生成 CSV。我需要的是将 csv 返回到 app.py 并将其显示在前端供用户下载。我如何实现这一目标?
应用程序.py
# Route to show processed files
@app.route('/view_process', endpoint='view_process')
def process_files():
if not session.get('logged_in'):
return redirect(url_for('login_user'))
subprocess.run(['python', 'inference.py'])
return render_template('view_process.html', message='Files processed sucessfully')
推理.py
from utils import *
processInputs(cfg, outputs, im_bgr_list, output_directory, im_names)
实用程序.py
def processInputs(cfg, outputs, im_bgr_list, output_directory, im_names):
getSegmentationCsv(outputs[i],im_bgr_list[i],im_names[i],output_directory)
def getSegmentationCsv(output,im_bgr,im_name, output_dir):
df = pd.concat([df1,df2],axis=1)
# Give the filename you wish to save the file to
filename = output_dir+im_name.split('.')[0] + '.csv'
# Use this function to search for any files which match your filename
files_present = glob.glob(filename)
# if no matching files, write to csv, if there are matching files, print statement
if not files_present:
df.to_csv(filename, index = False)
您必须使用 GET/POST 请求才能执行此操作。您可以使用基本的 HTTP 请求,这将重新加载整个页面,也可以使用 ajax,仅重新加载页面的某些部分。
如果使用 POST 方法,则必须将
methods=[GET,POST]
属性添加到 @app.route('/view_process', endpoint='view_process')
在您的
return
声明中,我看到您正在传递一个属性 message
,并且我假设前端收到了该消息。假设你使用Java Script接收消息,你可以传递另一个参数,例如path="filepath.csv"
,并在前端添加一个<a download></a>
标签,并动态地将href
属性更改为接收到的文件路径,在这种情况下,path
。
确保修改
utils.py
和 inference.py
将文件名返回为 app.py