article

Tuesday, January 25, 2022

Python Flask Vuejs CRUD (Create, Read, Update and Delete) with Mysql

Python Flask Vuejs CRUD (Create, Read, Update and Delete) with Mysql


https://bootstrap-vue.org/

https://bootstrap-vue.org/docs/components/modal#modals

https://vuejs.org/v2/guide/

Install Flask-CORS extension https://flask-cors.readthedocs.io/

$ pip install -U flask-cors
from flask_cors import CORS

https://github.com/axios/axios

CREATE TABLE `members` (
  `id` int(11) NOT NULL,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  `address` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `members` (`id`, `firstname`, `lastname`, `address`) VALUES
(1, 'Airi', 'Satou', 'Tokyo'),
(2, 'Angelica ', 'Ramos', 'London'),
(3, 'Ashton ', 'Cox', 'San Francisco'),
(4, 'Bradley', 'Greer', 'London'),
(5, 'Brenden ', 'Wagner', 'San Francisco'),
(40, 'Brielle', 'Williamson', 'New York'),
(54, 'Bruno', 'Nash', 'London'),
(55, 'Caesar', 'Vance', 'New York'),
(56, 'Cara', 'Stevens', 'New York'),
(57, 'Cedric', 'Kelly', 'Edinburgh'),
(58, 'Zorita Serran', 'Satou', 'Tokyo'),
(59, 'Angelica ', 'Ramos', 'London'),
(60, 'Ashton ', 'Cox', 'San Francisco'),
(61, 'Bradley ', 'Greer', 'London'),
(62, 'Brenden ', 'Wagner', 'San Francisco'),
(63, 'Brielle', 'Williamson', 'New York'),
(64, 'Bruno', 'Nash', 'London'),
(65, 'Caesar', 'Vance', 'New York'),
(66, 'Cara', 'Stevens', 'New York'),
(67, 'Brenden ', 'Wagner', 'San Francisco'),
(68, 'Brielle', 'Williamson', 'New York'),
(69, 'Bruno', 'Nash', 'London'),
(70, 'Caesar', 'Vance', 'New York'),
(71, 'Cara', 'Stevens', 'New York'),
(72, 'Cedric', 'Kelly', 'Edinburgh');

ALTER TABLE `members`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `members`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=73;
crud.html
//crud.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />
<title>Python Flask Vuejs CRUD (Create, Read, Update and Delete) with PHP Mysql</title>
</head>
<body>
<div class="container" id="vuejscrudapp">
	<div class="row">
        <div class="col-md-12 mt-5">
          <h1 class="text-center">Python Flask Vuejs CRUD (Create, Read, Update and Delete) with PHP Mysql</h1>
          <hr>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
          <!-- Add Records -->
        <div>
            <b-button id="show-btn" @click="showModal('my-modal')">Add Records</b-button>
 
            <b-modal ref="my-modal" hide-footer title="Add Records">
              <div>
                <form action="" @submit.prevent="onSubmit">
                  <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" v-model="firstname" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" v-model="lastname" class="form-control">
                  </div>
				  <div class="form-group">
                    <label for="">Address</label>
                    <input type="text" v-model="address" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Add Records</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal')">Close Me</b-button>
            </b-modal>
        </div>
 
        <!-- Update Record -->
        <div>
            <b-modal ref="my-modal1" hide-footer title="Update Record">
              <div>
                <form action="" @submit.prevent="onUpdate">
                  <div class="form-group">
                    <label for="">First Name</label>
                    <input type="text" v-model="edit_id">
                    <input type="text" v-model="edit_firstname" class="form-control">
                  </div>
                  <div class="form-group">
                    <label for="">Last Name</label>
                    <input type="text" v-model="edit_lastname" class="form-control">
                  </div>
				  <div class="form-group">
                    <label for="">Address</label>
                    <input type="text" v-model="edit_address" class="form-control">
                  </div>
                  <div class="form-group">
                    <button class="btn btn-sm btn-outline-info">Update Record</button>
                  </div>
                </form>
              </div>
              <b-button class="mt-3" variant="outline-danger" block @click="hideModal('my-modal1')">Close Me</b-button>
            </b-modal>
          </div>
		  
        </div>
	</div>
	  
    <div class="row">
        <div class="col-md-12">
          <table class="table table-striped table-bordered">
            <thead>
              <tr>
                <th>ID</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Address</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(record, i) in records" :key="record.id">
                <td>{{i + 1}}</td>
                <td>{{record.firstname}}</td>
                <td>{{record.lastname}}</td>
                <td>{{record.address}}</td>
                <td>
                  <button @click="deleteRecord(record.id)" class="btn btn-sm btn-outline-danger">Delete</button>
                  <button @click="editRecord(record.id)" class="btn btn-sm btn-outline-info">Edit</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
    </div>
</div>
 
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<!-- BootstrapVue js -->
<script src="https://unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>
<!-- Axios -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
    var app = new Vue({
        el: '#vuejscrudapp',
        data: {
			firstname: '',
			lastname: '',
			address: '',
			records: [],
			edit_id: '',
			edit_firstname: '',
			edit_lastname: '',
			edit_address: ''
        },
 
        methods: {
			showModal(id) {
				this.$refs[id].show()
			},
			hideModal(id) {
				this.$refs[id].hide()
			},
 
			onSubmit(){
				if (this.firstname !== '' && this.lastname !== '' && this.address !== '') {
					var config = { headers: {  
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'}
					}
					axios.post("http://127.0.0.1:5000/insert", 
						{ firstname : this.firstname, lastname : this.lastname, address : this.address}, config
					)
					.then(res => {
						console.log(res)
						alert('New record Successfully added')
						this.firstname = ''
						this.lastname = ''
						this.address = ''
		 
						app.hideModal('my-modal')
						app.getRecords()
					})
					.catch(err => {
						console.log(err)
					})
				}else{
				  alert('empty')
				}
			},
 
			getRecords(){
				axios({
				  url: 'http://localhost:5000/',
				  method: 'get'
				})
				.then(res => {
				  console.log(res)
				  this.records = res.data.members
				})
				.catch(err => {
				  console.log(err)
				})
			},
 
			editRecord(id){
				axios.get("http://127.0.0.1:5000/edit/" + id)
				.then(res => {
					console.log(res.data)
				    this.edit_id = res.data.editmember['id']
				    this.edit_firstname = res.data.editmember['firstname']
				    this.edit_lastname = res.data.editmember['lastname']
				    this.edit_address = res.data.editmember['address']
					app.showModal('my-modal1')
				})
				.catch(err => {
				  console.log(err)
				})
			},
			
			onUpdate(){
				if (this.edit_firstname !== '' && this.edit_lastname !== '' && this.edit_address !== '' && this.edit_id !== '') {

				    var config = { headers: {  
						'Content-Type': 'application/json',
						'Access-Control-Allow-Origin': '*'}
					}
					axios.post("http://127.0.0.1:5000/update", 
						{ edit_id : this.edit_id, edit_firstname : this.edit_firstname, edit_lastname : this.edit_lastname, edit_address : this.edit_address}, config
					)
					.then(res => {
						console.log(res)
						alert('record update');
		 
						this.edit_firstname = '';
						this.edit_lastname = '';
						this.edit_address = '';
						this.edit_id = '';
		 
						app.hideModal('my-modal1');
						app.getRecords();
					})
					  .catch(err => {
						console.log(err)
					})
	 
				}else{
				  alert('empty')
				}
			},
			
			deleteRecord(id){
				if (window.confirm('Delete this record')) {
					axios.get("http://127.0.0.1:5000/delete/" + id)
					.then(res => {
						console.log(res)
						alert('delete successfully')
						app.getRecords();
					})
					.catch(err => {
						console.log(err)
					})
				}
			},
		
        },
		  
        mounted: function(){
          this.getRecords()
        }
    })
</script>
</body>   
</html>
app.py
//app.py
from flask import Flask, jsonify, request
from flask_cors import CORS
from flaskext.mysql import MySQL #pip install flask-mysql
import pymysql

MEMBERS = [
    {
        'id': '1',
        'firstname': 'cairocoders',
        'lastname': 'Ednalan',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'firstname': 'clydey',
        'lastname': 'Ednalan',
        'address': 'Angles city'
    }
]
# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)
    
mysql = MySQL()
   
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = ''
app.config['MYSQL_DATABASE_DB'] = 'testingdb'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)

# enable CORS
CORS(app, resources={r'/*': {'origins': '*'}})


# sanity check route
@app.route('/ping', methods=['GET'])
def ping_pong():
    return jsonify('pong!')

@app.route('/members', methods=['GET'])
def all_members():
    return jsonify({
        'status': 'success',
        'members': MEMBERS
    })

@app.route('/')
def home():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    try:
        cursor.execute("SELECT * from members order by id")
        userslist = cursor.fetchall()
        return jsonify({
            'status': 'success',
            'members': userslist
        })
    except Exception as e:
        print(e)
    finally:
        cursor.close() 
        conn.close()

@app.route('/insert', methods=['GET', 'POST'])
def insert():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json(silent=True)
        firstname = post_data.get('firstname')
        lastname = post_data.get('lastname')
        address = post_data.get('address')

        print(firstname)
        print(lastname)

        sql = "INSERT INTO members(firstname,lastname,address) VALUES(%s, %s, %s)"
        data = (firstname, lastname, address)
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute(sql, data)
        conn.commit()

        response_object['message'] = "Successfully Added"
    return jsonify(response_object)

@app.route('/edit/<string:id>', methods=['GET', 'POST'])
def edit(id):
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    print(id)
    cursor.execute("SELECT * FROM members WHERE id = %s", [id])
    row = cursor.fetchone() 

    return jsonify({
        'status': 'success',
        'editmember': row
    })

@app.route('/update', methods=['GET', 'POST'])
def update():
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    response_object = {'status': 'success'}
    if request.method == 'POST':
        post_data = request.get_json(silent=True)
        edit_id = post_data.get('edit_id')
        edit_firstname = post_data.get('edit_firstname')
        edit_lastname = post_data.get('edit_lastname')
        edit_address = post_data.get('edit_address')

        print(edit_firstname)
        print(edit_lastname)

        cursor.execute ("UPDATE members SET firstname=%s, lastname=%s, address=%s WHERE id=%s",(edit_firstname, edit_lastname, edit_address, edit_id))
        conn.commit()
        cursor.close()

        response_object['message'] = "Successfully Updated"
    return jsonify(response_object)

@app.route('/delete/<string:id>', methods=['GET', 'POST'])
def delete(id):
    conn = mysql.connect()
    cursor = conn.cursor(pymysql.cursors.DictCursor)
  
    response_object = {'status': 'success'}

    cursor.execute("DELETE FROM members WHERE id = %s", [id])
    conn.commit()
    cursor.close()
    response_object['message'] = "Successfully Deleted"
    return jsonify(response_object)

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

Related Post