Skip to content

Instantly share code, notes, and snippets.

@imeesa
Created August 18, 2021 14:59
Show Gist options
  • Save imeesa/40f58713359cba3dd7d58e9b9a9b7841 to your computer and use it in GitHub Desktop.
Save imeesa/40f58713359cba3dd7d58e9b9a9b7841 to your computer and use it in GitHub Desktop.
from http.server import BaseHTTPRequestHandler
import socketserver
from functools import reduce
import urllib
urllib.parse.unquote('%20hello')
def parentfolder(path):
path = path.replace('\\', '/')
splitpath = path.split('/')[:-1]
outpath = splitpath[0]
for folder in splitpath[1:]:
outpath += '/'
outpath += folder
return outpath
def render(html, replacedict={}):
keys = ['{{'+key+'}}' for key in replacedict.keys()]
replacedhtml = reduce(lambda x, y: x.replace(
'{{'+y+'}}', replacedict[y]), replacedict, html)
return bytes(replacedhtml, 'utf8')+b'<br><br><br><br><br><noformat id="centeredstrawberryframework"><img src="/Logos/strawberrylogoplaceit.png" alt="Strawberry"></noformat>'
chatlist = list()
chatdict = dict(main = chatlist)
def add(*args):
total=type(args[0])()
for x in args:
if not type(x) ==list:
total += x
else:
for y in x: total+=y
return total
class ChatHandler(BaseHTTPRequestHandler):
def do_GET(self):
global chatdict
if self.path.split('/')[0] or 'main' in chatdict.keys():
pass
else: chatdict[self.path.split('/')[-1] or 'main'] = []
chatlist1 = chatdict[self.path.split('/')[0] or 'main']
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(add(b'<html>\n<body>\n', list(map(lambda x: x.encode(), chatlist1)), b'\n<form method="POST" enctype="multipart/formdata" action="/', self.path.split('/')[-1].encode() or b'main' , b'/msg">\n<input type="text" name="message">\n<input type="submit" value="Send">\n</form>\n</body>\n</html>'))
def do_POST(self):
if self.path.endswith('/msg'):
index = self.path.split('/')[-2]
global chatdict
content_len = int(self.headers.get('content-length', 0))
post_body = str(self.rfile.read(content_len))
chatdict[index].append(
urllib.parse.unquote(
self.client_address[0]+': '+post_body[10:][:-1].replace('+', ' ')+'<br>'
)
)
self.send_response(301)
self.send_header('Location', '/'+index)
self.end_headers()
PORT = 8080
Handler = ChatHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:#, Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment