如何使用html按钮(flask)

时间:2018-02-04 14:43:09

标签: python html flask

我正在尝试使用烧瓶中的html按钮运行python脚本。我想要它,以便当用户按下html中的按钮时,将在python中发送电子邮件的脚本将运行。

这是HTML部分。我希望当用户按下提交按钮时运行python脚本。

<div class="container">
<h1 class="brand"><span>Haze</span> Alertion</h1>
<div class="wrapper">
  <div class="company-info">
    <h3>Haze Warning Signup</h3>
    <ul>
      <li><i class="fa fa-road"></i> Polytechnic</li>
      <li><i class="fa fa-phone"></i> 1234-5678</li>
      <li><i class="fa fa-envelope"></i> smartlifestyle@hotmail.com</li>
    </ul>
  </div>
  <div class="contact">
    <h3>Registration</h3>
    <div class="alert">Your message has been sent</div>
    <form id="contactForm">
      <p>
        <label>Name</label>
        <input type="text" name="name" id="name" required>
      </p>
      <p>
        <label>Location</label>
        <input type="text" name="company" id="company">
      </p>
      <p>
        <label>Email Address</label>
        <input type="email" name="email" id="email" required>
      </p>
      <p>
        <label>Repeat Email Address</label>
        <input type="email" name="phone" id="phone">
      </p>
      <p class="full">
        <label>Any Special Instructions</label>
        <textarea name="message" rows="5" id="message"></textarea>
      </p>
      <p class="full">
        <button type="submit">Submit</button>
      </p>
    </form>
  </div>
</div>

这是python脚本。

import smtplib
import config
import data
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/Email_Signup')
def Email_signup():
    return render_template('Email_Signup(PSI).html')

def send_email(subject, msg):
    try:
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.ehlo()
        server.starttls()
        server.login(config.EMAIL_ADDRESS, config.PASSWORD)
        message = 'Subject: {}\n\n{}'.format(subject, msg)
        server.sendmail(config.EMAIL_ADDRESS, data.EMAIL_ADDRESS, message)
        server.quit()
        print("Success: Email sent!")
    except:
        print("Email failed to send.")

subject = "Haze Warning"
msg = "Brave yourselves, Haze is coming!"

send_email(subject, msg)

2 个答案:

答案 0 :(得分:0)

请查看this docs

你不能只是没有任何形式的按钮。 或者你必须放置简单的链接:

<a href="/Email_Signup">Email Signup</a>

答案 1 :(得分:0)

您应该使用javascript访问该路线。

使用jQuery检出AJAX:

http://flask.pocoo.org/docs/0.12/patterns/jquery/

这是一个非常相似的问题:

How to make server side code run when a button is cliked?