[PYTHON] How to write async and await in Vue.js

1. What is this article?

Make a note of how to write asyc and await in Vue.js.

2. Explanation of the example

Enter the integer N in the front end (website) and calculate (N + 3) in the back end. Also, at the same time as displaying the calculation result on the front end, write the calculation result to the csv file.

149.JPG

3. Architecture

The architecture is shown in the figure below. Enter the number on the front end and click the "Get" button to send the data to the back end. The calculation to add 3 to the numerical value received from the front end is executed by python, and the calculation result is written to the csv file and displayed back to the front end at the same time.

However, after "➆ Write the calculation result to the csv file" is completed, "⑧ Return the end process" is performed.

150.JPG

4. Source code point explanation

Click the "Get" button on the front end to execute proc () embedded in index.js. proc () consists of getdata () and hello (), but you have to wait for hello () to run until getdata () has finished running. Here we use "async" and "await".

151.JPG

152.JPG

4. Source code

It is assumed that Vue-Cli is already installed and ready to use. Please see the following site for various file placement and support for python-shell and CORS problems. https://qiita.com/NT1123/items/505059f23b0d34a50d41

/src/component/main.js


// eslint-disable-next-line
/* eslint-disable */ 
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from 'axios'  //When using axios, main.Import with js.

Vue.config.productionTip = false
Vue.prototype.$axios = axios  //When using axios, main.Need to add this line in js

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App }
})

/src/components/Top.vue


<template>

  <div>
    <h1>Demo screen</h1>
    <input type="button" value="Move" @click="goNewTask()"> <br>
    <input type="number" v-model="message"><input type="button" value="Get" @click="proc()">
    <p> <font size="2">Input data:{{ $data.message }} </font> </p>
    <p> <font size="2">output data:{{ $data.result }} </font> </p>
    <p> <font size="2">State:{{ $data.state }} </font> </p>
  </div>

</template>

<script>
// eslint-disable-next-line
/* eslint-disable */ 
import * as d3 from 'd3'  //To enable

export default {
  name: 'top',
  data: function(){
    return { 
        message:'',  //A variable that stores input data.
        result :'',  //A variable that stores the operation result.
        state:"wait" //A variable that stores the current status.
    }
  },
  methods: {
    //A method that sends the data entered in the text box to the backend, receives the calculation result from the backend, and displays the result.

    getdata:async function(){

        this.state="getting data"
        const res=await this.$axios.get('http://192.168.0.4:4000/api',{params:{dat:this.message}})
          .then(function(response){
            console.log(response.data.message)  //Console the operation result returned from the backend.I'm logging.
            this.result= response.data.message
            this.state="done"    
            }.bind(this))  //When performing Promise processing.bind(this)Is necessary
          .catch(function(error){  //About the processing to be performed when an error is returned from the backend
            this.state="ERROR"
            }.bind(this))
          .finally(function(){
            }.bind(this))},
    
    hello:function(){
        //this.state="getting data"
        this.$axios.get('http://192.168.0.4:4000/hello',{params:{dat:this.message}})
          .then(function(response){
   
            })  //When performing Promise processing.bind(this)Is necessary
          .catch(function(error){  //About the processing to be performed when an error is returned from the backend
            this.state="ERROR"
            }.bind(this))
          .finally(function(){
            }.bind(this))},
            
    async proc(){
      await this.getdata()
      this.hello()
    }        

  } 
}

</script>

/bkend/index.js


const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
const fs = require('fs')
JSONFILEPATH='test.csv'

//You have disabled the CORS policy.
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.get('/api', function(req, res) {

  var {PythonShell} = require('python-shell');
  var pyshell = new PythonShell('sample.py');  
  console.log("req")
  console.log(req.query.dat) //Console the data received from the front end.I'm logging.

  pyshell.send(req.query.dat); //From this code to python code'req.query.dat'Is provided as input data

  //Data is passed from python to this code after executing the python code.
  pyshell.on('message',  function (data) {


  var obj={
    age:data
  }
     //(2)JSON.Convert dictionary type array to JSON format using stringfy.
  var jsondat = JSON.stringify( obj );

   //(3)If the file to write the above jsondat already exists, delete the file once.
  if (fs.existsSync(JSONFILEPATH)) fs.unlinkSync(JSONFILEPATH)  

   //(4)Write jsondat to a file that exists in the JSONFILEPATH
  fs.writeFileSync(JSONFILEPATH,jsondat)
  console.log("csv writing...")


    res.send({
      message: data   //The result of the operation performed by python is returned to the front end.
    })
  })

})

app.get('/hello', function(req, res) {

  console.log("all process finished")

})

app.get('/', (req, res) => {res.send('Hello World4000!')} )
app.listen(4000)

/bkend/sample.py


import sys
data = sys.stdin.readline()  #Get data from standard input
num=int(data)

def sum(a):
    return a+3

print(sum(num))  #print contents python-Return to shell

5. Supplement

The following site is easy to understand for the explanation of asyanc and await.

https://qiita.com/soarflat/items/1a9613e023200bbebcb3

Recommended Posts

How to write async and await in Vue.js
How to write soberly in pandas
How to write this process in Perl?
How to use is and == in Python
How to write Ruby to_s in Python
How to write pydoc and multi-line comments
Repeated @ app.callback in Dash How to write Input and State neatly
Difference in how to write if statement between ruby ​​and python
How to generate permutations in Python and C ++
How to write the correct shebang in Perl, Python and Ruby scripts
How to write regular expression patterns in Linux
How to write a named tuple document in 2020
How to plot autocorrelation and partial autocorrelation in python
20th Offline Real-time How to Write Problems in Python
How to write string concatenation in multiple lines in Python
How to define Decorator and Decomaker in one function
Write tests in Python to profile and check coverage
[Python] How to sort dict in list and instance in list
Convert callback-style asynchronous API to async / await in Python
How to use Decorator in Django and how to make it
How to get RGB and HSV histograms in OpenCV
XPath Basics (2) -How to write XPath
How to develop in Python
[Note] How to write QR code and description in the same image with python
How to write custom validations in the Django REST Framework
How to swap elements in an array in Python, and how to reverse an array.
Foreigners talk: How to name classes and methods in English
How to use pyenv and pyenv-virtualenv in your own way
[Python] How to write an if statement in one sentence.
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to create and use static / dynamic libraries in C
Comparison of how to use higher-order functions in Python 2 and 3
How to get all the keys and values in the dictionary
[Blender] How to handle mouse and keyboard events in Blender scripts
How to write to update Datastore to async with Google Apps Engine
Summary of how to write .proto files used in gRPC
How to write a metaclass that supports both python2 and python3
How to execute external shell scripts and commands in python
How to create dataframes and mess with elements in pandas
[ROS] How to write Publisher and Subscriber on one node
How to log in to AtCoder with Python and submit automatically
How to write a Python class
[Python] How to do PCA in Python
How to handle session in SQLAlchemy
Python: How to use async with
How to install and use Tesseract-OCR
How to use classes in Theano
How to collect images in Python
Flask reuse How to write html
Hide websockets async / await in Python3
How to update Spyder in Anaconda
How to use SQLite in Python
How to convert 0.5 to 1056964608 in one shot
How to install and configure blackbird
How to use .bash_profile and .bashrc
How to install CUDA and nvidia-driver
Async / await with Kivy and tkinter
How to kill processes in bulk
How to install and use Graphviz
How to use Mysql in python
How to use ChemSpider in Python