・ I want to link Vue-Cli and Python. (I want to run Python on an app that uses Vue-CLi)
-The front end is composed of Vue-Cli. Put the Python code on the backend. -The interface between Vue-Cli and Python is [Python-shell](https://qiita.com/NT1123/items/09aed7b23388190cba23#3-1-%E3%82%A4%E3%83%B3%E3%82 % B9% E3% 83% 88% E3% 83% BC% E3% 83% AB% E6% 96% B9% E6% B3% 95) is used. -Assign different ports for the front end and back end so that both can communicate.
The installation method and version of the used packages and libraries are described below.
item | version | Installation method |
---|---|---|
Vue-Cli | 3.9.3 | See LINK destination |
python-shell | 1.0.8 | See LINK destination |
express | 4.17.1 | |
bodyparser | Explanation omitted | |
node.js | 12.14.0 | Explanation omitted |
npm | 6.3.14 | Explanation omitted |
From the web page, add +3 to the entered value and display the calculation result.
★ (1) to (6) in the above figure correspond to the operations (1) to (6) explained below.
(1) "Demo screen" Enter the numerical value in the text box. (2) Click the Get button. (3) The numerical value entered in (1) is sent to the Python code (sample.py) via index.js (running Python-shell). (4) sample.py adds +3 to the entered number. (5) sample.py returns the completed numerical value to index.js. (6) index.js returns the numerical value received from sample.py to the "demo screen". (7) The "Demo screen" displays the calculation results.
It is assumed that Vue-Cli is already installed and ready to use.
The directory structure of each file is arranged as follows.
/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="getdata()">
<p> <font size="2">Input data:{{ $data.message }} </font> </p>
<p> <font size="2">output data:{{ $data.result }} </font> </p>
<p> <font size="2">Status:{{ $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:function(){
this.state="getting data"
this.$axios.get('http://192.168.0.4:3000/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))}
}
}
</script>
/bkend/index.js
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.json())
//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) {
console.log("return data")
res.send({
message: data //The result of the operation performed by python is returned to the front end.
})
})
})
app.listen(3000)
/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
Vue-cli works on webpack, but python-shell doesn't seem to work on webpack. Therefore, I started a new server that is not running with vue-cli and made python-shell run on it.
When accessing xxx.xxx.xx.xx: 3000 from xxx.xxx.xx.xx: 91, communication is blocked for security reasons because the domain is different [CORS problem]. In order to avoid the CORS problem, there are cases where measures are taken on the accessing side and cases where measures are taken on the accessing side, but in this case, measures were taken on the accessing side. For more information, please see here.
/bkend/index.Part of js
/bkend/
//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();
});
Recommended Posts