【问题标题】:Python and Flask - Trying to have a function return a file contentPython 和 Flask - 试图让函数返回文件内容
【发布时间】:2015-06-02 03:00:39
【问题描述】:

我正在努力将文件内容返回给用户。有一个从用户接收 txt 文件的 Flask 代码,然后调用 Python 函数 transform() 来解析 infile,这两个代码都在做这项工作。

当我尝试将新文件(输出文件)发送(返回)给用户时,问题正在发生,Flask 代码也可以正常工作。 但我不知道如何让这个 Python 转换函数()“返回”该文件内容,已经测试了几个选项。

以下详细信息:

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')) 

【问题讨论】:

    标签: python file flask return


    【解决方案1】:

    您确实需要使用flask.send_file() callable 来产生正确的响应,但需要传入尚未关闭或即将关闭的文件名或文件对象。所以传入完整路径就可以了:

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

    当你传入一个文件对象时,你不能使用with 语句,因为它会在你从视图返回的那一刻关闭文件对象;只有当响应对象被处理为 WSGI 响应时,它才会被实际读取,在您的视图函数之外

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

    您也可以使用flask.send_from_directory() function;它的作用相同,但需要一个文件名和一个目录:

    return send_from_directory(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt')
    

    关于 mimetype 的警告同样适用;对于.txt,默认mimetype 为text/plain。该函数实质上连接了目录和文件名(flask.safe_join() 应用额外的安全检查以防止使用.. 结构破坏目录)并将其传递给flask.send_file()

    【讨论】:

    • 嗨 Martijn Pieters,非常感谢。我刚刚按照您的建议用新测试编辑了问题。
    • @FabianoLima 在您调用send_file() 时是否关闭了文件(您在with 块之外)?该文件需要完全写入,因此刷新到磁盘,因此可以在响应中设置正确的大小。
    • 刚刚又测试了一遍,“return send_file(os.path.join(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt'))”这行在最后一个“with block”里面",现在已经放在了相同的级别(缩进),Python transform() 现在正在将文件发送到 Flask 代码完成其余的工作(解析的文件现在正在下载给用户)。再次非常感谢您的大力帮助!
    猜你喜欢
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 2022-01-07
    • 2016-03-31
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多