Flask:客户端如何下载创建的JSON文件 [英] Flask: how can a client download a created JSON file

查看:461
本文介绍了Flask:客户端如何下载创建的JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON字符串,我正在从Web表单读取,我想创建一个临时文件,并允许将文件下载到本地客户机。换句话说,我的app.route读取字符串,将字符串写入文件,然后将文件发送到客户端:

  @ app.route('/ sendFile',methods = ['POST'])
def sendFile():
content = str(request.form ['jsonval'])
with open ('zones.geojson','w')为f:
f.write(content)
return send_file(f)

使这项工作最好的方法是什么?

解决方案

From 这个回答所有这一切需要的是指定正确的响应标头:

$ $ $ $ $ $ $ $ $ $ $ $ $ app.route('/ sendFile',methods = ['POST'] )
def sendFile():
content = str(request.form ['jsonval'])
返回响应(content,
mimetype ='application / json',
headers = {'Content-Disposition':'att achment; filename = zones.geojson'})


I have a JSON string that I am reading from a web form that I would like to create a temporary file out of and allow the file to be downloaded to the local client machine. In other words my app.route reads the string, writes the string to a file and then sends the file to the client:

@app.route('/sendFile', methods=['POST'])
def sendFile():
    content = str(request.form['jsonval'])
    with open('zones.geojson', 'w') as f:
        f.write(content)
    return send_file(f)

What's the best way to make this work?

解决方案

From this answer all that is needed is to specify the correct Response header:

@app.route('/sendFile', methods=['POST'])
def sendFile():
    content = str(request.form['jsonval'])
    return Response(content, 
            mimetype='application/json',
            headers={'Content-Disposition':'attachment;filename=zones.geojson'})

这篇关于Flask:客户端如何下载创建的JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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