Skip to content

Instantly share code, notes, and snippets.

@flying-sheep
Last active May 23, 2021 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flying-sheep/c296482b785662d505f06c8bfe32f16e to your computer and use it in GitHub Desktop.
Save flying-sheep/c296482b785662d505f06c8bfe32f16e to your computer and use it in GitHub Desktop.
Server for developing https://github.com/python/peps
import sys
import os
from http import HTTPStatus
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
from io import StringIO, BytesIO
from pep2html import PEP_TYPE_DISPATCH
here = Path(__file__).parent
template = '''\
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>{title}</title>
<link rel=stylesheet href=https://www.python.org/static/stylesheets/style.css>
<link rel=stylesheet href=https://www.python.org/static/stylesheets/mq.css>
<style>
.pep-page pre {{
padding: .5em;
background: inherit;
border-left: 0px;
box-shadow: 0 0 0 0;
}}
</style>
<script src=http://livejs.com/live.js></script>
</head>
<body class="content-wrapper pep-page">
<main class=container>
<section class="main-content with-left-sidebar">
<article class=text>
{body}
</article>
</section>
<aside class=left-sidebar>
<div class="psf-sidebar-widget sidebar-widget">
<h3 class=widget-title>The PSF</h3>
<p>The Python Software Foundation is the organization behind Python. Become a member of the PSF and help advance the software and our mission.</p>
</div>
</aside>
</main>
</body>
'''
def render_rst(html_path, rst_path):
with rst_path.open() as rst_file:
rst_lines = rst_file.readlines()
outfile = StringIO()
outfile.name = str(html_path)
PEP_TYPE_DISPATCH['text/x-rst'](str(rst_path), rst_lines, outfile)
title = str(rst_path.with_suffix('')).upper().replace('-', ' ')
return template.format(body=outfile.getvalue(), title=title)
class PEPRequestHandler(SimpleHTTPRequestHandler):
def send_head(self):
html_path = Path(self.path[1:]).relative_to(here)
if not html_path.match('pep-????.html'):
return super().send_head()
rst_path = html_path.with_suffix('.txt')
html = render_rst(html_path, rst_path).encode('utf-8')
f = BytesIO(html)
self.send_response(HTTPStatus.OK)
self.send_header('Content-type', 'text/html')
self.send_header('Content-Length', str(len(html)))
self.send_header('Last-Modified', self.date_time_string(rst_path.stat().st_mtime))
self.end_headers()
return f
if __name__ == '__main__':
print('Server started on http://localhost:8000')
server = HTTPServer(('', 8000), PEPRequestHandler)
server.serve_forever()
@flying-sheep
Copy link
Author

pathlib is super awesome btw. this would be much more complex without it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment