-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflaskwithMySQL.py
39 lines (34 loc) · 1.18 KB
/
flaskwithMySQL.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#importing the needed packages and modules
from flask import Flask, render_template, request, redirect
from flask_mysqldb import MySQL
import yaml
app = Flask(__name__)
#Configure db
db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASS'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql = MySQL(app)
@app.route('/', methods=['GET','POST'])
def hello():
if request.method == 'POST':
#Fetch form data
userDetails = request.form
name = userDetails['name']
email = userDetails['email']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO users(name, email) VALUES(%s, %s)",(name, email))
mysql.connection.commit()
cur.close()
return redirect('/users')
return render_template('index.html')
@app.route('/users')
def users():
cur = mysql.connection.cursor()
resultValue = cur.execute("SELECT * FROM users")
if resultValue > 0:
userDetails = cur.fetchall()
return render_template('users.html',userDetails=userDetails)
if __name__ == '__main__':
app.run(debug=True, host='localhost')