├── README.md ├── app.py ├── db.yaml ├── requirements.txt └── templates ├── index.html └── users.html /README.md: -------------------------------------------------------------------------------- 1 | Clone this project 2 | 3 | pip3 install -r requirements.txt 4 | 5 | Change the password in db.yaml to that of your MySQL's password 6 | 7 | Run the application by executing the command python3 app.py 8 | 9 | The application runs on localhost:5000 10 | -------------------------------------------------------------------------------- /app.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template, request, redirect 2 | from flask_mysqldb import MySQL 3 | import yaml 4 | 5 | app = Flask(__name__) 6 | 7 | # Configure db 8 | db = yaml.load(open('db.yaml')) 9 | app.config['MYSQL_HOST'] = db['mysql_host'] 10 | app.config['MYSQL_USER'] = db['mysql_user'] 11 | app.config['MYSQL_PASSWORD'] = db['mysql_password'] 12 | app.config['MYSQL_DB'] = db['mysql_db'] 13 | 14 | mysql = MySQL(app) 15 | 16 | @app.route('/', methods=['GET', 'POST']) 17 | def index(): 18 | if request.method == 'POST': 19 | # Fetch form data 20 | userDetails = request.form 21 | name = userDetails['name'] 22 | email = userDetails['email'] 23 | cur = mysql.connection.cursor() 24 | cur.execute("INSERT INTO users(name, email) VALUES(%s, %s)",(name, email)) 25 | mysql.connection.commit() 26 | cur.close() 27 | return redirect('/users') 28 | return render_template('index.html') 29 | 30 | @app.route('/users') 31 | def users(): 32 | cur = mysql.connection.cursor() 33 | resultValue = cur.execute("SELECT * FROM users") 34 | if resultValue > 0: 35 | userDetails = cur.fetchall() 36 | return render_template('users.html',userDetails=userDetails) 37 | 38 | if __name__ == '__main__': 39 | app.run(debug=True) 40 | -------------------------------------------------------------------------------- /db.yaml: -------------------------------------------------------------------------------- 1 | mysql_host: 'localhost' 2 | mysql_user: 'root' 3 | # Enter your password in field below 4 | mysql_password: '******' 5 | mysql_db: 'flaskapp' 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | flask 2 | flask-mysqldb 3 | -------------------------------------------------------------------------------- /templates/index.html: -------------------------------------------------------------------------------- 1 |
2 | Name 3 |
4 | Email 5 |
6 | 7 |
8 | -------------------------------------------------------------------------------- /templates/users.html: -------------------------------------------------------------------------------- 1 | 2 | {% for user in userDetails %} 3 | 4 | 5 | 6 | 7 | {% endfor %} 8 |
{{user[0]}} {{user[1]}}
9 | --------------------------------------------------------------------------------