EC2에서 파이썬 프로그램을 자바 스크립트에서 호출하는 간단한 코드

버튼을 눌러 파이썬 프로그램을 시작합니다.



다음과 같은 html을 작성한다. 입력하면, 입력한 값을 돌려주는 python 프로그램을 준비한다.


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

실행 결과



좋은 웹페이지 즐겨찾기