Python和Flask试图让函数返回一个文件conten

2024-04-26 23:36:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力将文件内容返回给用户。有一个Flask代码,它从用户那里接收一个txt文件,然后调用Python函数transform()来解析infile,这两个代码都在执行任务。在

当我试图将新文件(outfile)发送(返回)给用户时,这个问题就发生了,Flask代码也可以正常工作。 但我不知道如何让Python transform function()返回文件内容,已经测试了几个选项。在

以下详细信息:

def transform(filename):

    with open(os.path.join(app.config['UPLOAD_FOLDER'],filename), "r") as infile:
        with open(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_1st.txt'), "w") as file_parsed_1st:

            p = CiscoConfParse(infile)
            ''' 
            parsing the file uploaded by the user and 
            generating the result in a new file(file_parsed_1st.txt)  
            that is working OK
            '''

    with open (os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_1st.txt'), "r") as file_parsed_2nd:
        with open(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt'), "w") as outfile:
            '''
            file_parsed_1st.txt is a temp file, then it creates a new file (file_parsed_2nd.txt)
            That part is also working OK, the new file (file_parsed_2nd.txt) 
            has the results I want after all the parsing;
            Now I want this new file(file_parsed_2nd.txt) to "return" to the user
            '''

    #Editing -  
    #Here is where I was having a hard time, and that now is Working OK
    #using the follwing line:

        return send_file(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt')) 

Tags: 文件thepathtxtconfigappisos
1条回答
网友
1楼 · 发布于 2024-04-26 23:36:38

您确实需要使用^{} callable来生成正确的响应,但需要传入一个文件名或一个尚未关闭或即将关闭的文件对象。所以在完整路径中传递可以:

return send_file(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt'))

当您传入一个file对象时,您不能使用with语句,因为当您从视图返回时,它将关闭file对象;只有当响应对象作为WSGI响应处理时,才会实际读取它,而WSGI响应是在view函数的之外。在

如果您想向浏览器建议一个文件名以将文件另存为,您可能需要传入一个attachment_filename参数;这也有助于确定mimetype。您还可以使用mimetype参数显式指定mimetype。在

您也可以使用^{} function;它的作用是相同的,但需要一个文件名和一个目录:

^{pr2}$

同样的关于mimetype的警告也适用;对于.txt,默认的mimetype将是text/plain。该函数实质上连接目录和文件名(使用^{},它应用额外的安全检查以防止使用..构造跳出目录),并将其传递给flask.send_file()。在

相关问题 更多 >