Flask - 使用 sendgrid 上传 Wtforms 文件 API

Flask - Wtforms file upload with sendgrid API

我正在制作一个相对简单的表单,其中包含一个文件输入字段。我显然希望将上传的文件附加到通过 Sendgrid python api 发送的电子邮件中。此时表单已成功发送,但我没有上传任何文件,这是我目前所做的:

HTML

<form action="" method="post" name="property_info" class="clearfix" enctype="multipart/form-data">
  ...really long form, but here is the file input field
  <input type="file" id="upfile">
  ...more input fields..
</form>

app.py

app.config['UPLOAD_FOLDER'] = config.UPLOAD_FOLDER
app.config['ALLOWED_EXTENSIONS'] = config.ALLOWED_EXTENSIONS

#Check if the uploaded excel file has one of the three allowed file extensions
def allowed_file(filename):
  return '.' in filename and \
          filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/', methods=['GET','POST'])
def index():
  form = forms.GeneralProperty()
  year = datetime.date.today().year


if form.validate_on_submit():
    print 'form is valid'
    #upload excel file if it's present
    print request.files
      if form.excel_file.data:
      print 'there is a file uploaded'
      file = request.files['file']
      print 'file is ' + str(file)

      if file and allowed_file(file.filename):
        print 'file is allowed'
        filename = secure_filename(file.filename)
        print 'filename is ' + filename
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #Send e-mail with attached excel file
        print 'going into email function'
        excel_email.send_mail(form, excel_file=filename)

    #Otherwise, ignore the excel file
    else:
      excel_email.send_mail(form)

    flash('Thanks for submitting the form ' + form.person_name.data.split(' ')[0] + '! We will be in contact with you shortly.', 'bg-success')

  elif form.errors:
    flash('There was an error submitting the form, please check that all required fields are filled in.', 'bg-danger')

  return render_template('index.html', form=form, year=year)

excel_email.py

#Setting up email send method
def send_mail(form, excel_file=None):
  sg = sendgrid.SendGridClient('username', 'password')

  print 'Starting mail process....'
  message = sendgrid.Mail()
  message.add_to(str(form.person_email.data))
  message.set_from('example@heroku.com')
  message.set_from_name(str(form.person_name.data))
  message.set_subject('Property Form Submission')
  message.set_html(...really long HTML email template with all form data...)

  #If the excel file is attached, attach it to the e-mail
  if excel_file:
    message.add_attachment(excel_file)

  status, msg = sg.send(message)

  print status
  print msg

本地主机 运行 时控制台的输出

form is valid
ImmutableMultiDict([])
Starting mail process....
200
{"message":"success"}

非常感谢您的建议:)

您需要为输入命名。在您看来,您得到 request.files['file'],因此输入必须具有名称 "file".

<input type="file" name="file"/>

由于您使用的是 WTForms,因此应该让它呈现该字段。

{{ form.file }}