Vue-Cli and Python integration

1. 1. Purpose

・ I want to link Vue-Cli and Python. (I want to run Python on an app that uses Vue-CLi)

2. Method

-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.

4.JPG

3. 3. Preferences / preparation

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

Four. Created app

From the web page, add +3 to the entered value and display the calculation result.

5.JPG

★ (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.

4-1 System configuration

It is assumed that Vue-Cli is already installed and ready to use.

4-2 Directory structure

The directory structure of each file is arranged as follows.

6.JPG

4-3 code

/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

4-4 Execution method

Five. point

5-1 Reasons for using Pyshon-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.

5-2 How to avoid CORS problems

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

Vue-Cli and Python integration
[python] Compress and decompress
Python and numpy tips
[Python] pip and wheel
Batch design and python
Python iterators and generators
Ruby, Python and map
python input and output
Python and Ruby split
PHP and Python integration from scratch on Laravel
python tag integration test
Python3, venv and Ansible
Python asyncio and ContextVar
Programming with Python and Tkinter
Encryption and decryption with Python
Python: Class and instance variables
3-3, Python strings and character codes
Python 2 series and 3 series (Anaconda edition)
Python and hardware-Using RS232C with Python-
Python on Ruby and angry Ruby on Python
Python indentation and string format
Python real division (/) and integer division (//)
Install Python and Flask (Windows 10)
About python objects and classes
About Python variables and objects
Apache mod_auth_tkt and Python AuthTkt
Å (Ongustromu) and NFC @ Python
Understand Python packages and modules
# 2 [python3] Separation and comment out
Python shallow copy and deep copy
Python and ruby slice memo
Python installation and basic grammar
I compared Java and Python!
Python shallow and deep copy
About Python, len () and randint ()
About Python datetime and timezone
Install Python 3.7 and Django 3.0 (CentOS)
Python environment construction and TensorFlow
Python class variables and instance variables
Ruby and Python syntax ~ branch ~
[Python] Python and security-① What is Python?
Stack and Queue in Python
python metaclass and sqlalchemy declareative
Fibonacci and prime implementations (python)
Python basics: conditions and iterations
Use and integration of "Shodan"
Python bitwise operator and OR
Python debug and test module
Python list and tuples and commas
Python variables and object IDs
Python list comprehensions and generators
About Python and regular expressions
python with pyenv and venv
Unittest and CI in Python
Maxout description and implementation (Python)
[python] Get quotient and remainder
Python 3 sorted and comparison functions
[Python] Depth-first search and breadth-first search
Identity and equivalence Python is and ==
Source installation and installation of Python
Python or and and operator trap