- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2019-12-18T13:25:05+00:00","","")
#author("2019-12-18T15:10:43+00:00","","")
#mynavi(Python覚え書き)
#setlinebreak(on);
* 概要 [#y772906e]
#html(<div class="pl10">)
python の http.server.SimpleHTTPRequestHandler を使って Markdown をHTMLに変換する簡単なサーバを書いてみた。
#html(</div>)
* 目次 [#o25c6c15]
- 関連
-- [[Python覚え書き]]
-- [[pythonでWebサーバを書いてみる]]
* 環境作成 [#f3d33b1c]
#html(<div class="pl10">)
#myterm2(){{
mkdir markdown_server
cd markdown_server
python3 -m venv venv
source venv/bin/activate
pip install markdown
}}
#html(</div>)
* サーバを書く [#j3ccc9ba]
#html(<div class="pl10">)
https://docs.python.org/ja/3/library/http.server.html
https://docs.python.org/ja/3/library/http.server.html#http.server.SimpleHTTPRequestHandler
#mycode2(){{
"""Markdown公開用サーバ."""
import http.server
import markdown
import socketserver
import os
import posixpath
PORT = 8000
class MarkdownHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, request, client_address, server):
super().__init__(request, client_address, server)
self.extensions_map[".md"] = "text/html; charset=utf-8"
def do_GET(self):
base, ext = posixpath.splitext(self.path)
if ext == ".md" and os.path.exists(self.path[1:]):
with open(self.path[1:], "r") as f:
path = self.path.split("?")[0][1:]
*_, ext = path.split(".")
if ext == "md" and os.path.exists(path):
with open(path, "r") as f:
lines = "\n".join(f.readlines())
response = markdown.Markdown().convert(lines).encode("utf-8")
self.send_head()
response = markdown.Markdown().convert(lines)
response_bytes = response.encode("utf-8")
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header('Content-Length', len(response_bytes))
self.end_headers()
self.wfile.write(response)
return
super().do_GET()
# ポートの再利用を許可する(コレがないとしばらくの間は同じポートを利用できない)
socketserver.TCPServer.allow_reuse_address = True
with socketserver.TCPServer(("", PORT), MarkdownHandler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
}}
#html(</div>)