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
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
//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>
  
<!-- BootstrapVue js -->
<!-- Axios -->
<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
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//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