forked from cp-algorithms/cp-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
71 lines (61 loc) · 2.06 KB
/
main.py
File metadata and controls
71 lines (61 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from bs4 import BeautifulSoup
import time
def main(request):
# Set CORS headers for the preflight request
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
request_json = request.get_json()
md_content = request_json['markdown']
with TemporaryDirectory() as tmpdirname:
html_content = render(md_content, tmpdirname)
headers = {
'Access-Control-Allow-Origin': '*'
}
return (html_content, 200, headers)
def render(markdown: str, directory: str) -> str:
# prepare file structure and configuration for MkDocs
tmp_path = Path(str(directory))
(tmp_path / "docs").mkdir(parents=True, exist_ok=True)
(tmp_path / "mkdocs.yml").write_text("""
site_name: CP Algorithms
theme:
name: material
markdown_extensions:
- pymdownx.arithmatex:
generic: true
- pymdownx.highlight
- admonition
- pymdownx.details
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
- attr_list
- pymdownx.emoji:
emoji_index: !!python/name:materialx.emoji.twemoji
emoji_generator: !!python/name:materialx.emoji.to_svg
plugins:
- macros
""")
(tmp_path / "docs" / "index.md").write_text(markdown)
# render the page
start_time = time.time()
subprocess.run(['mkdocs', 'build', '--dirty'], cwd=tmp_path)
print(f"finish dirty build: {time.time() - start_time:2.5f}s")
# extract the main content (without header/footer/...)
with open(tmp_path / "site" / "index.html") as fp:
soup = BeautifulSoup(fp, "html.parser")
article = soup.find("article")
article_html = ''.join([str(x) for x in article])
return article_html
if __name__ == "__main__":
with TemporaryDirectory() as tmpdirname:
print(render("# H1", tmpdirname))