python - 尝试上传图像时,Flask 应用程序会提供 500(内部服务器错误)页面(没有任何错误回溯)。我究竟做错了什么?
问题描述
我目前正在尝试构建一个烧瓶应用程序,它将接受上传的图像,允许用户对该图像应用过滤器,然后让用户查看他们上传和过滤的图像库。我有一个名为upload()
, 和一个 template的方法upload.html
,它们打印在下面的代码片段中 - 我已经尝试了三个不同版本的upload()
基于教程的在烧瓶中上传图像的方法,每个版本都有相同的结果。带有表单的上传模板正常加载,我上传了一张图片,然后出现内部服务器错误。我回到我的 IDE 中的终端(我使用的是 CS50 IDE)来检查错误来自哪里,并且没有任何回溯。
奇怪的是,我在第二次和第三次尝试的基础上实现了这一点,我看过的教程,其中完全相同的实现工作得很好。
这是 HTML 模板:
{% extends "layout.html" %}
{% block title %}
Upload
{% endblock %}
{% block main %}
<form action="/upload" method="post" enctype=multipart/form-data>
<input type="file" name="image">
<input type="submit" value="Upload">
</form>
{% endblock %}
第一个版本upload()
:
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template("upload.html")
if request.files:
#The POST request came through with an image file.
image = request.files['image']
if image.filename == "":
print("No filename")
return redirect("/upload")
if image and allowed_image(image.filename):
filename = secure_filename(image.filename)
image.save(os.path.join(app.config['IMAGE_UPLOADS'], filename))
print("Image saved.")
return redirect("/")
else:
print("That file extension is not allowed")
return redirect("/upload")
else:
print("Not request.files")
return render_template("upload.html")
第二个,为此photos = UploadSet('photos', IMAGES)
,使用flask_uploads
扩展名:
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo'])
print(filename)
return redirect("/")
return render_template('upload.html')
第三个:
def upload():
if request.method == 'POST':
target = os.path.join(APP_ROOT, "images/")
print(target)
if not os.path.isdir(target):
os.mkdir(target)
for file in request.files.getlist("image"):
print(file)
filename = file.filename
destination = "/".join([target, filename])
print(destination)
file.save(destination)
return render_template("index.html")
else:
return render_template("upload.html")
这是上传屏幕的图像
内部服务器错误
解决方案
flask_uploads
使用[ pip install flask_uploads
]很容易上传文件。有了它,您不必编写样板代码来上传文件。注意 - 您可能必须安装特定版本的 werkzeug pip install werkzeug==0.16.0
,以防遇到“无法从 'werkzeug' 导入名称 'secure_filename'”的问题
这是我在 GitHub 上找到的一个示例。 https://gist.github.com/greyli/addff01c19ddca78cddf386800e57045
推荐阅读
- javascript - 离子弹出按钮
- ios - 在 Swift 中将复杂的 JSON 保存到 Core Data
- spring - Spring Cloud Stream生产者批处理
- docker - Identityserver4 openid-configuration 省略了运行 nginx 反向代理的主机端口
- python - 流控制和失败:不允许数据库访问,使用“django_db”....错误
- spring - 使用 resultSetMapping 在外部属性文件中存储本机查询的值
- git - 远程 git 存储库中的文件重命名失败
- javascript - 2个不同大小的数组,一旦达到最大索引,就可以在循环中重用一个数组
- kendo-ui - 在 Kendo for Angular 中将上下文菜单添加到对话框
- typescript - 如何编写接受实现接口的类作为参数的 TypeScript 函数?