Fab*_*ima 2 python return file flask
我正在努力将文件内容返回给用户。有一个从用户那里接收 txt 文件的 Flask 代码,然后调用 Python 函数 transform() 来解析 infile,这两个代码都在做这项工作。
当我尝试将新文件 (outfile) 发送(返回)给用户时,问题发生了,用于该文件的 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')) 
您确实需要使用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()功能;它做同样的事情,但需要一个文件名和一个目录:
return send_from_directory(app.config['UPLOAD_FOLDER'], 'file_parsed_2nd.txt')
关于 mimetype 的警告同样适用;为.txt默认的MIME类型会text/plain。该函数本质上连接目录和文件名(通过flask.safe_join()它应用额外的安全检查以防止使用..构造破坏目录)并将其传递给flask.send_file().
| 归档时间: | 
 | 
| 查看次数: | 5132 次 | 
| 最近记录: |