article

Tuesday, January 11, 2022

Python Flask Vue.js Axios - List All Data

Python Flask Vue.js Axios - List All Data

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

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

We'll be using the Vue CLI  https://cli.vuejs.org/

$ vue create client
This will require you to answer a few questions about the project.

Vue CLI v4.5.11
? Please pick a preset: (Use arrow keys)
❯ Default ([Vue 2] babel, eslint)
  Default (Vue 3 Preview) ([Vue 3] babel, eslint)
  Manually select features

Use the down arrow key to highlight

Run development server:
$ cd client
$ npm run serve

Install Bootstrap https://getbootstrap.com/docs/5.0/getting-started/download/
$ npm install bootstrap

Install Axios
https://github.com/axios/axios
$ npm install axios
app.py
 
from flask import Flask, jsonify
from flask_cors import CORS

MEMBERS = [
    {
        'id': '1',
        'name': 'cairocoders Ednalan',
        'email': 'cairocoders@gmail.com',
        'address': 'Olongapo city'
    },
    {
        'id': '2',
        'name': 'clydey Ednalan',
        'email': 'clydey@gmail.com',
        'address': 'Angles city'
    },
    {
        'id': '3',
        'name': 'claydren Ednalan',
        'email': 'clyderen@gmail.com',
        'address': 'San Fernando city'
    }
]

# configuration
DEBUG = True

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)

# 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
    })

if __name__ == '__main__':
    app.run()
client/scr/main.js
//client/scr/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import 'bootstrap/dist/css/bootstrap.css';

Vue.config.productionTip = false

new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');
client/src/App.vue
//client/src/App.vue
<template>
  <div id="app">
    <router-view/>
  </div>
</template>
client/src/Ping.vue
//client/src/Ping.vue
<template>
  <div>
    <p>{{ msg }}</p>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Ping',
  data() {
    return {
      msg: '',
    };
  },
  methods: {
    getMessage() {
      const path = 'http://localhost:5000/ping';
      axios.get(path)
        .then((res) => {
          console.log(res)
          this.msg = res.data;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMessage();
  },
};
</script>
client/src/components/Home.vue
//client/src/components/Home.vue
<template>
  <div class="container">
    <div class="row">
      <div class="col-sm-10">
        <h1>Member</h1>
        <hr><br><br>
        <button type="button" class="btn btn-success btn-sm">Add Member</button>
        <br><br>
        <table class="table table-hover">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Address</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(rs, index) in members" :key="index">
              <td>{{ rs.name }}</td>
              <td>{{ rs.email }}</td>
              <td>{{ rs.address }}</td>
              <td>
                <div class="btn-group" role="group">
                  <button type="button" class="btn btn-warning btn-sm">Update</button>
                  <button type="button" class="btn btn-danger btn-sm">Delete</button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      members: [],
    };
  },
  methods: {
    getMembers() {
      const path = 'http://localhost:5000/members';
      axios.get(path)
        .then((res) => {
          console.log(res);
          this.members = res.data.members;
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
  created() {
    this.getMembers();
  },
};
</script>
client/src/router/index.js
//client/src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Ping from '../components/Ping.vue';
import Home from '../components/Home.vue';

Vue.use(Router);

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/ping',
      name: 'Ping',
      component: Ping,
    },
  ],
});

Related Post