从HTML表单获取输入并通过Flask将其存储在mysql中

时间:2017-03-08 03:34:53

标签: python html mysql flask

我在python中迈出了第一步。我正在使用Flask框架,我正在编写一个基本应用程序,它将从html表单中获取输入并将其存储在表MySql数据库中。所以这就是我在做什么

html表单sample.html:

 <!DOCTYPE html>
  <html>
  <body>

  <form method="POST">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  Email Id : <input type="text" name="emailid"><br>
 <input type="submit" value="Submit">
 </form>

</body>
</html>

我正在使用的python脚本是:

from flask import Flask,request,render_template
from flaskext.mysql import MySQL
mysql=MySQL()

app=Flask(__name__)
app.config['MYSQL_DATABASE_USER']='root'
app.config['MYSQL_DATABASE_PASSWORD']='root'
app.config['MYSQL_DATABASE_DB']='names'
app.config['MYSQL_DATABASE_host']='127.0.0.1:3306'
mysql.init_app(app)

@app.route('/',methods=['GET','POST'])
def get_data():
 return render_template("sample.html")
  if request.method=='POST':
    first_name=request.form['fname']
    last_name=request.form['lname']
    emailid=request.form['emailid']
    connection = mysql.get_db()
    cursor = connection.cursor()
 query="INSERT INTO names_tbl(f_name,l_name,e_id) VALUES(%s,%s,%s)"
 cursor.execute(query,(first_name,last_name,email_id))
    connection.commit()
    return "nothing fucked"
else:
    return("something fucked up")

if __name__=='__main__':
app.run(debug=True)

2 个答案:

答案 0 :(得分:0)

@app.route('/',methods=['GET','POST'])
def get_data():
  if request.method=='POST':
    first_name=request.form['fname']
    last_name=request.form['lname']
    emailid=request.form['emailid']
    connection = mysql.get_db()
    cursor = connection.cursor()
    query="INSERT INTO names_tbl(f_name,l_name,e_id) VALUES(%s,%s,%s)"
    cursor.execute(query,(first_name,last_name,email_id))
    connection.commit()

 return render_template("sample.html")

if __name__=='__main__':
app.run(debug=True)

答案 1 :(得分:0)

import MySQLdb

db = MySQLdb.connect(
    host = 'localhost',
    user = 'root',
    passwd = 'pw',
    db = 'mydB',
    charset='utf8'
    )

@app.route('/',methods=['GET','POST'])
def get_data():
 return render_template("sample.html")
  if request.method=='POST':
    first_name=request.form['fname']
    last_name=request.form['lname']
    emailid=request.form['emailid']
    cursor = db.cursor()
    cursor.execute("""
    INSERT INTO names_tbl(f_name,l_name,e_id) \
    VALUES (%s,%s,%s) """, (first_name,last_name,email_id))
    cursor.close()
    return "nothing fucked"

if __name__=='__main__':
app.run(debug=True)