This repository has been archived on 2022-01-01. You can view files and clone it, but cannot push or open issues or pull requests.
Web/generate_errors.py

57 lines
1.7 KiB
Python
Raw Permalink Normal View History

2021-12-29 14:35:11 +01:00
from pprint import pp
from pathlib import Path
from urllib import request
import re
2022-01-01 14:50:44 +01:00
urlroot = 'https://www.w3.org/Protocols/rfc2616'
2021-12-29 14:35:11 +01:00
src = Path('src')
root = src.joinpath('error')
with root.joinpath('root.html').open('r') as root_file:
root_html = root_file.read()
with root.joinpath('root.css').open('r') as root_file:
root_css = root_file.read()
error = Path('dist_error')
error.mkdir(exist_ok=True)
for x in error.rglob('*'):
if x.is_file() or x.is_symlink(): x.unlink()
req = request.Request(
2022-01-01 14:50:44 +01:00
f'{urlroot}/rfc2616-sec10.html',
2021-12-29 14:35:11 +01:00
method='GET')
with request.urlopen(req) as res:
raw = res.read().decode('utf-8')
2022-01-01 14:50:44 +01:00
codes = (re.finditer(r"(?s)<h3><a id='(sec10\.[0-9]\.[0-9]+)'>"
2021-12-29 14:35:11 +01:00
r'10\.[0-9]\.[0-9]+</a>'
r'\s*([0-9]+)\s([a-zA-Z\s]+)</h3>\s*<p>(.*?)</p>', raw))
nginx_head = ''
nginx_body = ''
for item in codes:
2022-01-01 14:50:44 +01:00
sec, code, title, desc = item.groups()
2021-12-29 14:50:58 +01:00
if int(code) < 400 or int(code) >= 600: continue
2022-01-01 14:50:44 +01:00
desc = re.sub(r"(<a.*?href=')(.*)('>)",
lambda x:f'{x[1]}{urlroot}/{x[2]}{x[3]}', desc)
2021-12-29 14:35:11 +01:00
with error.joinpath(f'{code}.html').open('w') as html:
content = root_html.format(
2022-01-01 14:50:44 +01:00
code=code, title=title, desc=desc, style=root_css, sec=sec)
content = re.sub(r'\s+', ' ', content)
content = re.sub(r'>\s<', '><', content)
html.write(content)
2021-12-29 14:35:11 +01:00
nginx_head += f'error_page {code} @error{code};\n'
nginx_body += f'location @error{code} {{\n'\
f'root {error.resolve()};\n'\
f'try_files /{code}.html /{code}.html;\n'\
'internal;}\n'
with error.joinpath(f'nginx.conf').open('w') as nginx_file:
nginx_file.write(f'{nginx_head}\n{nginx_body}\n\n'\
'proxy_intercept_errors on;')