Skip to content

Commit dc5c18f

Browse files
committed
file list now works on ESP
1 parent 856eef4 commit dc5c18f

File tree

2 files changed

+45
-31
lines changed

2 files changed

+45
-31
lines changed

gurgleapps_webserver.py

Lines changed: 37 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def __init__(self, wifi_ssid, wifi_password, port=80, timeout=20, doc_root="/www
5151
print('waiting for connection...')
5252
time.sleep(1)
5353

54-
#if self.wlan.status() != 3:
54+
# if self.wlan.status() != 3:
5555
if self.wlan.isconnected() == False:
5656
raise RuntimeError('network connection failed')
5757
else:
@@ -61,7 +61,7 @@ def __init__(self, wifi_ssid, wifi_password, port=80, timeout=20, doc_root="/www
6161
self.serving = True
6262
self.ip_address = status[0]
6363
print('point your browser to http://', status[0])
64-
#asyncio.new_event_loop()
64+
# asyncio.new_event_loop()
6565
print("exit constructor")
6666

6767
# async def start_server(self):
@@ -98,7 +98,7 @@ async def serve_request(self, reader, writer):
9898
post_data = None
9999
while True:
100100
line = await reader.readline()
101-
#print("line: "+str(line))
101+
# print("line: "+str(line))
102102
line = line.decode('utf-8').strip()
103103
if line == "":
104104
break
@@ -111,7 +111,7 @@ async def serve_request(self, reader, writer):
111111
method = match.group(1)
112112
url = match.group(2)
113113
print(method, url)
114-
else: # regex didn't match, try splitting the request line
114+
else: # regex didn't match, try splitting the request line
115115
request_parts = request_raw.split(" ")
116116
if len(request_parts) > 1:
117117
method = request_parts[0]
@@ -146,7 +146,7 @@ async def serve_request(self, reader, writer):
146146
file_path = self.doc_root + url
147147
if self.log_level > 0:
148148
print("file_path: "+str(file_path))
149-
#if uos.stat(file_path)[6] > 0:
149+
# if uos.stat(file_path)[6] > 0:
150150
if self.file_exists(file_path):
151151
content_type = self.get_content_type(url)
152152
if self.log_level > 1:
@@ -156,6 +156,8 @@ async def serve_request(self, reader, writer):
156156
if url == "/":
157157
print("root")
158158
files_and_folders = self.list_files_and_folders(self.doc_root)
159+
await response.send_iterator(self.generate_root_page_html(files_and_folders))
160+
return
159161
html = self.generate_root_page_html(files_and_folders)
160162
await response.send(html)
161163
return
@@ -171,7 +173,7 @@ def dir_exists(self, filename):
171173
return (os.stat(filename)[0] & 0x4000) != 0
172174
except OSError:
173175
return False
174-
176+
175177
def file_exists(self, filename):
176178
try:
177179
return (os.stat(filename)[0] & 0x4000) == 0
@@ -228,8 +230,7 @@ def get_file_extension(self, file_path):
228230
return file_parts[-1]
229231
return ''
230232

231-
232-
def get_content_type(self,file_path):
233+
def get_content_type(self, file_path):
233234
extension = self.get_file_extension(file_path)
234235
content_type_map = {
235236
'html': 'text/html',
@@ -257,7 +258,7 @@ def get_content_type(self,file_path):
257258
return content_type_map.get(extension, 'text/plain')
258259

259260
# long pause for dots 4 quick blinks for zero 2 quick for a dot
260-
async def blink_ip(self, led_pin, ip = None, repeat=2, delay_between_digits=0.9, last_only = False):
261+
async def blink_ip(self, led_pin, ip=None, repeat=2, delay_between_digits=0.9, last_only=False):
261262
delay_between_repititions = 2
262263
if ip == None:
263264
ip = self.ip_address
@@ -285,14 +286,17 @@ def blink_element(element, pin, duration=0.27):
285286
ip_digits_and_dots = []
286287
ip_parts = ip.split('.')
287288
if last_only:
288-
ip_parts = [ip_parts[-1]] # Only blink the last part of the IP address
289+
# Only blink the last part of the IP address
290+
ip_parts = [ip_parts[-1]]
289291

290292
for part in ip_parts:
291293
for digit in part:
292294
ip_digits_and_dots.append(int(digit))
293-
ip_digits_and_dots.append('.') # Add a dot to the list to represent the separator
295+
# Add a dot to the list to represent the separator
296+
ip_digits_and_dots.append('.')
294297
ip_digits_and_dots.pop() # Remove the last dot
295-
ip_digits_and_dots.append('-') # Add a dash to the list to represent the end of the IP address
298+
# Add a dash to the list to represent the end of the IP address
299+
ip_digits_and_dots.append('-')
296300

297301
for _ in range(repeat):
298302
for element in ip_digits_and_dots:
@@ -313,6 +317,18 @@ def list_files_and_folders(self, path):
313317
return files_and_folders
314318

315319
def generate_root_page_html(self, files_and_folders):
320+
yield """
321+
<!DOCTYPE html>
322+
<html>
323+
<head>
324+
<title>GurgleApps.com Webserver</title>
325+
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
326+
</head>
327+
<body class="bg-gray-100">
328+
<div class="container mx-auto p-8">
329+
<h1 class="text-3xl font-bold mb-4">Welcome to GurgleApps.com Webserver</h1>
330+
<h2 class="text-2xl mb-2">File List:</h2>
331+
"""
316332
folder_icon_svg = """
317333
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="inline-block w-6 h-6">
318334
<path d="M4 4a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V8a2 2 0 00-2-2H9.586A2 2 0 018 6H4z" />
@@ -323,26 +339,16 @@ def generate_root_page_html(self, files_and_folders):
323339
<path d="M6 2a2 2 0 00-2 2v12a2 2 0 002 2h8a2 2 0 002-2V7.414A2 2 0 0016.414 6L13 2.586A2 2 0 0011.414 2H6z" />
324340
</svg>
325341
"""
326-
file_list_html = "<ul class='list-none'>"
342+
yield "<ul class='list-none'>"
327343
for file_or_folder in files_and_folders:
328-
icon = folder_icon_svg if file_or_folder['type']=='directory' else file_icon_svg
329-
file_list_html += f"<li class='my-2'><a href='/{file_or_folder['name']}' class='text-blue-600 hover:text-blue-800'>{icon} {file_or_folder['name']}</a></li>"
330-
file_list_html += "</ul>"
331-
332-
html_content = f"""
333-
<!DOCTYPE html>
334-
<html>
335-
<head>
336-
<title>GurgleApps.com Webserver</title>
337-
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
338-
</head>
339-
<body class="bg-gray-100">
340-
<div class="container mx-auto p-8">
341-
<h1 class="text-3xl font-bold mb-4">Welcome to GurgleApps.com Webserver</h1>
342-
<h2 class="text-2xl mb-2">File List:</h2>
343-
{file_list_html}
344-
</div>
344+
icon = folder_icon_svg if file_or_folder['type'] == 'directory' else file_icon_svg
345+
yield f"<li class='my-2'><a href='/{file_or_folder['name']}' class='text-blue-600 hover:text-blue-800'>{icon} {file_or_folder['name']}</a></li>"
346+
yield "</ul>"
347+
# Closing tags for the body and container div
348+
yield """
349+
</div>
345350
</body>
346351
</html>
347352
"""
348-
return html_content
353+
354+

response.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,11 @@ async def send_file(self, file_path, status_code=200, content_type="text/html"):
4343
except Exception as e:
4444
print("Error sending file:", e)
4545
await self.send('', status_code=404)
46+
47+
async def send_iterator(self, iterator, status_code=200, content_type="text/html"):
48+
await self.send_headers(status_code=status_code, content_type=content_type)
49+
for chunk in iterator:
50+
self.writer.write(chunk)
51+
await self.writer.drain()
52+
await self.writer.wait_closed()
53+

0 commit comments

Comments
 (0)