0001 #!/usr/bin/python3 0002 # -*- utf-8 -*- 0003 # Copyright (C) 2021 Ken'ichi Fukamachi, all rights reserved. see ./LICENSE file. 0004 import os 0005 import sys 0006 import http.server 0007 import socketserver 0008 import cgi 0009 from urllib.parse import urlparse 0010 from urllib.parse import parse_qs 0011 import mysql.connector 0012 0013 0014 # 0015 # Configurations 0016 # 0017 HTTP_HOST = "0.0.0.0" 0018 HTTP_PORT = 8080 0019 HTDOCS_DIR = "/var/www/html" 0020 0021 MYSQL_USER = 'root' 0022 MYSQL_PASSWORD = '1qaz2wsx' 0023 MYSQL_HOST = 'mysql' 0024 MYSQL_DATABASE = 'test' 0025 0026 0027 0028 # 0029 # MySQL client example: 0030 # 0031 class OurSQL: 0032 0033 def __init__(self): 0034 try: 0035 conn = mysql.connector.connect( 0036 user=MYSQL_USER, 0037 password=MYSQL_PASSWORD, 0038 host=MYSQL_HOST, 0039 database=MYSQL_DATABASE 0040 ) 0041 self.conn = conn; 0042 print("(debug) connected ? = " + str(conn.is_connected())) 0043 except mysql.connector.Error as err: 0044 print(err) 0045 0046 def __del__(self): 0047 self.conn.close() 0048 0049 0050 def create_table(self): 0051 SQL = ( 0052 'CREATE TABLE IF NOT EXISTS shop_menu (' 0053 ' id MEDIUMINT NOT NULL AUTO_INCREMENT,' 0054 ' name CHAR(30) NOT NULL,' 0055 ' price INT NOT NULL,' 0056 ' PRIMARY KEY (id)' 0057 ');' 0058 ) 0059 cursor = self.conn.cursor() 0060 cursor.execute(SQL) 0061 self.conn.commit() 0062 cursor.close() 0063 0064 def insert(self): 0065 cursor = self.conn.cursor() 0066 sqlfmt = 'INSERT INTO shop_menu (name,price) VALUES (%s,%s)' 0067 cursor.execute(sqlfmt, ('beer', 200)) 0068 cursor.execute(sqlfmt, ('water', 100)) 0069 cursor.execute(sqlfmt, ('水', 100)) 0070 cursor.execute(sqlfmt, ('お茶', 100)) 0071 cursor.execute(sqlfmt, ('お菓子', 100)) 0072 cursor.execute(sqlfmt, ('アイス', 30)) 0073 self.conn.commit() 0074 cursor.close() 0075 0076 def select(self): 0077 print("(debug) SELECT * FROM shop_menu\n") 0078 cursor = self.conn.cursor() 0079 cursor.execute('SELECT * FROM shop_menu') 0080 for (id, name, price) in cursor: 0081 print("id:{} name:{} price:{}".format(id, name, price)) 0082 cursor.close() 0083 0084 def query(self, key): 0085 r='' 0086 cursor = self.conn.cursor() 0087 cursor.execute('SELECT name,price FROM shop_menu WHERE name=\'{}\''.format(key)) 0088 for (name, price) in cursor: 0089 r = r + "商品
{} の価格は {} 円です\n".format(name, price) 0090 cursor.close() 0091 return r 0092 0093 0094 # 0095 # WWW server example: Handler class, which handles www requests 0096 # 0097 0098 # Handler = http.server.SimpleHTTPRequestHandler 0099 class Handler(http.server.SimpleHTTPRequestHandler): 0100 def __init__(self, *args, **kwargs): 0101 super().__init__(*args, directory=HTDOCS_DIR, **kwargs) 0102 0103 def do_GET(self): 0104 # basic routing 0105 if self.path == '/shop': 0106 return self.__shop_menu() 0107 if self.path == '/hello': 0108 return self.__hello_world() 0109 0110 return super().do_GET() 0111 0112 def do_POST(self): 0113 self._set_headers() 0114 form = cgi.FieldStorage( 0115 fp=self.rfile, 0116 headers=self.headers, 0117 environ={'REQUEST_METHOD': 'POST'} 0118 ) 0119 key=form.getvalue("key") 0120 self.__shop_search(key, self.wfile) 0121 0122 def _set_headers(self): 0123 self.send_response(200) 0124 self.send_header('Content-type','text/html; charset=utf-8') 0125 self.end_headers() 0126 0127 def __hello_world(self): 0128 self._set_headers() 0129 message = "Hello World! (GET response)\n" 0130 self.wfile.write(bytes(message, "utf8")) 0131 0132 def __shop_menu(self): 0133 self._set_headers() 0134 message = ('' 0135 '' 0136 '
' 0137 '研究室内売店 商品検索:' 0138 ' ' 0139 ' ' 0140 '
' 0141 '
(debug) embedded html case' 0142 '' 0143 '' 0144 ) 0145 self.wfile.write(bytes(message, "utf8")) 0146 0147 def __shop_search(self, key, wfile): 0148 oursql = OurSQL() 0149 r_msg = oursql.query(key) 0150 if r_msg == '': 0151 r_msg = '取扱っておりません' 0152 r_msg = r_msg + "
ご来店おまちしております\n" 0153 message = "

(debug) [POST response] search key = {}\n\n

".format(key) 0154 message = message + r_msg + "\n\n" 0155 wfile.write(bytes(message, "utf8")) 0156 0157 0158 # 0159 # MAIN 0160 # 0161 if __name__ == "__main__": 0162 # [debug] initialize database 0163 if os.getenv("SQL_INIT"): 0164 oursql = OurSQL() 0165 oursql.create_table() 0166 oursql.insert() 0167 sys.exit(0) 0168 0169 # [debug] database 0170 if os.getenv("SQL_DUMP"): 0171 oursql = OurSQL() 0172 oursql.select() 0173 sys.exit(0) 0174 0175 # version 3 only 0176 if sys.version_info.major < 3: 0177 print("***error: python 2 is not supported") 0178 sys.exit(1) 0179 0180 # run python www server (httpd) 0181 with socketserver.TCPServer((HTTP_HOST, HTTP_PORT), Handler) as httpd: 0182 print("(debug) serving at port", HTTP_PORT) 0183 httpd.serve_forever()