|
import re |
|
from os import system |
|
from os.path import abspath |
|
try: |
|
import usocket as socket |
|
except: |
|
import socket |
|
|
|
|
|
response_headers = { |
|
"Cache-Control": "no-cache" |
|
} |
|
|
|
def make_response(body): |
|
s = 'HTTP/1.0 200 OK\r\n{header}\r\n\r\n{body}' |
|
header = '\r\n'.join(':'.join([k, v]) for k, v in response_headers.items()) |
|
return s.format(header=header, body=body) |
|
|
|
def respond(request): |
|
if str(request) == '': |
|
return '' |
|
path_raw = str(request).split(' ')[1] |
|
path = path_raw.split('/') |
|
|
|
if path_raw == '/': |
|
with open(abspath('./statics/main.html')) as f: |
|
return make_response(f.read()) |
|
elif path[-1] in ['f', 's', 'b']: |
|
system(abspath('./drive.sh %s' % path[-1])) |
|
return 'HTTP/1.0 200 OK' |
|
elif any(path[-1].endswith(x) for x in ['js', 'css']): |
|
with open(abspath('./statics/{}'.format(path[-1]))) as f: |
|
return make_response(f.read()) |
|
else: |
|
return 'HTTP/1.0 404' |
|
|
|
def main(micropython_optimize=False): |
|
s = socket.socket() |
|
ai = socket.getaddrinfo("0.0.0.0", 8080) |
|
print("Bind address info:", ai) |
|
addr = ai[0][-1] |
|
|
|
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
|
s.bind(addr) |
|
s.listen(5) |
|
print("Ready: <host_ip>:8080") |
|
|
|
counter = 0 |
|
while True: |
|
res = s.accept() |
|
client_sock = res[0] |
|
client_addr = res[1] |
|
print("Client address:", client_addr) |
|
print("Client socket:", client_sock) |
|
|
|
if not micropython_optimize: |
|
client_stream = client_sock.makefile("rwb") |
|
else: |
|
client_stream = client_sock |
|
|
|
print("Request:") |
|
req = client_stream.readline() |
|
print(req) |
|
while True: |
|
h = client_stream.readline() |
|
if h == b"" or h == b"\r\n": |
|
break |
|
print(h) |
|
client_stream.write(respond(req)) |
|
|
|
client_stream.close() |
|
if not micropython_optimize: |
|
client_sock.close() |
|
counter += 1 |
|
print() |
|
|
|
main() |