如何使用烧瓶从表单发送数据和文件?

HOw to send data and file from a form using flask?

我使用 html 和烧瓶创建了一个表格。用户将在其中填写他的姓名、地址和其他信息,并上传他的照片和其他文件。一旦用户填写信息并提交表格,他将被重定向到另一个页面,页面上有他自己填写的信息和照片。

我能够填写用户信息并将他重定向到另一个页面 "apply.html" 但是当我尝试上传照片时。它可以上传图片,但不会将我重定向到 "apply.html"

在我的 routes.py

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/form.html', methods=['POST'])
def upload_file():
    nform = NewRegistration(request.form)
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))


@app.route('/form.html', methods=['GET', 'POST'])
def form():
  nform = NewRegistration(request.form)
  if request.method == 'POST':
    if nform.validate() == False:
      flash('All fields are required.')
      return render_template('form.html', form=nform)
    else:
      post = request.form['element_15'].strip()  
      name = request.form['element_1_1'].strip()
      last = request.form['element_1_2'].strip()
      Name = str(name)+ ' ' +str(last)
      father = request.form['element_2'].strip()
      mother = request.form['element_3'].strip()
      gender = request.form['element_17'].strip()

      data = {'Name' : Name, 'post' : post, 'father' : father}

      return render_template("apply.html", data=data)

    elif request.method == 'GET':
      return render_template('form.html', form=nform)

我知道这个问题是因为两个函数 "upload_file" 和 "form" 所以建议我获取信息和照片的最佳方式并且能够将用户重定向到 apply.html

因为您需要在

中添加 render_template()
@app.route('/form.html', methods=['POST'])
def upload_file():
    // do something
    render_template("yourpage.html")

每条路线都必须return一个回应。 另外我建议使用相同的路径来保存文件+表单。

@app.route('/form.html', methods=['GET', 'POST'])
def form():
  nform = NewRegistration(request.form)
  if request.method == 'POST':
    if nform.validate() == False:
      flash('All fields are required.')
      return render_template('form.html', form=nform)
    else:

        try:
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        except Exception as e:
            print "Form without file "+e
        post = request.form['element_15'].strip()
        name = request.form['element_1_1'].strip()
        last = request.form['element_1_2'].strip()
        Name = str(name)+ ' ' +str(last)
        father = request.form['element_2'].strip()
        mother = request.form['element_3'].strip()
        gender = request.form['element_17'].strip()
        data = {'Name' : Name, 'post' : post, 'father' : father}
        return render_template("apply.html", data=data)

    elif request.method == 'GET':
      return render_template('form.html', form=nform)

如果有帮助请告诉我。