簡易 Web サーバー2021年12月28日 | |
はじめにPython で簡易 Web サーバーを書く。 決まったページを返すindex.html <html> <body> <p>OK</p> </body> </html> server.py
import http.server
import socketserver
PORT = 8080
handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), handler) as httpd:
print("server at port", PORT)
httpd.server_forever()
起動 $ python server.py ブラウザで "http://localhost:8080" にアクセスする。OK と出ればよい。 動的なページを返すindex.html を動的に作り出す。 server2.py
import http.server
import socketserver
from datetime import datetime
PORT = 8080
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
contents = [
"<html>",
"<body>",
"<p>%s</p>" % "{:%Y-%m-%d %H:%M:%S}".format(datetime.now()),
"</body>",
"</html>",
]
with open("index.html", "w") as f:
f.write("\n".join(contents))
self.path = "index.html"
return http.server.SimpleHTTPRequestHandler.do_GET(self)
handler = MyHttpRequestHandler
with socketserver.TCPServer(("", PORT), handler) as httpd:
print("server at port", PORT)
httpd.serve_forever()
起動 $ python server2.py ブラウザで "http://localhost:8080" にアクセスし、リロードで表示が変われば OK。 | |
| PENGUINITIS | |