gpt4 book ai didi

python - 文件未在 cookiecutter-flask 应用程序中使用 Flask-wtforms 上传

转载 作者:太空狗 更新时间:2023-10-29 17:34:28 25 4
gpt4 key购买 nike

我在上传文件时遇到问题 cookiecutter-flask应用程序(0.10.1 版)。现在,它没有保存上传的文件。

Cookiecutter-Flask 默认安装 WTForms 和 Flask-WTForms。我曾尝试向其中添加 Flask-Uploads,但我不相信模块此时会添加任何内容,因此我已将其卸载。这是 Flask-WTF 文件上传文档:http://flask-wtf.readthedocs.io/en/latest/form.html#module-flask_wtf.file

文档和我的应用程序之间的主要区别在于,我似乎拥有更多文件的信息,以符合 cookiecutter 的惯例。

app_name/spreadsheet/forms.py 中:

from flask_wtf import Form
from wtforms.validators import DataRequired
from flask_wtf.file import FileField, FileAllowed, FileRequired

class UploadForm(Form):
"""Upload form."""

csv = FileField('Your CSV', validators=[FileRequired(),FileAllowed(['csv', 'CSVs only!'])])

def __init__(self, *args, **kwargs):
"""Create instance."""
super(UploadForm, self).__init__(*args, **kwargs)
self.user = None

def validate(self):
"""Validate the form."""
initial_validation = super(UploadForm, self).validate()
if not initial_validation:
return False

app_name/spreadsheet/views.py 中:

from flask import Blueprint, render_template
from flask_login import login_required
from werkzeug.utils import secure_filename
from app_name.spreadsheet.forms import UploadForm
from app_name.spreadsheet.models import Spreadsheet
from app_name.utils import flash, flash_errors

blueprint = Blueprint('spreadsheet', __name__, url_prefix='/spreadsheets', static_folder='../static')

@blueprint.route('/upload', methods=['GET', 'POST']) #TODO test without GET since it won't work anyway
@login_required
def upload():
uploadform = UploadForm()
if uploadform.validate_on_submit():
filename = secure_filename(form.csv.data.filename)
uploadform.csv.data.save('uploads/csvs/' + filename)
flash("CSV saved.")
return redirect(url_for('list'))
else:
filename = None
return render_template('spreadsheets/upload.html', uploadform=uploadform)

这是我上传文件时没有显示错误的命令行输出:

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /spreadsheets/upload HTTP/1.1" 200 -
127.0.0.1 - - [04/Sep/2016 10:29:10] "GET /_debug_toolbar/static/css/toolbar.css?0.3058158586562558 HTTP/1.1" 200 -
127.0.0.1 - - [04/Sep/2016 10:29:14] "POST /spreadsheets/upload HTTP/1.1" 200 -
127.0.0.1 - - [04/Sep/2016 10:29:14] "GET /_debug_toolbar/static/css/toolbar.css?0.3790246965220061 HTTP/1.1" 200 -

对于 uploads/csvs 目录,我尝试了绝对路径和相对路径,该目录的权限为 766。

模板文件是:

{% extends "layout.html" %}
{% block content %}
<h1>Welcome {{ session.username }}</h1>

{% with uploadform=uploadform %}
{% if current_user and current_user.is_authenticated and uploadform %}
<form id="uploadForm" method="POST" class="" action="{{ url_for('spreadsheet.upload') }}" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<div class="form-group">
{{ uploadform.csv(class_="form-control") }}
</div>
<button type="submit" class="btn btn-default">Upload</button>
</form>
{% endif %}
{% endwith %}

{% endblock %}

生成此 HTML:

        <form id="uploadForm" method="POST" class="" action="/spreadsheets/upload" enctype="multipart/form-data">
<input type="hidden" name="csrf_token" value="LONG_RANDOM_VALUE"/>
<div class="form-group">
<input class="form-control" id="csv" name="csv" type="file">
</div>
<button type="submit" class="btn btn-default">Upload</button>
</form>

最佳答案

查看文档,您提供的链接表明 csvdata 字段是 werkzeug.datastructures.FileStorage 的一个实例。 FileStorage.save() 的文档建议:

If the destination is a file object you have to close it yourself after the call.

会不会因为你没有关闭文件,所以它没有被写入磁盘?

关于python - 文件未在 cookiecutter-flask 应用程序中使用 Flask-wtforms 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39318572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com