LoginSignup
1
1

More than 3 years have passed since last update.

EC2でpythonプログラムをJavascriptから呼び出す簡易コード

Last updated at Posted at 2020-12-25

ボタンを押してpythonプログラムを起動

以下のようなhtmlを作成する。入力すると、入力した値を返すpythonプログラムを用意する。

image.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
  <h1>テスト</h1>
  <p>文字を入力してください</p>
  <input id="plane" type="text" value="">
  <input id="btn" type="button" value="入力">
  <p id="string"></p>
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script>
    $(function(){
      $("#btn").click(
        function() {
          var plane = document.getElementById("plane").value;
          $.ajax({
            url: "./test.py",
            type: "post",
            data: {data: plane},
            success: function(data){
              document.getElementById("string").innerText = data;
            },
            error: function(data){
              console.log("failed");
            }
          });
        }
      );
    });
  </script>
</body>
</html>
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import cgi

storage = cgi.FieldStorage()
data = storage.getvalue('data')
print('Status: 200 OK')
print('Content-type: text/html\n')

print('入力された文字は、' + data + 'です。')

httpdの設定

[ec2-user@ip-xxx-xxx-xxx-xxx ~]$ sudo -i
[root@ip-xxx-xxx-xxx-xxx ~]# yum install python3
[root@ip-xxx-xxx-xxx-xxx ~]# yum install httpd
[root@ip-xxx-xxx-xxx-xxx ~]# systemctl start httpd
[root@ip-xxx-xxx-xxx-xxx ~]# cd /var/www/html/
[root@ip-xxx-xxx-xxx-xxx html]# vi index.html
[root@ip-xxx-xxx-xxx-xxx html]# vi test.py
[root@ip-xxx-xxx-xxx-xxx html]# chmod 775 test.py
[root@ip-xxx-xxx-xxx-xxx html]# vi /etc/httpd/conf/httpd.conf
   144行目あたり行末にExecCGIを追加         Options Indexes FollowSymLinks ExecCGI
   157行目あたり行を追加                    AddHandler cgi-script .cgi .py
   306行目あたり行末に.html .htmを追加      AddType text/html .shtml .html .htm
   307行目あたり行末に.html .htmを追加      AddOutputFilter INCLUDES .shtml .html .htm
[root@ip-xxx-xxx-xxx-xxx html]# systemctl restart httpd

実行結果

image.png

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1