import argparse import markdown2 import os import SocketServer import StringIO import sys from SimpleHTTPServer import SimpleHTTPRequestHandler MARKDOWN_EXTENSIONS = ["md","markdown"] TEMPLATE = """
""" class MDRequestHandler(SimpleHTTPRequestHandler): #--------------------------------------------------------------- def do_GET(self, *args, **kwargs): """ Respond to a request, converting Markdown to html on the fly if requested file has a markdown extension """ is_markdown = any(self.path.endswith(e) for e in MARKDOWN_EXTENSIONS) if is_markdown: f = self.send_markdown() else: f = self.send_head() if f: self.copyfile(f, self.wfile) f.close() #--------------------------------------------------------------- def send_markdown(self): path = self.translate_path(self.path) try: mdf = open(path, 'rb') content = TEMPLATE % (markdown2.markdown( f = StringIO.StringIO(content) except IOError: self.send_error(404, "File not found") return None self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) fs = os.fstat(mdf.fileno()) self.send_header("Content-Length", "%d"%(f.len)) self.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) self.end_headers() return f def run(port): httpd = SocketServer.TCPServer(("", port), MDRequestHandler) print "serving at port: %d\nCtrl+C to Quit" % (port,) httpd.serve_forever() if __name__ == "__main__": parser = argparse.ArgumentParser(description="A simple Markdown document server") parser.add_argument('--port', "-p", default=8000, type=int, help="port to run the server on") args = parser.parse_args() run(port=args.port)