Skip to content

Commit e27aab7

Browse files
committed
move from HtmlOnlyHandler to ExtendedHandler
to support various content types and CORS origin. also re-wrote the `do_POST` method for efficiency
1 parent cde43bc commit e27aab7

File tree

1 file changed

+50
-43
lines changed

1 file changed

+50
-43
lines changed

py/test/selenium/webdriver/common/webserver.py

Lines changed: 50 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -58,68 +58,75 @@ def updir():
5858
DEFAULT_PORT = 8000
5959

6060

61-
class HtmlOnlyHandler(BaseHTTPRequestHandler):
61+
class ExtendedHandler(BaseHTTPRequestHandler):
6262
"""Http handler."""
6363

64+
def _set_headers(self, content_type="text/html"):
65+
"""Sets response headers with CORS support."""
66+
self.send_response(200)
67+
self.send_header("Content-type", content_type)
68+
self.send_header("Access-Control-Allow-Origin", "*")
69+
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
70+
self.send_header("Access-Control-Allow-Headers", "Content-Type")
71+
self.end_headers()
72+
6473
def do_GET(self):
6574
"""GET method handler."""
6675
try:
6776
path = self.path[1:].split("?")[0]
68-
if path[:5] == "page/":
69-
html = """<html><head><title>Page{page_number}</title></head>
70-
<body>Page number <span id=\"pageNumber\">{page_number}</span>
71-
<p><a href=\"../xhtmlTest.html\" target=\"_top\">top</a>
72-
</body></html>""".format(
73-
page_number=path[5:]
74-
)
75-
html = html.encode("utf-8")
77+
file_path = os.path.join(HTML_ROOT, path)
78+
file_extension = os.path.splitext(path)[1]
79+
80+
# Serve dynamic HTML page for specific "page/" paths
81+
if path.startswith("page/"):
82+
page_number = path[5:]
83+
html = f"""<html><head><title>Page{page_number}</title></head>
84+
<body>Page number <span id="pageNumber">{page_number}</span>
85+
<p><a href="../xhtmlTest.html" target="_top">top</a></p>
86+
</body></html>"""
87+
self._set_headers("text/html")
88+
self.wfile.write(html.encode("utf-8"))
89+
return
90+
91+
# Serve file contents based on file extension
92+
if os.path.isfile(file_path):
93+
if file_extension == ".json":
94+
content_type = "application/json"
95+
elif file_extension == ".html":
96+
content_type = "text/html"
97+
else:
98+
content_type = "application/octet-stream"
99+
100+
with open(file_path, encoding="latin-1") as f:
101+
content = f.read().encode("utf-8")
102+
self._set_headers(content_type)
103+
self.wfile.write(content)
76104
else:
77-
with open(os.path.join(HTML_ROOT, path), encoding="latin-1") as f:
78-
html = f.read().encode("utf-8")
79-
self.send_response(200)
80-
self.send_header("Content-type", "text/html")
81-
self.end_headers()
82-
self.wfile.write(html)
105+
self.send_error(404, f"File Not Found: {path}")
83106
except OSError:
84107
self.send_error(404, f"File Not Found: {path}")
85108

86109
def do_POST(self):
87110
"""POST method handler."""
88111
try:
89112
remaining_bytes = int(self.headers["content-length"])
90-
contents = ""
91-
line = self.rfile.readline()
92-
contents += line.decode("utf-8")
93-
remaining_bytes -= len(line)
94-
line = self.rfile.readline()
95-
contents += line.decode("utf-8")
96-
remaining_bytes -= len(line)
97-
fn = re.findall(r'Content-Disposition.*name="upload"; filename="(.*)"', line.decode("utf-8"))
98-
if not fn:
99-
self.send_error(500, f"File not found. {contents}")
113+
contents = self.rfile.read(remaining_bytes).decode("utf-8")
114+
115+
# Check for file upload in POST content
116+
fn_match = re.search(r'Content-Disposition.*name="upload"; filename="(.*)"', contents)
117+
if not fn_match:
118+
self.send_error(500, f"File not found in content. {contents}")
100119
return
101-
line = self.rfile.readline()
102-
remaining_bytes -= len(line)
103-
contents += line.decode("utf-8")
104-
line = self.rfile.readline()
105-
remaining_bytes -= len(line)
106-
contents += line.decode("utf-8")
107-
preline = self.rfile.readline()
108-
remaining_bytes -= len(preline)
109-
while remaining_bytes > 0:
110-
line = self.rfile.readline()
111-
remaining_bytes -= len(line)
112-
contents += line.decode("utf-8")
113-
114-
self.send_response(200)
115-
self.send_header("Content-type", "text/html")
116-
self.end_headers()
117120

121+
# Send response with the uploaded content and completion script
122+
self._set_headers("text/html")
118123
self.wfile.write(
119124
f"""<!doctype html>
120125
{contents}
121126
<script>window.top.window.onUploadDone();</script>
122-
""".encode()
127+
""".encode(
128+
"utf-8"
129+
)
123130
)
124131
except Exception as e:
125132
self.send_error(500, f"Error found: {e}")
@@ -142,7 +149,7 @@ def __init__(self, host=DEFAULT_HOST_IP, port=DEFAULT_PORT):
142149
port = port
143150
while True:
144151
try:
145-
self.server = ThreadedHTTPServer((host, port), HtmlOnlyHandler)
152+
self.server = ThreadedHTTPServer((host, port), ExtendedHandler)
146153
self.host = host
147154
self.port = port
148155
break

0 commit comments

Comments
 (0)