Skip to content

Commit 2212257

Browse files
committed
reformat
1 parent 937e60c commit 2212257

File tree

2 files changed

+116
-63
lines changed

2 files changed

+116
-63
lines changed

httpmdhtml/md_to_html.py

Lines changed: 46 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,63 +11,84 @@
1111
from bs4 import BeautifulSoup, element
1212

1313

14-
def markdown_to_html(MarkdownIt_obj, in_file_path, out_file_path="tmp.html",
15-
encode_local_images=False, css_file=None, live_md_rr=None):
16-
14+
def markdown_to_html(
15+
MarkdownIt_obj,
16+
in_file_path,
17+
out_file_path="tmp.html",
18+
encode_local_images=False,
19+
css_file=None,
20+
live_md_rr=None,
21+
):
1722
text = open(in_file_path, "r").read()
1823
tokens = MarkdownIt_obj.parse(text)
1924
html_text = MarkdownIt_obj.render(text)
2025
# pretty CSS
21-
soup = BeautifulSoup(html_text, 'html5lib') # adds <html>, <head>, <body>
22-
soup.select_one('head').append(soup.new_tag("meta"))
23-
soup.select_one('meta').attrs['charset'] = "UTF-8"
26+
soup = BeautifulSoup(html_text, "html5lib") # adds <html>, <head>, <body>
27+
soup.select_one("head").append(soup.new_tag("meta"))
28+
soup.select_one("meta").attrs["charset"] = "UTF-8"
2429
# if lots of images, caching is preferable more often than not
2530
# soup.select_one('meta').attrs['http-equiv'] = "Cache-control"
2631
# soup.select_one('meta').attrs['content'] = "no-cache"
27-
soup.select_one('head').append(soup.new_tag("style"))
32+
soup.select_one("head").append(soup.new_tag("style"))
2833
if css_file:
29-
with open(css_file, 'r') as f:
30-
css=f.read()
34+
with open(css_file, "r") as f:
35+
css = f.read()
3136
else:
32-
css="""body { background-color: #272822; color: white; font-family: Courier; }
37+
css = """body { background-color: #272822; color: white; font-family: Courier; }
3338
a[href] { color: #66d9ef; }
3439
code { color: #ae81ff; background-color: #272b33; border-radius: 6px; }
3540
table, th, td { border: 1px solid; border-collapse: collapse; padding-left: 4px; padding-right: 4px; }"""
3641
soup.select_one("style").string = css
3742
if live_md_rr:
38-
script = f"setTimeout(function(){{ document.location.reload(); }}, {live_md_rr});"
39-
soup.select_one('head').append(soup.new_tag("script"))
43+
script = (
44+
f"setTimeout(function(){{ document.location.reload(); }}, {live_md_rr});"
45+
)
46+
soup.select_one("head").append(soup.new_tag("script"))
4047
soup.select_one("script").string = script
4148
if encode_local_images:
4249
img_elems = soup.select("img")
4350
url_pattern = "^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$"
4451
for img in img_elems:
45-
if not re.match(url_pattern, img.attrs['src']):
46-
img_path = os.path.join(os.path.dirname(in_file_path), img.attrs['src'])
52+
if not re.match(url_pattern, img.attrs["src"]):
53+
img_path = os.path.join(os.path.dirname(in_file_path), img.attrs["src"])
4754
with open(img_path, "rb") as image_obj:
4855
img_bytes = str(base64.b64encode(image_obj.read()), "utf-8")
49-
img.attrs['src'] = f"data:image/png;base64,{img_bytes}"
56+
img.attrs["src"] = f"data:image/png;base64,{img_bytes}"
5057
Path(out_file_path).write_text(str(soup))
5158

5259

5360
if __name__ == "__main__":
54-
5561
MarkdownIt_obj = MarkdownIt("commonmark").enable("table").enable("strikethrough")
5662
parser = argparse.ArgumentParser()
57-
parser.add_argument('--in_file_path', '-i', required=True,
58-
help='in-file-path; your existing markdown file')
59-
parser.add_argument('--out_file_path', '-o', default="tmp.html",
60-
help='out-file-path; your HTML file to be created')
61-
parser.add_argument('--encode_local_images', '-e', action='store_true',
62-
help='in HTML, embed base64-encoded data of local images linked to in your markdown; removes dependency on presence of the external local images')
63-
parser.add_argument('--css_file', default=None,
64-
help='css-file-path; its content will be written to the <style> element')
63+
parser.add_argument(
64+
"--in_file_path",
65+
"-i",
66+
required=True,
67+
help="in-file-path; your existing markdown file",
68+
)
69+
parser.add_argument(
70+
"--out_file_path",
71+
"-o",
72+
default="tmp.html",
73+
help="out-file-path; your HTML file to be created",
74+
)
75+
parser.add_argument(
76+
"--encode_local_images",
77+
"-e",
78+
action="store_true",
79+
help="in HTML, embed base64-encoded data of local images linked to in your markdown; removes dependency on presence of the external local images",
80+
)
81+
parser.add_argument(
82+
"--css_file",
83+
default=None,
84+
help="css-file-path; its content will be written to the <style> element",
85+
)
6586
args = parser.parse_args()
6687

6788
markdown_to_html(
6889
MarkdownIt_obj=MarkdownIt_obj,
6990
in_file_path=args.in_file_path,
7091
out_file_path=args.out_file_path,
7192
encode_local_images=args.encode_local_images,
72-
css_file=args.css_file
93+
css_file=args.css_file,
7394
)

httpmdhtml/server.py

Lines changed: 70 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import posixpath
1010
import select
1111
import shutil
12-
import socket # For gethostbyaddr()
12+
import socket # For gethostbyaddr()
1313
import socketserver
1414
import sys
1515
import time
@@ -31,25 +31,35 @@
3131

3232

3333
class md_to_html_SimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
34-
def __init__(self, *args, MarkdownIt_obj=None, css_file=None, live_md_rr=False, **kwargs):
34+
def __init__(
35+
self, *args, MarkdownIt_obj=None, css_file=None, live_md_rr=False, **kwargs
36+
):
3537
self.MarkdownIt_obj = MarkdownIt_obj
3638
self.css_file = css_file
3739
self.live_md_rr = live_md_rr
3840
super().__init__(*args, **kwargs)
3941

40-
4142
def do_GET(self, rm_temp_html=False):
4243
"""Serve a GET request."""
43-
self.url_dc_path = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path) # url decode, strip query params for file check
44-
if self.MarkdownIt_obj and self.url_dc_path.endswith(".md") and os.path.exists(os.path.join(self.directory, f".{self.url_dc_path}")): # check for markdown file request
45-
in_file_path=os.path.join(self.directory, f".{self.url_dc_path}")
46-
out_file_path=os.path.join(self.directory, f".{os.path.splitext(self.url_dc_path)[0]}.html")
44+
self.url_dc_path = urllib.parse.unquote(
45+
urllib.parse.urlsplit(self.path).path
46+
) # url decode, strip query params for file check
47+
if (
48+
self.MarkdownIt_obj
49+
and self.url_dc_path.endswith(".md")
50+
and os.path.exists(os.path.join(self.directory, f".{self.url_dc_path}"))
51+
): # check for markdown file request
52+
in_file_path = os.path.join(self.directory, f".{self.url_dc_path}")
53+
out_file_path = os.path.join(
54+
self.directory, f".{os.path.splitext(self.url_dc_path)[0]}.html"
55+
)
4756
md_to_html.markdown_to_html(
48-
self.MarkdownIt_obj,
49-
in_file_path=in_file_path,
50-
out_file_path=out_file_path,
51-
css_file=self.css_file,
52-
live_md_rr=self.live_md_rr)
57+
self.MarkdownIt_obj,
58+
in_file_path=in_file_path,
59+
out_file_path=out_file_path,
60+
css_file=self.css_file,
61+
live_md_rr=self.live_md_rr,
62+
)
5363
self.path = f"{os.path.splitext(self.path)[0]}.html"
5464
rm_temp_html = True
5565
f = self.send_head()
@@ -63,44 +73,66 @@ def do_GET(self, rm_temp_html=False):
6373

6474

6575
if __name__ == "__main__":
66-
6776
parser = argparse.ArgumentParser()
68-
parser.add_argument('--cgi', action='store_true',
69-
help='Run as CGI Server')
70-
parser.add_argument('--bind', '-b', metavar='ADDRESS',
71-
help='Specify alternate bind address '
72-
'[default: all interfaces]')
73-
parser.add_argument('--directory', '-d', default=os.getcwd(),
74-
help='Specify alternative directory '
75-
'[default:current directory]')
76-
parser.add_argument('--css_file', default=None,
77-
help='css-file-path; its content will be written to the <style> element')
78-
parser.add_argument('--live_md_rr', '-l', action='store', type=int, default=None,
79-
help='Continuous refresh rate of MD page, in ms. Respects cache')
80-
parser.add_argument('port', action='store',
81-
default=8000, type=int,
82-
nargs='?',
83-
help='Specify alternate port [default: 8000]')
77+
parser.add_argument("--cgi", action="store_true", help="Run as CGI Server")
78+
parser.add_argument(
79+
"--bind",
80+
"-b",
81+
metavar="ADDRESS",
82+
help="Specify alternate bind address " "[default: all interfaces]",
83+
)
84+
parser.add_argument(
85+
"--directory",
86+
"-d",
87+
default=os.getcwd(),
88+
help="Specify alternative directory " "[default:current directory]",
89+
)
90+
parser.add_argument(
91+
"--css_file",
92+
default=None,
93+
help="css-file-path; its content will be written to the <style> element",
94+
)
95+
parser.add_argument(
96+
"--live_md_rr",
97+
"-l",
98+
action="store",
99+
type=int,
100+
default=None,
101+
help="Continuous refresh rate of MD page, in ms. Respects cache",
102+
)
103+
parser.add_argument(
104+
"port",
105+
action="store",
106+
default=8000,
107+
type=int,
108+
nargs="?",
109+
help="Specify alternate port [default: 8000]",
110+
)
84111
args = parser.parse_args()
85112
if args.cgi:
86113
handler_class = CGIHTTPRequestHandler
87114
else:
88-
MarkdownIt_obj = MarkdownIt("commonmark").enable("table").enable("strikethrough")
115+
MarkdownIt_obj = (
116+
MarkdownIt("commonmark").enable("table").enable("strikethrough")
117+
)
89118
if args.css_file and not os.path.isfile(args.css_file):
90-
raise FileNotFoundError(f"looks like the given `css_file` argument's value - {args.css_file} - cannot be found")
91-
handler_class = partial(md_to_html_SimpleHTTPRequestHandler,
92-
directory=args.directory,
93-
MarkdownIt_obj=MarkdownIt_obj,
94-
css_file=args.css_file,
95-
live_md_rr=args.live_md_rr)
119+
raise FileNotFoundError(
120+
f"looks like the given `css_file` argument's value - {args.css_file} - cannot be found"
121+
)
122+
handler_class = partial(
123+
md_to_html_SimpleHTTPRequestHandler,
124+
directory=args.directory,
125+
MarkdownIt_obj=MarkdownIt_obj,
126+
css_file=args.css_file,
127+
live_md_rr=args.live_md_rr,
128+
)
96129

97130
# ensure dual-stack is not disabled; ref #38907
98131
class DualStackServer(ThreadingHTTPServer):
99132
def server_bind(self):
100133
# suppress exception when protocol is IPv4
101134
with contextlib.suppress(Exception):
102-
self.socket.setsockopt(
103-
socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
135+
self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)
104136
return super().server_bind()
105137

106138
http_server_test(

0 commit comments

Comments
 (0)