Skip to content

Instantly share code, notes, and snippets.

@MeexReay
Last active September 25, 2023 14:09
Show Gist options
  • Save MeexReay/a5492af64695a206406e483a3a891b3d to your computer and use it in GitHub Desktop.
Save MeexReay/a5492af64695a206406e483a3a891b3d to your computer and use it in GitHub Desktop.
изи сайт на пайтоне
import socket
import threading
import traceback
from urllib.parse import unquote
import json
class mxsite:
def __init__(self):
self.sock = socket.socket()
self.running = False
def callback(self, path, method, params, addr, headers):
print(addr,">",path)
h = json.dumps(headers,indent=1).replace('\n','<br>')
return {
"code": "200 OK",
"content": f"<b>path=</b>{path}<br>" \
f"<b>method=</b>{method}<br>" \
f"<b>params=</b>{params}<br>" \
f"<b>addr=</b>{addr}<br>" \
f"<b>headers=</b>{h}",
"content-type": "text/html",
"headers": {}
}
def decode_url_params(self, p):
params = {}
for x in p.split("&"):
y = x.split("=")
params[unquote(y[0])] = unquote(y[1])
return params
def process(self, conn: socket.socket, addr):
addr = ":".join([str(i) for i in addr])
try:
data = conn.recv(1024*4).decode("utf8")
lines = data.split("\r\n")
method, path = lines[0].split(" ")[:2]
params = {}
if "?" in path:
params = self.decode_url_params(path.split("?")[1])
path = path.split("?")[0]
if lines[-1] != "":
params.update(self.decode_url_params(lines[-1]))
headers = {}
for i in lines[1:]:
if i != "":
ss = i.split(":")
if len(ss) == 2:
if ss[1].startswith(" "):
ss[1] = ss[1][1:]
headers[ss[0]] = ss[1]
callback = self.callback(path,method,params,addr,headers)
cbheaders = "\r\n"
for k,v in callback["headers"]:
cbheaders += k+": "+v+"\r\n"
response = f"HTTP/1.1 {callback['code']}\r\n" \
f"Content-Length: {len(callback['content'])}\r\n" \
f"Content-Type: {callback['content-type']}\r\n" \
f"Connection: Closed{cbheaders}\r\n{callback['content']}"
conn.send(response.encode())
conn.close()
except Exception as e:
traceback.print_exc()
def close(self):
self.running = False
self.sock.close()
def run(self, host):
self.sock.bind(host)
self.running = True
print("Site started at", host)
self.sock.listen()
while self.running:
threading.Thread(
target=self.process,
args=self.sock.accept(),
daemon=True
).start()
if __name__ == "__main__":
class my_site(mxsite):
def callback(self, path, method, params, addr, headers):
print(addr,">",path)
return {
"code": "200 OK", # статус код (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
"content": "hellow orld", # контент страницы
"content-type": "text/html", # тип контента (https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types)
"headers": {} # дополнительные хедеры
}
my_site().run(("localhost",8080))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment