[CGI] Run the Python program on the server with Vue.js + axios and get the output data

Introduction

I can do everything with the front end, but I wanted the fun of Python in the calculation part, so I touched CGI that dynamically runs the program on the server, so I summarized it. The back end is still sparse.

I have an XREA account on a free rental server, so I will actually try it there. High-performance, high-quality rental server that can be used for free | XREA

What I want to do is

  1. Click the button
  2. Pass data to the server using Vue.js and axios
  3. Execute a CGI script written in Python, perform an operation, and return the result in JSON
  4. Display the returned data on the same screen

That's right.

This time, as an example, we will create a program that calculates and returns the greatest common divisor and least common multiple of the two input numbers.

Try to make

File placement

├─ cgi-bin
│    └─ index.cgi
├─ index.html
└─ main.js

CGI scripts written in Python create a directory called cgi-bin and put it in it. Written in Python but with the extension .cgi.

After uploading to the server, you need to specify the permissions around CGI, which will be described later.

HTML (index.html)

<html>
<head>
    <meta charset="UTF-8">
    <title>Returns the greatest common divisor and least common multiple</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>
    <script type="module" src="main.js"></script>
</head>
<body>
    <div id="app">
        <!--Input part-->
        <p>
            <input v-model="a" type="number" value="12">
            <input v-model="b" type="number" value="15">
            <button v-on:click="getResult">Calculation</button>
        </p>
        <!--Display part-->
        <p>
Greatest common divisor: {{ result['gcd'] }}<br>
Least common multiple: {{ result['lcm'] }}
        </p>
    </div>
</body>
</html>

Load Vue.js and axios on the CDN. If you load a JavaScript file written in Vue with type =" module ", it will be executed after the DOM is loaded, so you can rest assured.

JavaScript (main.js)

var vm = new Vue({
    el: '#app',
    data: {
        a: 12,
        b: 15,
        result: {},  //Variable to store the returned object
    },
    methods: {
        getResult: function() {
            const url = './cgi-bin/';
            //Data transfer with axios
            axios.get(url, {
                params: {  //Specify parameters with params
                    a: this.a,
                    b: this.b
                }
            })
            .then(res => this.result = res.data)  //Store data in result
        }
    }
});

Create a Vue instance and pass data with axios. The URL is ./cgi-bin/. If the name is ʻindex.cgi`, you don't have to specify the file name like HTML.

Also, the returned data res.data can be retrieved as an object, so there was no need to fix it withJSON.parse (). (Because I returned it as JSON, I was convinced that it would be returned as a JSON string.) By the way, I get this error.

SyntaxError: Unexpected token o in JSON at position 1

If you wonder what ʻo is, it seems to be ʻo of ʻobject` ...

Python CGI (index.cgi)

#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import cgi
import cgitb
import math
import json

cgitb.enable()  #Turn on CGI debugging

form = cgi.FieldStorage()  #Store the data obtained by GET
a = int(form['a'].value)   #Data comes as a character string, so convert it to a number
b = int(form['b'].value)

data = {
    'gcd': math.gcd(a, b),  # math.gcd()Is python 3.Apparently added in 5
    'lcm': a * b // math.gcd(a, b)
}

print('Content-Type: application/json')
print()
print(json.dumps(data))  #Return in json format

Specify the location of the Python interpreter at the beginning of the line. I think that the execution path of CGI of each language is written on the specification page of the rental server, so check it. XREA is here. xrea_py_path.png

Context-Type Theprint ()after the specified line is for a line break, and it seems to be a useless specification unless this is inserted. You can usually do \ n at the end of the Context-Type string.

After uploading, you need to specify the permissions of the directory containing the CGI script and its files, and XREA also has recommended permissions. xrea_permission.png In particular, note that the CGI executable must be 700 or more (executable) (I often forgot).

I will also post a link with the above XREA specifications. specification|High-performance, high-quality rental server that can be used for free|XREA

Run

Here is the screen that I uploaded the file and actually tried it xrea_cgi_disp.png good feeling. If you send it blank or decimal, you will usually get an error, but it's a trial.

that's all.

Recommended Posts

[CGI] Run the Python program on the server with Vue.js + axios and get the output data
Get data from MySQL on a VPS with Python 3 and SQLAlchemy
Get the width of the div on the server side with Selenium + PhantomJS + Python
Until you install Python with pythonbrew and run Flask on a WSGI server
Get comments on youtube Live with [python] and [pytchat]!
Run CGI written in python on Sakura's rental server
Get comments and subscribers with the YouTube Data API
Install django on python + anaconda and start the server
Get Youtube data with python
Run Python CGI on CORESERVER
Access the host SQL Server with python27 / pyodbc on the container
Get rid of dirty data with Python and regular expressions
Solve the spiral book (algorithm and data structure) with python!
Build a Python environment and transfer data to the server
System trade starting with Python3: Get the latest program code
Get additional data to LDAP with python (Writer and Reader)
[Introduction to Python] How to get data with the listdir function
Get the matched string with a regular expression and reuse it when replacing on Python3
Run the program without building a Python environment! !! (How to get started with Google Colaboratory)
How is the progress? Let's get on with the boom ?? in Python
Run the output code on the local web server as "A, pretending to be B" in python
Get started with the Python framework Django on Mac OS X
Get the weather with Python requests
Get the weather with Python requests 2
[Python] Get economic data with DataReader
I tried to get and analyze the statistical data of the new corona with Python: Data of Johns Hopkins University
Put Cabocha 0.68 on Windows and try to analyze the dependency with Python
[In-Database Python Analysis Tutorial with SQL Server 2017] Step 3: Data Exploration and Visualization
[Personal memo] Get data on the Web and make it a DataFrame
Send and receive image data as JSON over the network with Python
Get and convert the current time in the system local timezone with python
Deploy and use the prediction model created in Python on SQL Server
Install the python module with pip on a server without root privileges
Get the number of articles accessed and likes with Qiita API + Python
Read the file with python and delete the line breaks [Notes on reading the file]
Send and receive binary data via serial communication with python3 (on mac)
Get and estimate the shape of the head using Dlib and OpenCV with python
Compare nighttime and daytime returns on the Nikkei Stock Average with python
Rock-paper-scissors with Python Let's run on a Windows local server for beginners
Install Python3 and Django on Amazon Linux (EC2) and run your web server
Get additional data in LDAP with python
Data pipeline construction with Python and Luigi
[Note] Get data from PostgreSQL with Python
Run servo with Python on ESP32 (Windows)
[Python] Get the variable name with str
A memo with Python2.7 and Python3 on CentOS
Build CGI Server running on Python 3 on Docker
Download files on the web with Python
Run python wsgi server on NGINX Unit
Put Docker in Windows Home and run a simple web server with Python
How to get started with the 2020 Python project (windows wsl and mac standardization)
Make a Python program a daemon and run it automatically when the OS starts
Execute raw SQL using python data source with redash and display the result
Get information on the 100 most influential tech Twitter users in the world with python.
Get coordinate values and keyboard input values by clicking on the python / matplotlib diagram
Get the stock price of a Japanese company with Python and make a graph
[Introduction to Python] How to get the index of data with a for statement
Periodically run a python program on AWS Lambda
[Python] Get the files in a folder with Python
Install and run Python3.5 + NumPy + SciPy on Windows 10
Drawing tips with matplotlib on the server side