简体   繁体   中英

How do you run a python script using html button (flask)

I am trying to run a python script using html button in flask. I want it so that when the users press the button in html, the script which sends email in python will run.

This is the HTML portion. I want the python script to run when the user press the submit button.

<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>

And this is the python script.

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)

Please take a look at this docs

You can't just place button without any form. Or you have to place simple link like:

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

You should access the route with javascript.

Checkout AJAX with jQuery:

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

Here's a very similar question:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM