我有一个脚本("script2.py"),它接受特定类型的HTML文件,抓取一些内容,并在txt输出文件中对其进行总结。我正在构建一个烧瓶应用程序,让用户上传一个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)
发布于 2021-04-14 23:51:33
我知道这是怎么回事了。有几个问题。
.。
发布于 2021-04-09 03:33:07
,
app.response_class
,但是实际上没有自定义的响应类,所以我想知道为什么要这样做。为什么不使用app.make_response()
script2.run_script_in_web_app
正在返回一个BeautifulSoup对象,而不是文件的实际内容。你必须做soup.body()
https://stackoverflow.com/questions/66986820
复制相似问题