minor ahh update
This commit is contained in:
1 parent
b0e4a8c496
commit
88d4ce7320
8 files changed
+1240
-453
No files matched your search
+99
@@ -0,0 +1,99 @@
|
||||
# Environment variables
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Virtual environments
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
# IDEs and editors
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# Database
|
||||
*.sqlite3
|
||||
*.db
|
||||
|
||||
# Compiled source
|
||||
*.com
|
||||
*.class
|
||||
*.dll
|
||||
*.exe
|
||||
*.o
|
||||
*.so
|
||||
|
||||
# Packages
|
||||
*.7z
|
||||
*.dmg
|
||||
*.gz
|
||||
*.iso
|
||||
*.jar
|
||||
*.rar
|
||||
*.tar
|
||||
*.zip
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
Pipfile.lock
|
||||
|
||||
# poetry
|
||||
poetry.lock
|
||||
|
||||
# Coverage reports
|
||||
htmlcov/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
coverage.xml
|
||||
*.cover
|
||||
|
||||
# haha what is the above part claude i dont know
|
||||
|
||||
non git user
|
||||
+79
-352
@@ -4,367 +4,22 @@ go dam
|
||||
"""
|
||||
|
||||
import http.server as serverhttp
|
||||
|
||||
from the_server_handler import ServerLogic, connectionSettings, get_that_connection
|
||||
import mysql.connector as sqlcon
|
||||
import json
|
||||
import sql
|
||||
|
||||
# import datetime
|
||||
# import os
|
||||
from dotenv import dotenv_values
|
||||
|
||||
# from typing import Callable, Dict, Any
|
||||
|
||||
from things import (
|
||||
funny_trycatch_wrapper,
|
||||
process_tuples,
|
||||
funny_tuples_to_dicts_processor,
|
||||
) # no way its the funny trycatch wrapper
|
||||
|
||||
dotenv_values1 = dotenv_values()
|
||||
db_name = dotenv_values1["db_name"]
|
||||
# he really did that
|
||||
# from mysql.connector import errorcode
|
||||
comectomKeys = ["user", "password", "host", "database"]
|
||||
comectomtrk = {
|
||||
"db_user": "user",
|
||||
"db_password": "password",
|
||||
"db_host": "host",
|
||||
"db_name": "database",
|
||||
}
|
||||
|
||||
# def getnewdict(d:dict, l:list) -> dict:
|
||||
# r = dict()
|
||||
# for k in d:
|
||||
# if k in l:
|
||||
# r[k] = d[k]
|
||||
# return r
|
||||
getnewdict = lambda d, l: {k: d[k] for k in d if k in l}
|
||||
|
||||
# def getnewdicttranslate(d:dict, tltb:dict) -> dict:
|
||||
# r = dict()
|
||||
# for k in d:
|
||||
# if k in tltb:
|
||||
# r[tltb[k]] = d[k]
|
||||
# return r
|
||||
getnewdicttranslate = lambda d, tltb: {tltb[k]: d[k] for k in d if k in tltb}
|
||||
|
||||
|
||||
connectionSettings = {
|
||||
**getnewdicttranslate(dotenv_values1, comectomtrk),
|
||||
"raise_on_warnings": True,
|
||||
}
|
||||
|
||||
|
||||
# quer = "insert into tbale (kewod, id) values (%s, %s);" # do not support custom key Only if
|
||||
# vals = (
|
||||
# r"faf",
|
||||
# r"24",
|
||||
# )
|
||||
tablesql = sql.Table(name="tbale", database=db_name)
|
||||
|
||||
tablesql.select()
|
||||
|
||||
|
||||
def get_that_connection(
|
||||
connectionSettings: dict,
|
||||
) -> tuple: # the giving up is real
|
||||
try:
|
||||
connectio = sqlcon.connect(**connectionSettings)
|
||||
except sqlcon.Error as e:
|
||||
return (None, e)
|
||||
else:
|
||||
return (connectio, None)
|
||||
|
||||
|
||||
class ServerLogic(serverhttp.BaseHTTPRequestHandler):
|
||||
# def __do_POST2(self):
|
||||
# if self.path == "/close":
|
||||
# return self.close()
|
||||
# self.header_setup()
|
||||
# content_length = int(self.headers["Content-Length"])
|
||||
# with self.rfile as r:
|
||||
# post_data_bytes = self.rfile.read(content_length)
|
||||
# self.wfile.write(
|
||||
# b"MY SERVER: The post data I received from the request has following data:\n"
|
||||
# + post_data_bytes
|
||||
# )
|
||||
# try:
|
||||
# data_dict = json.loads(post_data_bytes.decode("utf-8"))
|
||||
# except Exception as e:
|
||||
# print(e)
|
||||
# try:
|
||||
# connectio = sqlcon.connect(**connectionSettings)
|
||||
# connectio.autocommit = True # EUYOEYOEYOEYOEYO
|
||||
# except sqlcon.Error as e:
|
||||
# print(e.errno, e.msg)
|
||||
# else:
|
||||
# with connectio.cursor(buffered=True) as cur:
|
||||
# try:
|
||||
# res = cur.execute(
|
||||
# "insert into tbale (kewod, id) values (%s, %s)",
|
||||
# (
|
||||
# data_dict["kewod"],
|
||||
# data_dict["id"],
|
||||
# ),
|
||||
# multi=True,
|
||||
# )
|
||||
|
||||
# print(res)
|
||||
# except Exception as e:
|
||||
# print("execute err: ", e)
|
||||
# self.wfile.write(b"\n is it very much Invalid." + str(e).encode())
|
||||
# else:
|
||||
# print(cur)
|
||||
# cur.execute("select * from tbale")
|
||||
# self.wfile.write(
|
||||
# b"\n We have this in the this: "
|
||||
# + str.encode(str(cur.fetchall()))
|
||||
# )
|
||||
# return
|
||||
# def __do_GET2(self):
|
||||
# if self.path == "/close":
|
||||
# return self.close()
|
||||
|
||||
# self.header_setup()
|
||||
# try:
|
||||
# connectio = sqlcon.connect(**connectionSettings)
|
||||
# except sqlcon.Error as e:
|
||||
# print(e)
|
||||
# else:
|
||||
# with connectio.cursor(buffered=True, raw=True) as cur:
|
||||
# try:
|
||||
# res = cur.execute("select * from tbale")
|
||||
# w = cur.fetchall()
|
||||
# except Exception as e:
|
||||
# print(e)
|
||||
# else:
|
||||
# print(w)
|
||||
# self.wfile.write(bytes(w).decode())
|
||||
# return
|
||||
# def __close2(self):
|
||||
# try:
|
||||
# self.server.server_close()
|
||||
# except BaseException as e:
|
||||
# print(e)
|
||||
# finally:
|
||||
# print("gato")
|
||||
# raise SystemExit("truly the /close")
|
||||
|
||||
def youJustHaveToDoTheseStuff(self):
|
||||
# print(self.headers)
|
||||
print("the path is : ", self.path)
|
||||
print("the entire headers:\n", self.headers.as_string())
|
||||
# print(self.headers.get(""))
|
||||
|
||||
def close(self):
|
||||
funny_trycatch_wrapper(
|
||||
tries=[(self.server.server_close)],
|
||||
finallies=[(print, ("gato")), ('raise SystemExit("truly the /close")')],
|
||||
)
|
||||
|
||||
def header_setup(
|
||||
self, code: int = 200, headers: dict = {"Content-type": "text/html"}
|
||||
):
|
||||
self.send_response(code)
|
||||
if headers is not None:
|
||||
for key in headers:
|
||||
self.send_header(key, headers[key]) # why!
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
self.youJustHaveToDoTheseStuff()
|
||||
|
||||
if self.path == "/close":
|
||||
return self.close()
|
||||
|
||||
if self.path == "/":
|
||||
self.header_setup()
|
||||
with open("index.html", "rb") as file:
|
||||
self.wfile.write(file.read())
|
||||
return
|
||||
|
||||
(connectio, eror) = get_that_connection(connectionSettings)
|
||||
if eror:
|
||||
print("coneti eror: ", eror)
|
||||
return
|
||||
# HE. MUST. AVOID. THE. TRYCATCH
|
||||
with connectio.cursor(buffered=True) as cur:
|
||||
try:
|
||||
res = cur.execute("select * from tbale")
|
||||
w = cur.fetchall()
|
||||
anotherone = cur.execute(
|
||||
"select column_name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbale'"
|
||||
)
|
||||
anotherone2 = cur.fetchall()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return # return ealy no else
|
||||
c = process_tuples(w)
|
||||
efg = funny_tuples_to_dicts_processor(anotherone2, c)
|
||||
|
||||
if self.path == "/endp":
|
||||
self.header_setup(headers={"Content-type": "application/json"})
|
||||
# print(w, c, sep="\n")
|
||||
# self.wfile.write(str(c).encode())
|
||||
# self.wfile.write(str(anotherone2).encode())
|
||||
self.wfile.write(str(efg).encode())
|
||||
return
|
||||
else:
|
||||
wd = [(a["neme"], a["kewod"], a["cod"]) for a in efg]
|
||||
# print(wd)
|
||||
for a, v, c in wd:
|
||||
# print(a,v)
|
||||
# print(self.path, a)
|
||||
if self.path.lstrip("/") == a:
|
||||
if c == 200:
|
||||
self.header_setup(c)
|
||||
self.wfile.write(v.encode())
|
||||
elif c in [301, 302]:
|
||||
self.header_setup(c, {"Location": v})
|
||||
return
|
||||
self.header_setup(404)
|
||||
self.wfile.write(
|
||||
b"""
|
||||
<h1>404</h1>
|
||||
<p>where u at</p>
|
||||
"""
|
||||
)
|
||||
return
|
||||
|
||||
def do_POST(self):
|
||||
self.youJustHaveToDoTheseStuff()
|
||||
|
||||
match self.path:
|
||||
case "/close":
|
||||
return self.close()
|
||||
|
||||
case "/endp":
|
||||
self.header_setup(headers={"Content-type": "text/plain"})
|
||||
content_type = self.headers.get("Content-Type")
|
||||
content_length = int(self.headers.get("Content-Length"))
|
||||
with self.rfile as r:
|
||||
post_data_bytes = r.read(content_length)
|
||||
## read how many bytes is the content length
|
||||
|
||||
self.wfile.write(
|
||||
b"Ive got a POST at "
|
||||
+ self.headers.get("Origin", "nowhere lmao").encode()
|
||||
+ b" from "
|
||||
+ self.headers.get("Referer", "who?").encode()
|
||||
+ b" with the following data:\n"
|
||||
+ post_data_bytes
|
||||
)
|
||||
if content_type == "application/json":
|
||||
try:
|
||||
data_dict: dict = json.loads(post_data_bytes)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.wfile.write(
|
||||
b"\nhaha your data sucks (json.load is strict/bad): "
|
||||
+ str(e).encode()
|
||||
)
|
||||
return
|
||||
(connectio, eror) = get_that_connection(connectionSettings)
|
||||
if eror:
|
||||
print("coneti eror: ", eror)
|
||||
self.wfile.write(
|
||||
b"the thing cant even start like what f: "
|
||||
+ str(eror).encode()
|
||||
)
|
||||
return
|
||||
connectio.autocommit = True
|
||||
print((*data_dict.keys(), *data_dict.values()))
|
||||
with connectio.cursor(buffered=True) as cur:
|
||||
try:
|
||||
anotherone = cur.execute(
|
||||
"select column_name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbale'"
|
||||
)
|
||||
this_list_of_colnaes = cur.fetchall()
|
||||
except Exception as e:
|
||||
print("to day i cant get the damn colum")
|
||||
this_list_of_colnaes = [u[0] for u in this_list_of_colnaes] # weird
|
||||
if data_dict:
|
||||
# tehwe: list = []
|
||||
# for key in data_dict:
|
||||
# if key in this_list_of_colnaes:
|
||||
# tehwe.append(key)
|
||||
if data_dict.get("from") == "ldlda":
|
||||
ogdata_dict = data_dict.copy()
|
||||
hehedata_dict = ogdata_dict["data"]
|
||||
data_dict = getnewdicttranslate(
|
||||
hehedata_dict,
|
||||
{
|
||||
"one": "neme",
|
||||
"two": "kewod",
|
||||
"three": "cod",
|
||||
"four": "expi",
|
||||
},
|
||||
)
|
||||
print(data_dict)
|
||||
wwwww = tuple(
|
||||
key for key in data_dict if key in this_list_of_colnaes
|
||||
)
|
||||
# hmmm
|
||||
# repated cod? huh?
|
||||
|
||||
# updated_Verybreakablequery_insert_into = (
|
||||
# f"insert into tbale {wwwww} values {tuple('?'* len(wwwww))}"
|
||||
updated_Verybreakablequery_insert_into = (
|
||||
"insert into tbale ({0}) values ({0})".format(
|
||||
",".join(["{}"] * len(wwwww))
|
||||
).format(*wwwww, *("?",) * len(wwwww))
|
||||
)
|
||||
print(
|
||||
wwwww,
|
||||
tuple(data_dict[w] for w in wwwww),
|
||||
updated_Verybreakablequery_insert_into,
|
||||
sep="\n",
|
||||
)
|
||||
with connectio.cursor(prepared=True) as cur:
|
||||
try:
|
||||
res = cur.execute(
|
||||
updated_Verybreakablequery_insert_into,
|
||||
tuple(data_dict[w] for w in wwwww),
|
||||
multi=True,
|
||||
)
|
||||
print("insert into qure: ", cur.fetchall())
|
||||
another = cur.execute("select * from tbale")
|
||||
w2f = cur.fetchall()
|
||||
except Exception as e:
|
||||
print("execute err: ", e)
|
||||
self.wfile.write(
|
||||
b"\n is it very much Invalid: " + str(e).encode()
|
||||
)
|
||||
else:
|
||||
# print(cur)
|
||||
# cur.execute("select * from tbale")
|
||||
# aq142 = cur.fetchall()
|
||||
self.wfile.write(b"\n We have this in the this: ")
|
||||
# self.do_GET()
|
||||
self.wfile.write(str(process_tuples(w2f)).encode())
|
||||
## WHAT THE FUCK IS THIS PART
|
||||
else:
|
||||
self.wfile.write(b"\nits of the type: ")
|
||||
self.wfile.write(content_type.encode())
|
||||
case _:
|
||||
self.header_setup(403)
|
||||
self.wfile.write(
|
||||
b"""
|
||||
<h1>403</h1>
|
||||
<p>tf u doin</p>
|
||||
"""
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
def runServer():
|
||||
|
||||
# while True:
|
||||
# connectio,e = get_that_connection(**connectionSettings)
|
||||
# if not e:
|
||||
# break
|
||||
server = serverhttp.HTTPServer(("", 8088), ServerLogic)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
server.server_close()
|
||||
# connectio.close()
|
||||
raise SystemExit("\nctrl c")
|
||||
except BaseException as e:
|
||||
print(e)
|
||||
@@ -372,3 +27,75 @@ def runServer():
|
||||
|
||||
if __name__ == "__main__":
|
||||
runServer()
|
||||
|
||||
|
||||
# import sql
|
||||
|
||||
# import datetime
|
||||
# import os
|
||||
# from dotenv import dotenv_values
|
||||
|
||||
# from typing import Callable, Dict, Any
|
||||
|
||||
# from things import (
|
||||
# funny_trycatch_wrapper,
|
||||
# process_tuples,
|
||||
# funny_tuples_to_dicts_processor,
|
||||
# ) # no way its the funny trycatch wrapper
|
||||
|
||||
# dotenv_values1 = dotenv_values()
|
||||
# db_name = dotenv_values1["db_name"]
|
||||
|
||||
# he really did that
|
||||
# from mysql.connector import errorcode
|
||||
|
||||
# comectomKeys = ["user", "password", "host", "database"]
|
||||
# comectomtrk = {
|
||||
# "db_user": "user",
|
||||
# "db_password": "password",
|
||||
# "db_host": "host",
|
||||
# "db_name": "database",
|
||||
# }
|
||||
|
||||
# def getnewdict(d:dict, l:list) -> dict:
|
||||
# r = dict()
|
||||
# for k in d:
|
||||
# if k in l:
|
||||
# r[k] = d[k]
|
||||
# return r
|
||||
# getnewdict = lambda d, l: {k: d[k] for k in d if k in l}
|
||||
|
||||
# def getnewdicttranslate(d:dict, tltb:dict) -> dict:
|
||||
# r = dict()
|
||||
# for k in d:
|
||||
# if k in tltb:
|
||||
# r[tltb[k]] = d[k]
|
||||
# return r
|
||||
# getnewdicttranslate = lambda d, tltb: {tltb[k]: d[k] for k in d if k in tltb}
|
||||
|
||||
|
||||
# connectionSettings = {
|
||||
# **getnewdicttranslate(dotenv_values1, comectomtrk),
|
||||
# "raise_on_warnings": True,
|
||||
# }
|
||||
|
||||
|
||||
# quer = "insert into tbale (kewod, id) values (%s, %s);" # do not support custom key Only if
|
||||
# vals = (
|
||||
# r"faf",
|
||||
# r"24",
|
||||
# )
|
||||
# tablesql = sql.Table(name="tbale", database=db_name)
|
||||
|
||||
# tablesql.select()
|
||||
|
||||
|
||||
# def get_that_connection(
|
||||
# connectionSettings: dict,
|
||||
# ) -> tuple: # the giving up is real
|
||||
# try:
|
||||
# connectio = sqlcon.connect(**connectionSettings)
|
||||
# except sqlcon.Error as e:
|
||||
# return (None, e)
|
||||
# else:
|
||||
# return (connectio, None)
|
||||
+77
-45
@@ -5,59 +5,91 @@
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>lđa testing</title>
|
||||
<link type="text/css" rel="stylesheet" href="./style.css" />
|
||||
<!-- huh? what? -->
|
||||
<script type="module" src="./script.js" defer></script>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/katex.min.css">
|
||||
<!-- real -->
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<form action="/endp" method="post" id="only_form">
|
||||
<style>
|
||||
@scope {
|
||||
*:not(style, script) {
|
||||
display: block;
|
||||
}
|
||||
|
||||
p {
|
||||
font-size: larger;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<label for="oneid">url (anything after the first /):<input type="text" name="one" id="oneid"
|
||||
placeholder="url" /></label>
|
||||
<label for="twoid">content (as html cuz mime my ass):<textarea rows="7" cols="40" name="two" id="twoid"
|
||||
placeholder="content"></textarea>
|
||||
<header>
|
||||
<h1>front end design:</h1>
|
||||
</header>
|
||||
<nav>
|
||||
<ul>
|
||||
<li>
|
||||
<a>about</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="#oneid">view</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="">read</a>
|
||||
</li>
|
||||
<li>
|
||||
<a>write</a>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<main>
|
||||
<div class="box">
|
||||
<form action="./endp" method="post" id="only_form" enctype="text/plain">
|
||||
<label for="oneid">url (no space please thanks)
|
||||
<div style=>
|
||||
<a id="woah" style="text-align: right; min-width: 240px;
|
||||
"></a>
|
||||
<input style="display: inline;" required type="text" name="one" id="oneid" placeholder="url"
|
||||
maxlength="15" pattern="\S+" />
|
||||
</div>
|
||||
</label>
|
||||
<label for="threeid">response code if path visited. Default 200<input type="number" name="three" id="threeid"
|
||||
placeholder="http res code" min="0" /></label>
|
||||
<label for="the_Textarea">content (idk how it works anymore):
|
||||
<div class="setting-buttons">
|
||||
<!-- <input type="button" id="viewTextarea" value="show textarea" /> -->
|
||||
<input type="button" id="viewDiv" value="show rendered" />
|
||||
<input type="button" value="markdown to html" id="translateMD">
|
||||
<input type="checkbox" id="auto_translate">
|
||||
</div>
|
||||
</label>
|
||||
<div>
|
||||
<textarea class="why" name="two" id="the_Textarea" placeholder="what"></textarea>
|
||||
<!-- <div class="why" name="two" id="the_div" placeholder="type in here"></div> -->
|
||||
</div>
|
||||
<label for="threeid">response code if path visited. Default 200<input type="number" name="three"
|
||||
id="threeid" placeholder="http res code" min="0" pattern="\d*" /></label>
|
||||
<label for="fourid">expiration time for anything (todo idk how to do )<input type="number" name="four"
|
||||
id="fourid" placeholder="expiration in days" min="0" /></label>
|
||||
<p>if bugs tell me how to solve cuz im bad</p>
|
||||
id="fourid" placeholder="expiration in days" min="0" pattern="\d*" /></label>
|
||||
<p>leave empty for none / default</p>
|
||||
<input type="submit" value="Sumit rn" />
|
||||
<script>
|
||||
const form = document.getElementById("only_form");
|
||||
// const what = form.querySelector("input[type=submit]");
|
||||
console.log(form);
|
||||
form.addEventListener("submit", (e) => {
|
||||
// somewhere there has been code
|
||||
e.preventDefault();
|
||||
const data = new FormData(form);
|
||||
const jsData = Object.fromEntries(data);
|
||||
Object.entries(jsData).forEach(
|
||||
([k, v]) => (jsData[k] = v ? v : undefined)
|
||||
); // important here as we are dealing with Strings true/false kinda works how it is.
|
||||
const jsonified_data = JSON.stringify(jsData);
|
||||
const jsonified_custom_data = `{"from":"ldlda","data":${jsonified_data}}`; // haxxor
|
||||
const xhr = new XMLHttpRequest(); // this is going to be used. a lot.
|
||||
xhr.open("POST", form.getAttribute("action"));
|
||||
xhr.setRequestHeader("Content-type", "application/json");
|
||||
xhr.send(jsonified_custom_data);
|
||||
xhr.addEventListener(
|
||||
"load",
|
||||
(_) => (document.getElementById("what").innerText = xhr.response)
|
||||
);
|
||||
return false;
|
||||
});
|
||||
</script>
|
||||
</form>
|
||||
<div>
|
||||
<p>html from markdown:</p>
|
||||
<div class="why" name="two" id="the_div" placeholder="press the translate button"></div>
|
||||
<div id="errorfrommd"></div>
|
||||
</div>
|
||||
</div>
|
||||
<p>if bugs tell me how to solve cuz im bad</p>
|
||||
<div hidden>
|
||||
<p>what post got (sensitive):</p>
|
||||
<div id="what"></div>
|
||||
</div>
|
||||
<div hidden class="table">
|
||||
what is present:
|
||||
<table id="tbale">
|
||||
<thead>
|
||||
<th>no.</th>
|
||||
<th>url</th>
|
||||
<th>it is a</th>
|
||||
<th>exp time</th>
|
||||
</thead>
|
||||
<tbody id="updatedget"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</main>
|
||||
<footer>
|
||||
<h1>by <a href="//ldlda.com">lđa</a></h1>
|
||||
<p>very fragile</p>
|
||||
</footer>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -1,15 +1,84 @@
|
||||
# what by lda
|
||||
# stupid lil thhing
|
||||
|
||||
its bad
|
||||
## rn
|
||||
|
||||
## the most worstest server uve ever seen
|
||||
### server
|
||||
|
||||
i hate this more than you do
|
||||
get mechanism
|
||||
|
||||
## you dont read the code
|
||||
- close to close
|
||||
- get specific pages to get specific pages,
|
||||
- get the same page (endp) to view all,
|
||||
- get match name to get keyword in plain text => so no viewing html (NO XSS)
|
||||
- name is filtered from select all (select three columns)
|
||||
|
||||
definition of a black box. things go in things go out, and what is inside stays unknown
|
||||
post mech
|
||||
|
||||
## how do i run
|
||||
- post in either key: value or from: ldlda data: one two three four
|
||||
- post in json (stricter than your dict or obj)
|
||||
- funny insert query builder
|
||||
- at least automatically retrieve column names, not used much besides safety (cant trust myself type shi)
|
||||
|
||||
you dont
|
||||
common:
|
||||
|
||||
- process db info funnily (and badly): get all of them every time, still have to find right key (ineff)
|
||||
|
||||
### db
|
||||
|
||||
- just a lil table
|
||||
- server connects to the table, then NEVER disconnects.
|
||||
- autocommit
|
||||
|
||||
### client
|
||||
|
||||
- form with a lot of new tech used wrongly
|
||||
- four fields. url, textbox, two numbers
|
||||
- table that formats get endp
|
||||
- div beside form that displays rendered markdown (using micromark) automatically = spam them every 240ms
|
||||
- other stuctures outside main (FOR NOTHING)
|
||||
- most terrifying stylesheet and script file ever seen
|
||||
|
||||
issues:
|
||||
|
||||
- div has to limit size with px otherwise it grows and grows
|
||||
|
||||
markdown:
|
||||
|
||||
- import with import (esm)
|
||||
- lightweight(?) until i use it every 240ms
|
||||
- bad frontend, no styling
|
||||
|
||||
## desired outcome
|
||||
|
||||
### server
|
||||
|
||||
- handle requests better, with pictures and all
|
||||
- more modular, use more http methods
|
||||
- upload documents with stuff: trees
|
||||
- refactor into shorter code blocks
|
||||
- use more python technologies
|
||||
|
||||
### db
|
||||
|
||||
- use the linking tably to handle trees
|
||||
- do more processing here too
|
||||
|
||||
### client
|
||||
|
||||
- split into 4 pages:
|
||||
|
||||
- about where theres just info
|
||||
- write page where i write
|
||||
- application looks like stackedit
|
||||
- use contenteditable divs, probably with styling
|
||||
- use md engine skillfully
|
||||
- read page where i read
|
||||
- apply custom stylesheets
|
||||
- view page where i view
|
||||
- use custom queries
|
||||
- search
|
||||
|
||||
## what i can do rn
|
||||
|
||||
- refactor server handler, so it just do ifs then send code to other functions
|
||||
- fix layout
|
||||
@@ -0,0 +1,210 @@
|
||||
import { micromark } from "https://esm.sh/micromark@3?bundle";
|
||||
import {
|
||||
math,
|
||||
mathHtml,
|
||||
} from "https://esm.sh/micromark-extension-math@3?bundle";
|
||||
import { gfm, gfmHtml } from "https://esm.sh/micromark-extension-gfm@3?bundle";
|
||||
import {
|
||||
frontmatter,
|
||||
frontmatterHtml,
|
||||
} from "https://esm.sh/micromark-extension-frontmatter@2?bundle";
|
||||
// if this works yeag
|
||||
|
||||
const block = (evt) => {
|
||||
evt.preventDefault();
|
||||
evt.stopPropagation();
|
||||
evt.stopImmediatePropagation();
|
||||
};
|
||||
|
||||
const ainput = document.getElementById("woah");
|
||||
const baddress = window.location.pathname;
|
||||
//lmao
|
||||
const address =
|
||||
baddress.charAt(baddress.length - 1) === "/" ? baddress : baddress + "/";
|
||||
const hehe = [
|
||||
"somewhere idfk",
|
||||
"somewhere else ig",
|
||||
"around idk not here probably",
|
||||
"prob somwhere else",
|
||||
"right at this place, right here, where the link is at",
|
||||
];
|
||||
const updateurlhref = (e) => {
|
||||
if (e.target.value) {
|
||||
if (e.target.checkValidity()) {
|
||||
ainput.innerText = window.location.origin + address;
|
||||
ainput.setAttribute("href", "./" + e.target.value);
|
||||
} else {
|
||||
ainput.removeAttribute("href");
|
||||
ainput.innerHTML = `<span style="color:red">invalid: </span>`;
|
||||
}
|
||||
} else {
|
||||
ainput.removeAttribute("href");
|
||||
ainput.textContent = null;
|
||||
}
|
||||
};
|
||||
const urlfield = document.getElementById("oneid");
|
||||
urlfield.addEventListener("input", updateurlhref);
|
||||
|
||||
const divTextarea = document.getElementById("the_div");
|
||||
const realTextarea = document.getElementById("the_Textarea");
|
||||
|
||||
const placeholderDivText = "attr(placeholder)";
|
||||
divTextarea.style.setProperty(
|
||||
"--placeholder-content",
|
||||
divTextarea.textContent.trim() ? "" : placeholderDivText
|
||||
); // prolly init type shi
|
||||
|
||||
const translateMDButton = document.getElementById("translateMD");
|
||||
|
||||
const MDtoHTMLEngine = (v) =>
|
||||
micromark(v, {
|
||||
extensions: [frontmatter(), gfm(), math()],
|
||||
htmlExtensions: [frontmatterHtml(), gfmHtml(), mathHtml()],
|
||||
});
|
||||
const updateMD = (e) => {
|
||||
divTextarea.innerHTML = MDtoHTMLEngine(realTextarea.value);
|
||||
click_out_the_div();
|
||||
};
|
||||
translateMDButton.addEventListener("click", updateMD);
|
||||
//
|
||||
let updatingInterval = 240;
|
||||
let justUpdated = false;
|
||||
let updateTimeout;
|
||||
const typingHandler = (f) => (e) => {
|
||||
if (!justUpdated && !updateTimeout) {
|
||||
justUpdated = true;
|
||||
updateTimeout = setTimeout(() => {
|
||||
try {
|
||||
f();
|
||||
document.getElementById("errorfrommd").textContent = null;
|
||||
} catch (e) {
|
||||
document.getElementById("errorfrommd").textContent = e.message;
|
||||
}
|
||||
|
||||
justUpdated = false;
|
||||
updateTimeout = null;
|
||||
}, updatingInterval);
|
||||
}
|
||||
};
|
||||
const mdUpdatingHandler = typingHandler(updateMD); //why
|
||||
document.getElementById("auto_translate").addEventListener("change", (e) => {
|
||||
if (e.target.checked) {
|
||||
mdUpdatingHandler();
|
||||
realTextarea.addEventListener("input", mdUpdatingHandler);
|
||||
} else {
|
||||
realTextarea.removeEventListener("input", mdUpdatingHandler);
|
||||
}
|
||||
});
|
||||
|
||||
const click_in_the_div = (e) => {
|
||||
divTextarea.style.setProperty("--placeholder-content", "");
|
||||
};
|
||||
const click_out_the_div = (e) => {
|
||||
if (divTextarea.textContent.trim() || divTextarea.innerHTML) {
|
||||
divTextarea.style.setProperty("--placeholder-content", "");
|
||||
} else {
|
||||
divTextarea.style.setProperty("--placeholder-content", placeholderDivText);
|
||||
}
|
||||
};
|
||||
divTextarea.addEventListener("focus", click_in_the_div); // if function () {}
|
||||
divTextarea.addEventListener("blur", click_out_the_div); // i can use this
|
||||
|
||||
const resizeObserver = new ResizeObserver((mutation) => [
|
||||
mutation[0].contentRect.width,
|
||||
mutation[0].contentRect.height,
|
||||
]);
|
||||
|
||||
divTextarea.style.setProperty;
|
||||
const toggleDivTextarea = document.getElementById("viewDiv");
|
||||
|
||||
toggleDivTextarea.addEventListener("click", (e) => {
|
||||
divTextarea.toggleAttribute("hidden");
|
||||
});
|
||||
|
||||
document.querySelectorAll('input[type="number"]').forEach((e) => {
|
||||
e.addEventListener("keydown", (evt) => {
|
||||
if (["-", "+", ".", "e", "E"].includes(evt.key)) {
|
||||
// what if regex?
|
||||
block(evt);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const form = document.getElementById("only_form");
|
||||
form.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const data = new FormData(form);
|
||||
const jsData = Object.fromEntries(data);
|
||||
Object.entries(jsData).forEach(([k, v]) => (jsData[k] = v || undefined));
|
||||
// important here as we are dealing with Strings true/false kinda works how it is.
|
||||
const shippedData = { from: "ldlda", data: jsData };
|
||||
const jsonified_data = JSON.stringify(shippedData);
|
||||
|
||||
// const xhr = new XMLHttpRequest();
|
||||
// xhr.open(form.getAttribute("method"), form.getAttribute("action"));
|
||||
// xhr.setRequestHeader("Content-type", "application/json");
|
||||
// xhr.send(jsonified_custom_data);
|
||||
// xhr.addEventListener(
|
||||
// "load",
|
||||
// (_) => (document.getElementById("what").innerText = xhr.response)
|
||||
// );
|
||||
|
||||
const request = new Request(form.getAttribute("action"), {
|
||||
method: form.getAttribute("method"),
|
||||
headers: new Headers({ "Content-type": "application/json" }),
|
||||
body: jsonified_data,
|
||||
});
|
||||
|
||||
fetch(request)
|
||||
.then((response) => response.text())
|
||||
.then((t) => {
|
||||
const a = document.getElementById("what");
|
||||
a.parentElement.hidden = false;
|
||||
a.textContent = t;
|
||||
GETendp();
|
||||
})
|
||||
.catch((e) => console.error(e));
|
||||
return false;
|
||||
});
|
||||
|
||||
let htmlContent = "";
|
||||
const tableContent = document.getElementById("tbale");
|
||||
const actualTableContent = document.getElementById("updatedget");
|
||||
|
||||
const GETendp = (_) =>
|
||||
fetch(address + "endp")
|
||||
.then((response) => response.json())
|
||||
.then((json) => {
|
||||
console.log(json);
|
||||
// htmlContent = "<tbody>";
|
||||
|
||||
for (let key in json) {
|
||||
const url = json[key]["one"];
|
||||
const responsecode = json[key]["three"];
|
||||
let responsecontent = "something else";
|
||||
switch (responsecode) {
|
||||
case 200:
|
||||
responsecontent = "text";
|
||||
break;
|
||||
// damn
|
||||
case 301:
|
||||
case 302:
|
||||
responsecontent = "redirect";
|
||||
break;
|
||||
}
|
||||
htmlContent +=
|
||||
`<tr>
|
||||
<th>${key}</th>
|
||||
<td><a href="${"./" + url}">${url}</a></td>
|
||||
<td>${responsecontent}</td>
|
||||
<td>${json[key]["four"] || "Never"}</td>
|
||||
</tr>`;
|
||||
}
|
||||
|
||||
// htmlContent += "</tbody>";
|
||||
actualTableContent.innerHTML = htmlContent;
|
||||
})
|
||||
.catch((e) => console.error(e));
|
||||
|
||||
GETendp();
|
||||
tableContent.parentElement.hidden = false;
|
||||
@@ -0,0 +1,208 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
:root {
|
||||
--dark-enough: #303030;
|
||||
--color-1: #8bafed;
|
||||
--color-2: #faf3ed;
|
||||
--color-3: #feddcc;
|
||||
--color-4: #ff7100;
|
||||
--challenge: "use dem colors";
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: white;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='215' height='215' viewBox='0 0 200 200'%3E%3Cpolygon fill='%23FAF7F5' fill-opacity='0.58' points='100 0 0 100 100 100 100 200 200 100 200 0'/%3E%3C/svg%3E");
|
||||
|
||||
color: var(--dark-enough);
|
||||
background-attachment: fixed;
|
||||
display: grid;
|
||||
gap: 1em;
|
||||
grid-template-columns: fit-content(20%) auto;
|
||||
grid-template-rows: 100px 1fr 300px;
|
||||
grid-template-areas: "head head" "nav main" "nav foot";
|
||||
max-width: 100%;
|
||||
}
|
||||
body, html{
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
body > * {
|
||||
margin-inline: auto;
|
||||
border-radius: 15px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* why do i have to care about this */
|
||||
nav {
|
||||
grid-area: nav;
|
||||
background-color: azure;
|
||||
min-width: 120px;
|
||||
max-width: 280px;
|
||||
|
||||
ul {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
li {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 2em;
|
||||
transition: height 1s ease-in-out, background-color 1s ease-in-out;
|
||||
|
||||
&:hover,
|
||||
&:focus{
|
||||
height: 7em;
|
||||
background-color: paleturquoise;
|
||||
transition: height 1s ease-in-out, background-color 1s ease-in-out;
|
||||
}
|
||||
> a {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
align-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
header {
|
||||
background-color: azure;
|
||||
height: 100px;
|
||||
display: flex;
|
||||
justify-content: space-around;
|
||||
align-items: center;
|
||||
grid-area: head;
|
||||
}
|
||||
|
||||
header nav {
|
||||
font-size: xx-large;
|
||||
display: flex;
|
||||
gap: 1em;
|
||||
}
|
||||
/* previous design */
|
||||
|
||||
main {
|
||||
grid-area: main;
|
||||
min-height: 100vh;
|
||||
background-color: aliceblue;
|
||||
padding: 1em;
|
||||
display: flex;
|
||||
flex-flow: column nowrap;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
footer {
|
||||
grid-area: foot;
|
||||
background-color: aliceblue;
|
||||
display: flex;
|
||||
flex-flow: column nowrap;
|
||||
place-items: center;
|
||||
place-content: center;
|
||||
}
|
||||
|
||||
|
||||
.box {
|
||||
background-color: mistyrose;
|
||||
padding: 0.5em;
|
||||
border-radius: 6px;
|
||||
max-width: calc(100% - 1em);
|
||||
margin-inline: auto;
|
||||
|
||||
display: flex;
|
||||
flex-flow: row wrap;
|
||||
gap: 1em;
|
||||
}
|
||||
form label,
|
||||
input {
|
||||
display: block;
|
||||
}
|
||||
|
||||
label:has(input:valid)::before {
|
||||
content: "";
|
||||
}
|
||||
|
||||
label:has(input:invalid)::before {
|
||||
content: "invalid: ";
|
||||
color: red;
|
||||
}
|
||||
|
||||
label:has(input:required:invalid)::before {
|
||||
content: "required: ";
|
||||
color: red;
|
||||
}
|
||||
|
||||
.setting-buttons * {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
/* *[hidden] { display: none;} */
|
||||
/* why do i have to do that */
|
||||
#the_div::before {
|
||||
content: var(--placeholder-content);
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
#the_div::before,
|
||||
input::placeholder,
|
||||
textarea::placeholder {
|
||||
color: gray;
|
||||
}
|
||||
|
||||
#the_div {
|
||||
background-color: field;
|
||||
border: thin solid var(--dark-enough);
|
||||
border-radius: 6px;
|
||||
/* width: max-content; */
|
||||
max-height: 86vh;
|
||||
outline: none;
|
||||
overflow: auto;
|
||||
overflow-wrap: break-word;
|
||||
resize: none;
|
||||
min-height: 16rem;
|
||||
flex: 1 1 50%;
|
||||
}
|
||||
/* ????? */
|
||||
|
||||
img {
|
||||
object-fit: contain;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.why {
|
||||
min-width: 20rem;
|
||||
/* padding: 4px; */
|
||||
max-width: 960px;
|
||||
|
||||
min-height: 7rem;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
.table > table {
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
border-radius: 6px;
|
||||
}
|
||||
|
||||
thead {
|
||||
background-color: lavender;
|
||||
border-bottom: var(--dark-enough) 1px solid;
|
||||
}
|
||||
|
||||
tbody > tr:nth-of-type(even) {
|
||||
background-color: snow;
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
/* selecting all cells using NOT & > * > * > * */
|
||||
padding: 3px 6px;
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import http.server as serverhttp
|
||||
import mysql.connector as sqlcon
|
||||
from dotenv import dotenv_values
|
||||
import json
|
||||
# import urllib, sql
|
||||
|
||||
from things import (
|
||||
process_datetime_tuples,
|
||||
funny_tuples_to_dicts_processor,
|
||||
getnewdicttranslate,
|
||||
)
|
||||
|
||||
|
||||
from dotenv import dotenv_values
|
||||
|
||||
dotenv_values1 = dotenv_values() ## change so fast
|
||||
db_name = dotenv_values1["db_name"]
|
||||
|
||||
comectomKeys = ["user", "password", "host", "database"]
|
||||
comectomtrk = {
|
||||
"db_user": "user",
|
||||
"db_password": "password",
|
||||
"db_host": "host",
|
||||
"db_name": "database",
|
||||
}
|
||||
connectionSettings = {
|
||||
**getnewdicttranslate(dotenv_values1, comectomtrk),
|
||||
"raise_on_warnings": True,
|
||||
}
|
||||
|
||||
|
||||
def get_that_connection(
|
||||
connectionSettings: dict,
|
||||
) -> tuple: # the giving up is real
|
||||
try:
|
||||
connectio = sqlcon.connect(**connectionSettings)
|
||||
except sqlcon.Error as e:
|
||||
return (None, e)
|
||||
else:
|
||||
return (connectio, None)
|
||||
|
||||
|
||||
## USE THE @ if you know how
|
||||
|
||||
|
||||
class ServerLogic(serverhttp.BaseHTTPRequestHandler):
|
||||
|
||||
def youJustHaveToDoTheseStuff(self):
|
||||
# print("all headers:\n", self.headers)
|
||||
print("the path is : ", self.path)
|
||||
print(
|
||||
"connected at: ",
|
||||
self.headers.get("X-Forwarded-For", "directly").split(", ")[0],
|
||||
)
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.server.server_close()
|
||||
except BaseException as e:
|
||||
print(e)
|
||||
finally:
|
||||
print("gato")
|
||||
raise SystemExit("truly the /close")
|
||||
|
||||
def header_setup(
|
||||
self, code: int = 200, headers: dict = {"Content-type": "text/html"}
|
||||
):
|
||||
self.send_response(code)
|
||||
if headers is not None:
|
||||
for key in headers:
|
||||
self.send_header(key, headers[key]) # why!
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
self.youJustHaveToDoTheseStuff()
|
||||
|
||||
if self.path == "/close":
|
||||
return self.close()
|
||||
|
||||
if self.path == "/":
|
||||
self.header_setup()
|
||||
with open("index.html", "rb") as file:
|
||||
self.wfile.write(file.read())
|
||||
return
|
||||
if self.path == "/style.css": # allowed files is funny
|
||||
self.header_setup(headers={"Content-Type": "text/css"})
|
||||
with open("style.css", "rb") as file:
|
||||
self.wfile.write(file.read())
|
||||
return
|
||||
if self.path == "/script.js": #
|
||||
self.header_setup(
|
||||
headers={"Content-Type": "text/javascript"}
|
||||
) ## never knew!
|
||||
with open("script.js", "rb") as file:
|
||||
self.wfile.write(file.read())
|
||||
return
|
||||
|
||||
(connectio, eror) = get_that_connection(connectionSettings)
|
||||
if eror:
|
||||
print("coneti eror: ", eror)
|
||||
return
|
||||
# HE. MUST. AVOID. THE. TRYCATCH
|
||||
with connectio.cursor(buffered=True) as cur:
|
||||
try:
|
||||
res = cur.execute("select * from tbale")
|
||||
w = cur.fetchall()
|
||||
res = cur.execute(
|
||||
"select column_name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbale'"
|
||||
)
|
||||
anotherone2 = cur.fetchall()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return # return ealy no else
|
||||
c = process_datetime_tuples(w)
|
||||
ncnw = funny_tuples_to_dicts_processor(anotherone2, c)
|
||||
|
||||
if self.path == "/endp":
|
||||
efg = json.dumps(
|
||||
[ # haha yeah right why cant you do it client side
|
||||
## BIGGER QUESTION is that this is 2 of the same data
|
||||
getnewdicttranslate(
|
||||
i,
|
||||
{"neme": "one", "kewod": "two", "cod": "three", "expi": "four"},
|
||||
)
|
||||
for i in ncnw
|
||||
]
|
||||
)
|
||||
self.header_setup(headers={"Content-type": "application/json"})
|
||||
# self.wfile.write(str(c).encode())
|
||||
# self.wfile.write(str(anotherone2).encode())
|
||||
self.wfile.write(str(efg).encode())
|
||||
return
|
||||
else:
|
||||
wd = [(a["neme"], a["kewod"], a["cod"]) for a in ncnw]
|
||||
# print(wd)
|
||||
for a, v, c in wd:
|
||||
# print(a,v)
|
||||
# print(self.path, a)
|
||||
if self.path.lstrip("/") == a:
|
||||
if c == 200:
|
||||
self.header_setup(c, {"Content-type": "text/plain"})
|
||||
self.wfile.write(v.encode()) if v else None ## i mean crashes are handled anyway things keep running as is
|
||||
elif c in [301, 302]:
|
||||
self.header_setup(c, {"Location": v})
|
||||
return
|
||||
self.header_setup(404)
|
||||
self.wfile.write(
|
||||
b"""
|
||||
<h1>404</h1>
|
||||
<p>where u at</p>
|
||||
"""
|
||||
)
|
||||
return
|
||||
|
||||
def do_POST(self):
|
||||
self.youJustHaveToDoTheseStuff()
|
||||
|
||||
match self.path:
|
||||
case "/close":
|
||||
return self.close()
|
||||
|
||||
case "/endp":
|
||||
self.header_setup(headers={"Content-type": "text/plain"})
|
||||
content_type = self.headers.get("Content-Type")
|
||||
content_length = int(self.headers.get("Content-Length"))
|
||||
with self.rfile as r:
|
||||
post_data_bytes = r.read(content_length)
|
||||
## read how many bytes is the content length
|
||||
|
||||
self.wfile.write(
|
||||
b"Ive got a POST at "
|
||||
+ self.headers.get("Origin", "nowhere lmao").encode()
|
||||
+ b" from "
|
||||
+ self.headers.get("Referer", "who?").encode()
|
||||
+ b" with the following data:\n"
|
||||
+ post_data_bytes
|
||||
)
|
||||
|
||||
if content_type == "application/json":
|
||||
try:
|
||||
data_dict: dict = json.loads(post_data_bytes)
|
||||
##
|
||||
except Exception as e:
|
||||
print(e)
|
||||
self.wfile.write(
|
||||
b"\nhaha your data sucks (json.load is strict/bad): "
|
||||
+ str(e).encode()
|
||||
)
|
||||
return
|
||||
##
|
||||
(connectio, eror) = get_that_connection(connectionSettings)
|
||||
##
|
||||
if eror:
|
||||
print("coneti eror: ", eror)
|
||||
self.wfile.write(
|
||||
b"the thing cant even start like what f: "
|
||||
+ str(eror).encode()
|
||||
)
|
||||
return
|
||||
##
|
||||
# print((*data_dict.keys(), *data_dict.values()))
|
||||
|
||||
with connectio.cursor(buffered=True) as cur:
|
||||
try:
|
||||
anotherone = cur.execute(
|
||||
"select column_name from INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tbale'"
|
||||
)
|
||||
this_list_of_colnaes = cur.fetchall()
|
||||
except Exception as e:
|
||||
print("to day i cant get the damn colums: ", e)
|
||||
this_list_of_colnaes = [u[0] for u in this_list_of_colnaes] # weird
|
||||
##
|
||||
if data_dict.get("from") == "ldlda":
|
||||
ogdata_dict = data_dict.copy() ## as this isnt deep copy also because the thing is short lived i guess i dont ever need this for anything
|
||||
print("b4: ",data_dict, ogdata_dict) ## initial state for comp
|
||||
data_dict = getnewdicttranslate(
|
||||
ogdata_dict["data"], ## this would actually change ogdatadict.data
|
||||
{
|
||||
"one": "neme",
|
||||
"two": "kewod",
|
||||
"three": "cod",
|
||||
"four": "expi",
|
||||
},
|
||||
)
|
||||
print("aftr: ",data_dict, ogdata_dict) ## notice that the thing changed.
|
||||
##
|
||||
|
||||
wwwww = tuple(
|
||||
key for key in data_dict if key in this_list_of_colnaes
|
||||
)
|
||||
# hmmm
|
||||
# repated cod? huh?
|
||||
|
||||
updated_Verybreakablequery_insert_into = ( ## LEARN PYTHON SQL this is nasty
|
||||
"insert into tbale ({0}) values ({0})".format(
|
||||
",".join(["{}"] * len(wwwww))
|
||||
).format(*wwwww, *("?",) * len(wwwww))
|
||||
)
|
||||
print(
|
||||
wwwww,
|
||||
tuple(data_dict[w] for w in wwwww),
|
||||
updated_Verybreakablequery_insert_into,
|
||||
sep="\n",
|
||||
)
|
||||
|
||||
with connectio.cursor(prepared=True) as cur:
|
||||
connectio.autocommit = True
|
||||
try:
|
||||
res = cur.execute(
|
||||
updated_Verybreakablequery_insert_into,
|
||||
tuple(data_dict[w] for w in wwwww),
|
||||
# multi=True,
|
||||
)
|
||||
print("insert into qure: ", cur.fetchall())
|
||||
another = cur.execute("select * from tbale")
|
||||
w2f = cur.fetchall()
|
||||
##
|
||||
except Exception as e:
|
||||
print("execute err: ", e)
|
||||
self.wfile.write(
|
||||
b"\n is it very much Invalid: " + str(e).encode()
|
||||
)
|
||||
##
|
||||
else:
|
||||
# print(cur)
|
||||
# cur.execute("select * from tbale")
|
||||
# aq142 = cur.fetchall()
|
||||
# self.do_GET()
|
||||
pass
|
||||
##
|
||||
# self.wfile.write(b"\n We have this in the this: ")
|
||||
# self.wfile.write(str(process_datetime_tuples(w2f)).encode())
|
||||
|
||||
## what is a get to endp
|
||||
else: # elif content-type != json
|
||||
self.wfile.write(b"\nits of the type: ")
|
||||
self.wfile.write(content_type.encode())
|
||||
|
||||
case _: # self.path
|
||||
self.header_setup(403)
|
||||
self.wfile.write(
|
||||
b"""
|
||||
<h1>403</h1>
|
||||
<p>tf u doin</p>
|
||||
"""
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
# out
|
||||
|
||||
# def __do_POST2(self):
|
||||
# if self.path == "/close":
|
||||
# return self.close()
|
||||
# self.header_setup()
|
||||
# content_length = int(self.headers["Content-Length"])
|
||||
# with self.rfile as r:
|
||||
# post_data_bytes = self.rfile.read(content_length)
|
||||
# self.wfile.write(
|
||||
# b"MY SERVER: The post data I received from the request has following data:\n"
|
||||
# + post_data_bytes
|
||||
# )
|
||||
# try:
|
||||
# data_dict = json.loads(post_data_bytes.decode("utf-8"))
|
||||
# except Exception as e:
|
||||
# print(e)
|
||||
# try:
|
||||
# connectio = sqlcon.connect(**connectionSettings)
|
||||
# connectio.autocommit = True # EUYOEYOEYOEYOEYO
|
||||
# except sqlcon.Error as e:
|
||||
# print(e.errno, e.msg)
|
||||
# else:
|
||||
# with connectio.cursor(buffered=True) as cur:
|
||||
# try:
|
||||
# res = cur.execute(
|
||||
# "insert into tbale (kewod, id) values (%s, %s)",
|
||||
# (
|
||||
# data_dict["kewod"],
|
||||
# data_dict["id"],
|
||||
# ),
|
||||
# multi=True,
|
||||
# )
|
||||
|
||||
# print(res)
|
||||
# except Exception as e:
|
||||
# print("execute err: ", e)
|
||||
# self.wfile.write(b"\n is it very much Invalid." + str(e).encode())
|
||||
# else:
|
||||
# print(cur)
|
||||
# cur.execute("select * from tbale")
|
||||
# self.wfile.write(
|
||||
# b"\n We have this in the this: "
|
||||
# + str.encode(str(cur.fetchall()))
|
||||
# )
|
||||
# return
|
||||
|
||||
# def __do_GET2(self):
|
||||
# if self.path == "/close":
|
||||
# return self.close()
|
||||
|
||||
# self.header_setup()
|
||||
# try:
|
||||
# connectio = sqlcon.connect(**connectionSettings)
|
||||
# except sqlcon.Error as e:
|
||||
# print(e)
|
||||
# else:
|
||||
# with connectio.cursor(buffered=True, raw=True) as cur:
|
||||
# try:
|
||||
# res = cur.execute("select * from tbale")
|
||||
# w = cur.fetchall()
|
||||
# except Exception as e:
|
||||
# print(e)
|
||||
# else:
|
||||
# print(w)
|
||||
# self.wfile.write(bytes(w).decode())
|
||||
# return
|
||||
|
||||
# def __close2(self):
|
||||
# try:
|
||||
# self.server.server_close()
|
||||
# except BaseException as e:
|
||||
# print(e)
|
||||
# finally:
|
||||
# print("gato")
|
||||
# raise SystemExit("truly the /close")
|
||||
# do i need the funny trycatch ONCE
|
||||
# def close(self):
|
||||
# funny_trycatch_wrapper(
|
||||
# tries=[(self.server.server_close)],
|
||||
# finallies=[(print, ("gato")), ('raise SystemExit("truly the /close")')],
|
||||
# )
|
||||
@@ -1,31 +1,33 @@
|
||||
from typing import Callable, Dict, Any, List, Tuple, Union
|
||||
from itertools import zip_longest
|
||||
import datetime
|
||||
import copy
|
||||
|
||||
# import os, sys
|
||||
|
||||
class FunnyStuff:
|
||||
@staticmethod
|
||||
def funny(
|
||||
f: Callable,
|
||||
# m: Dict["args": list(), "kwargs": dict()]
|
||||
*a,
|
||||
**b,
|
||||
):
|
||||
# a = m.get("args", [])
|
||||
# b = m.get("kwargs", {})
|
||||
return f(*a, **b)
|
||||
# class FunnyStuff:
|
||||
# @staticmethod
|
||||
# def funny(
|
||||
# f: Callable,
|
||||
# # m: Dict["args": list(), "kwargs": dict()]
|
||||
# *a,
|
||||
# **b,
|
||||
# ):
|
||||
# # a = m.get("args", [])
|
||||
# # b = m.get("kwargs", {})
|
||||
# return f(*a, **b)
|
||||
|
||||
@staticmethod
|
||||
def funny2(t: tuple[Callable, tuple[Any, ...], Dict[str, Any]] = None):
|
||||
f, a, k = t
|
||||
# print(f, a, k)
|
||||
return FunnyStuff.funny(f, *a, **k)
|
||||
# @staticmethod
|
||||
# def funny2(t: tuple[Callable, tuple[Any, ...], Dict[str, Any]] = None):
|
||||
# f, a, k = t
|
||||
# # print(f, a, k)
|
||||
# return FunnyStuff.funny(f, *a, **k)
|
||||
|
||||
@staticmethod
|
||||
def funny3(t: tuple[Callable, tuple[Any, ...], Dict[str, Any]] = None):
|
||||
f, a, k = t
|
||||
# print(f, a, k)
|
||||
return f(*a, **k)
|
||||
# @staticmethod
|
||||
# def funny3(t: tuple[Callable, tuple[Any, ...], Dict[str, Any]] = None):
|
||||
# f, a, k = t
|
||||
# # print(f, a, k)
|
||||
# return f(*a, **k)
|
||||
|
||||
|
||||
# FunnyStuff.funny(print, 3, 4, 5, 6, 7, sep="")
|
||||
@@ -44,13 +46,69 @@ def unpack_with_defaults(t, defaults=(None, (), {})):
|
||||
)
|
||||
|
||||
|
||||
# def maybe_safer_unpack(t: tuple, defaults=(None, tuple(), dict())):
|
||||
# """
|
||||
# so uh
|
||||
# normally t[0] would be a function or a string
|
||||
# when t[0] is a function t[1] and t[2] might be, and when t[0] is a string
|
||||
# maybe just return t idfk
|
||||
|
||||
# """
|
||||
# # typeof = type(t)
|
||||
# # if typeof == str:
|
||||
# # return t
|
||||
# try:
|
||||
# new_tuple = list(copy.deepcopy(defaults))
|
||||
# except copy.Error as e:
|
||||
# print("this shouldnt happen?")
|
||||
# raise e
|
||||
# print(defaults, new_tuple)
|
||||
# if not isinstance(t, tuple):
|
||||
# new_tuple[0] = t
|
||||
# length = -1
|
||||
# t = (t,)
|
||||
# else:
|
||||
# new_tuple[0] = t[0]
|
||||
# length = len(t)
|
||||
# # length = len(t) if typeof == tuple else -1 # right
|
||||
# if length == 1:
|
||||
# return tuple(new_tuple)
|
||||
# for w in t[1:]:
|
||||
# print("w = ",w)
|
||||
# if isinstance(w, (tuple, list)):
|
||||
# new_tuple[1] += tuple(w)
|
||||
# elif isinstance(w, (dict)):
|
||||
# # what is set: set is basically dict key. they are unique.
|
||||
# # its the reference thing
|
||||
# new_tuple[2].update(w)
|
||||
# else:
|
||||
# new_tuple[1] += (w,)
|
||||
# # space saver
|
||||
# return tuple(new_tuple)
|
||||
|
||||
|
||||
# test_subject = [
|
||||
# ("print('exec, is string')"),
|
||||
# ("print('exec, is tuple')",),
|
||||
# (print,"thing", "things", {"sep":"\n"}),
|
||||
# (lambda _: print("lambda"),),
|
||||
# ("eval(3 + 5)",),
|
||||
|
||||
|
||||
# ]
|
||||
|
||||
# for i in test_subject:
|
||||
# print( f"{i = },\n{unpack_with_defaults(i) = },\n{maybe_safer_unpack(i) = }\n")
|
||||
|
||||
|
||||
def function_splitter(
|
||||
t: tuple[Union[Callable, str], tuple[Any, ...], Dict[str, Any]] = (
|
||||
None,
|
||||
(),
|
||||
{},
|
||||
tuple(),
|
||||
dict(),
|
||||
),
|
||||
*e,
|
||||
order: bool = False,
|
||||
**ae,
|
||||
):
|
||||
"""inp: (a, (b)?, {c}?), *oa?, **okwa?,
|
||||
@@ -58,7 +116,7 @@ def function_splitter(
|
||||
works like your function caller, (function, (args), {kwargs})
|
||||
function(*oa, **args, **okwa, **kwargs) # funny order huhg
|
||||
|
||||
Execute a function or a string using exec if it's the only argument.
|
||||
Execute a function or a string using eval if it's the only argument.
|
||||
|
||||
:param t: Tuple containing a function or string, args, and kwargs.
|
||||
:param e: Additional positional arguments.
|
||||
@@ -72,7 +130,11 @@ def function_splitter(
|
||||
f, a, k = unpack_with_defaults(t)
|
||||
if not isinstance(a, tuple):
|
||||
a = (a,) # i dont know why but this is wack as hell
|
||||
return f(*e, *a, **ae, **k)
|
||||
return f(*e, *a, **ae, **k) # funny ahh order
|
||||
|
||||
|
||||
# print(function_splitter((print, ["real af", len("")])))
|
||||
# function_splitter("raise SystemExit('wow')")
|
||||
|
||||
|
||||
def funny_trycatch_wrapper(
|
||||
@@ -114,7 +176,9 @@ def funny_trycatch_wrapper(
|
||||
for exception_type, handlers in excepts.items():
|
||||
if isinstance(e, exception_type):
|
||||
for handler in handlers:
|
||||
f = function_splitter(handler, e) # do i give the thing the thng or the thing
|
||||
f = function_splitter(
|
||||
handler, e
|
||||
) # do i give the thing the thng or the thing
|
||||
superreturn["rexcepts"][handler] = res
|
||||
break
|
||||
|
||||
@@ -129,26 +193,26 @@ def funny_trycatch_wrapper(
|
||||
return superreturn # lmao
|
||||
|
||||
|
||||
thisone = "this string"
|
||||
thatone = "that string"
|
||||
tries = [
|
||||
(
|
||||
print,
|
||||
("hello world"),
|
||||
),
|
||||
(print, (3 + 5, 9, 2 * 5, 33 / 3), {"sep": " "}),
|
||||
# ("1/0"),
|
||||
# ("raise Exception('real exeption')"),
|
||||
]
|
||||
excepts = {
|
||||
ZeroDivisionError: [(print, ("who divided by 0"))],
|
||||
Exception: [(lambda e: print(f"what tf is this error {e} like what"))],
|
||||
}
|
||||
finallies = [
|
||||
'print("finally")',
|
||||
]
|
||||
elses = [(print, "things gone well")]
|
||||
# funny_trycatch_wrapper(tries=tries, excepts=excepts, elses=elses, finallies=finallies)
|
||||
# thisone = "this string"
|
||||
# thatone = "that string"
|
||||
# tries = [
|
||||
# (
|
||||
# print,
|
||||
# ("hello world"),
|
||||
# ),
|
||||
# (print, (3 + 5, 9, 2 * 5, 33 / 3), {"sep": " "}),
|
||||
# # ("1/0"),
|
||||
# # ("raise Exception('real exeption')"),
|
||||
# ]
|
||||
# excepts = {
|
||||
# ZeroDivisionError: [(print, ("who divided by 0"))],
|
||||
# Exception: [(lambda e: print(f"what tf is this error {e} like what"))],
|
||||
# }
|
||||
# finallies = [
|
||||
# 'print("finally")',
|
||||
# ]
|
||||
# elses = [(print, "things gone well")]
|
||||
# # funny_trycatch_wrapper(tries=tries, excepts=excepts, elses=elses, finallies=finallies)
|
||||
|
||||
|
||||
def funny_singular_Simple_trycatch(Onetry: tuple):
|
||||
@@ -162,7 +226,7 @@ def funny_singular_Simple_trycatch(Onetry: tuple):
|
||||
return (this, er)
|
||||
|
||||
|
||||
def process_tuples(
|
||||
def process_datetime_tuples(
|
||||
tuples: List[Tuple[Any, ...]], action: str = "timestamp"
|
||||
) -> List[Tuple[Any, ...]]:
|
||||
"""
|
||||
@@ -183,7 +247,9 @@ def process_tuples(
|
||||
if action == "string":
|
||||
processed_tuple.append(item.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
elif action == "timestamp":
|
||||
processed_tuple.append(item.timestamp())
|
||||
processed_tuple.append(
|
||||
item.timestamp()
|
||||
) # why are you float why is it float does it need to be float
|
||||
else:
|
||||
raise ValueError("Unsupported action. Use 'string' or 'timestamp'.")
|
||||
else:
|
||||
@@ -203,3 +269,7 @@ def funny_tuples_to_dicts_processor(colname: list[tuple], coldata: list[tuple]):
|
||||
new_dict[colname[i][0]] = a
|
||||
new_dicts.append(new_dict)
|
||||
return new_dicts
|
||||
|
||||
|
||||
getnewdict = lambda d, l: {k: d[k] for k in d if k in l}
|
||||
getnewdicttranslate = lambda d, tltb: {tltb[k]: d[k] for k in d if k in tltb}
|
||||
Reference in new issue
Block a user