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

x33g5p2x  于 2023-04-04  发布在  Mysql
关注(0)|答案(2)|浏览(96)

我正在学习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)
o2rvlv0m

o2rvlv0m1#

@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)
nxagd54h

nxagd54h2#

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)

相关问题