Make a note of how to write asyc and await in Vue.js.
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.
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.
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".
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
The following site is easy to understand for the explanation of asyanc and await.
https://qiita.com/soarflat/items/1a9613e023200bbebcb3
Recommended Posts