Created
January 6, 2016 18:26
-
-
Save evilchili/d63b7212cfee37dae5ad to your computer and use it in GitHub Desktop.
A Minimalist webserver that listens on 8000, handles gets, and renders markdown if the request asks for a file ending in .md. Requires mistune.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python -u | |
""" | |
A Minimalist webserver that listens on 8000, handles gets, and renders markdown if the request asks for a file ending in .md. | |
""" | |
import os | |
import SimpleHTTPServer | |
import mistune | |
renderer = mistune.Renderer(hard_wrap=True) | |
markdown = mistune.Markdown(renderer=renderer) | |
# basic CSS for markdown rendering. Season to taste. | |
HEAD = """ | |
<head> | |
<style type='text/css'> | |
html,body { | |
font-family: helvetica neue, arial, sans-serif; | |
max-width: 960px; | |
} | |
pre { | |
background-color: #EEE; | |
border: 1px dashed #DDD; | |
padding: 10px; | |
} | |
</style> | |
</head> | |
""" | |
class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): | |
""" | |
Subclass SimpleHTTPRequestHandler to handle markdown files | |
""" | |
def do_GET(self): | |
self.send_response(200) | |
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate") | |
self.send_header("Pragma", "no-cache") | |
self.send_header("Expires", "0") | |
# if the request ends in '.md', assume it is a markdown file and render it as HTML | |
if os.path.splitext(self.path)[1] == '.md': | |
self.send_header('Content-Type', 'text/html') | |
self.end_headers() | |
with open('.' + self.path) as md: | |
self.wfile.write("<html>") | |
self.wfile.write(HEAD) | |
self.wfile.write(markdown(md.read())) | |
self.wfile.write("</body></html>") | |
self.wfile.close() | |
# everything else gets passed through | |
else: | |
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) | |
if __name__ == '__main__': | |
SimpleHTTPServer.test(HandlerClass=MyHTTPRequestHandler) | |
# :vim: set filetype=python |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment