简体   繁体   English

使用 Python Flask 从字符串变量中读取并上传 .txt 文件?

[英]Reading from a string variable and uploading a .txt file using Python Flask?

I'm trying to build a web app using Python and Flask to convert .JSON to .CSV format.我正在尝试使用 Python 和 Flask 构建一个 Web 应用程序,以将 .JSON 转换为 .CSV 格式。

Here's how it should work.这是它应该如何工作。 The app programmatically downloads a JSON file from an API and I need to convert to .CSV format and when the user visits the link, it should convert the JSON to .CSV and it should be downloaded automatically and save it in the user's local disk.该应用程序以编程方式从 API 下载 JSON 文件,我需要转换为 .CSV 格式,当用户访问链接时,它应该将 JSON 转换为 .CSV 并且应该自动下载并将其保存在用户的本地磁盘中。

Initially, my approach was to download the JSON file in the servers local disk and convert it to CSV file by creating a new file and by using send_file, the user can download the CSV file.最初,我的方法是将 JSON 文件下载到服务器本地磁盘中,然后通过创建新文件将其转换为 CSV 文件,然后使用 send_file 用户可以下载 CSV 文件。

But, since I deployed into Heroku and I realized the Heroku filesystem is temporary and I can't store any files.但是,自从我部署到 Heroku 后,我意识到 Heroku 文件系统是临时的,我无法存储任何文件。 I had to change the file concept and convert it by storing it to a string variable.我不得不改变文件概念并通过将其存储为字符串变量来转换它。

This is how my code looks now after deploying to heroku.这就是我的代码在部署到 heroku 后的样子。

from flask import Flask,render_template,send_file
import requests
import os
import csv
import json
#import urllib.request



app = Flask(__name__,template_folder='templates')

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/jsonParser')
def jsonParser():
    download_url = "https://www....." #link to .JSON file.

    r = requests.get(download_url)
    x = json.loads(r.content)
    outputArray =  ["id", "phones", "email", "firstname", "lastname","role","username","isActive","_created_at","_updated_at"]
    output = ','.join(outputArray)

        try:
            idValue = x["id"] or x["_id"]
            idValue = str(idValue)
        except:
            idValue = x["_id"] or "nil"

        output2 =   ",".join([ idValue ,
                        x["phones"] or "nil",
                        x["email"] or "nil",
                        x["firstname"] or "nil",
                        x["lastname"] or "nil",
                        str(x["role"]) or "nil",
                        x["username"] or "nil",
                       str(x["isActive"]) or "nil" ,

                        str(x["_created_at"]) or "",
                        str(x["_updated_at"]) or ""]) 
        output =  output + "<br>" + output2 #'\n'.join([output, output2])


    return output


if __name__ == "__main__":
    app.run(debug=True,threaded=True)

So now, the output variable consists of the converted .CSV.所以现在, output变量由转换后的 .CSV 组成。 I'm wondering if there's any way that I can convert it to .txt file so that the user can download it by visiting /jsonParser without storing the .txt file on the server-side.我想知道是否有任何方法可以将其转换为 .txt 文件,以便用户可以通过访问 /jsonParser 下载它,而无需将 .txt 文件存储在服务器端。

Is that what you wanted to do?那是你想做的吗? Can you try it like that:你可以这样试试吗:

from io import StringIO
from flask import Response

@app.route('/jsonParser')
def jsonParser():

    ...

    output = output + "<br>" + output2  # '\n'.join([output, output2])

    string_out = StringIO()
    string_out.write(output)

    returnfile = string_out.getvalue()

    return Response(returnfile, mimetype="text/plain", headers={"Content-disposition": "attachment; filename=output.txt"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM