如何使用Flask响应返回TXT文件



我有一个脚本("script2.py"(,它接受一种特定类型的HTML文件,抓取一些内容,并将其汇总到txt输出文件中。我正在构建一个flask应用程序,它将允许用户上传一个HTML文件,运行脚本,然后在他们点击"后返回一个txt输出文件作为响应;提交";。这些文件非常小,我想避免在运行脚本时将它们保存在任何地方有没有办法向用户提供一个带有烧瓶响应的txt文件

使用下面的代码,我可以上传一个文件并返回一个txt文件作为响应,但该文件只包含这些行。。。

xml version="1.0" encoding="UTF-8"?
html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd"

在堆栈中,将打印以下错误消息。

AssertionError: applications must write bytes
During handling of the above exception, another exception occurred:
...
TypeError: 'NoneType' object is not callable

我的网络应用程序的代码如下。";run_script_in_web_app"我调用的函数是将HTML文件转换为txt文件的脚本部分。

from flask import Flask, render_template, request, Response, make_response
import script2
app = Flask(__name__)
@app.route('/')
def display_home():
return render_template("home.html")
@app.route('/upload', methods=["GET", "POST"])
def upload_and_run():
uploaded_file = request.files['file']
file_name = uploaded_file.filename
file_contents = uploaded_file.stream.read().decode("utf-8")
result = script2.run_script_in_web_app(file_name, file_contents)
response = app.response_class(response=result, status=200, mimetype='application/txt')
return response
if __name__ == '__main__':
app.run()

我意识到这种方法目前是不安全的,因为它没有验证用户输入。我只是想让事情在本地主机上端对端地运行,然后再把所有这些东西分层。

我已经运行了一些测试,并且非常确信脚本的部分";上游";的响应正在工作(测试HTML文件不是空的,上传正在工作,script2能够打开文件,等等(

我正在调用的函数如下所示。评论指出了每一行中发生的事情。

这是我正在调用的script2中的函数。

def run_script_in_web_app(filename, file_contents):
global soup
name = filename
# Convert the HTML file contents into a Beautiful Soup object. 
soup = BeautifulSoup(file_contents)
return soup
# Creates a dictionary that contains an "author" value extracted from the HTML input file.
extracted_authors = parse_authors(soup)
# Pulls contents from "header" divs with a certain ID in the input file.
parse_headers(soup)
# Pulls contents from "body" divs with a certain ID in the input file. 
parse_bodies(soup)
# Creates a list of dictionaries from header div contents. 
extracted_heads = extract_headers(header_divs)
# Creates a list of dictionaries from body div contents. 
extracted_bodies = extract_body(body_divs)
# Combines the header and body dictionaries together into a single list of dictionaries. 
heads_and_bodies = merge_heads_with_bodies(extracted_heads, extracted_bodies)
# Writes the list of dictionaries and the "author" dictionary together in a .txt file for display to the end user. 
output_file = dict_writer(extracted_authors, heads_and_bodies, name)
return (output_file)
  1. 我看到你在做app.response_class,但实际上你没有自定义响应类,所以我想知道你为什么这么做。为什么不app.make_response()
  2. 但我认为问题在于您的代码——script2.run_script_in_web_app返回的是BeautifulSoup对象,而不是文件的实际内容。你必须做soup.body()

我弄清楚了这里发生了什么。有几个问题。

  1. 正如@NoCommandLine所指出的,我的";run_script_in_web_app"函数有两个返回语句,所以它只是返回一个漂亮的汤对象,而不是我认为会返回的输出文件。

  2. ";dict_writer";我调用的函数";run_script_in_web_app"将输出文件写入磁盘。相反,我需要将输出写入一个结果,并将其返回到Flask。

最新更新