semi broken. some changes to the conn thing

This commit is contained in:
lda committed 2025-05-01 19:16:36 +07:00
1 parent dbebf03250
commit 517707b79c
3 files changed
+120 -97

No files matched your search

+7 -6
View File
@@ -4,14 +4,15 @@ go dam
"""
import http.server as serverhttp
import sys
from the_server_handler import ServerLogic, connectionSettings, get_that_connection
from the_server_handler import \
ServerLogic # , connectionSettings, get_that_connection
# import mysql.connector as sqlcon
import sys
if not (sys.version_info >= (3, 11)):
if not sys.version_info >= (3, 11):
raise Exception(f"python 3.11 up, u running {sys.version}")
PORT = 8088
@@ -25,11 +26,11 @@ def runServer():
server = serverhttp.HTTPServer(("", PORT), ServerLogic)
try:
server.serve_forever()
except KeyboardInterrupt:
except KeyboardInterrupt as c:
server.server_close()
# connectio.close()
raise SystemExit("\nctrl c")
except BaseException as e:
raise SystemExit("\nctrl c") from c
except Exception as e:
print(e)
# finally:
# print("why am i printing")
+87 -79
View File
@@ -1,27 +1,29 @@
import http.server as serverhttp
# import urllib.parse
import warnings
# import chardet
from http import HTTPStatus as rescode
# import urllib
import json
import mimetypes
# import traceback
import os
from typing import Literal
import mysql.connector as sqlcon
# import urllib.parse
import warnings
from functools import wraps
# import chardet
from http import HTTPStatus as rescode
from pathlib import Path
from typing import Literal, Optional
# from mysql.connector import errorcode
from dotenv import dotenv_values
from urllib import parse as urlparse # lmao the normal person
# import urllib
import json
from functools import wraps
from pathlib import Path
import mysql.connector as sqlcon
from dotenv import dotenv_values
# from dotenv import dotenv_values
# import urllib, sql
class ServerLogic(serverhttp.BaseHTTPRequestHandler): ...
@@ -42,11 +44,9 @@ if os.path.isdir(webrootdir): # unfuckable
os.chdir(webrootdir) # move to safe part of world
curdir = os.path.curdir or os.getcwd()
print(os.path.curdir, os.getcwd())
from things import (
process_datetime_DICTS,
# process_datetime_tuples,
# funny_tuples_to_dicts_processor,
from things import ( # process_datetime_tuples,; funny_tuples_to_dicts_processor,
getnewdicttranslate,
process_datetime_DICTS,
)
dotenv_values1 = dotenv_values() ## change so fast
@@ -78,39 +78,37 @@ def get_that_connection(
return (connectio, None)
def better_connection_actuallyworking(connectionSettings: dict):
def better_connection_actuallyworking(connectionSettings: dict, conn_name="conn"):
"""
arg for func:
1. conn (do you hate life)
2. thingElse
Wraps a function and injects a SQL connection as a kwarg.
The kwarg is named via conn_name, default is 'conn'.
"""
def ONETHING(func):
def decorator(func):
@wraps(func)
def huh(*a, **kw):
# conn = sqlcon.connect(**connectionSettings)
def wrapper(*args, **kwargs):
try:
with sqlcon.connect(
**connectionSettings
) as conn: # HOLY SHIT THANK YOU CHAT GPT
return func(conn, *a, **kw)
with sqlcon.connect(**connectionSettings) as conn:
kwargs[conn_name] = conn
return func(*args, **kwargs)
except sqlcon.Error as e:
print("oh hey errorSql FromtheWrapper", e)
raise e
print("SQL error from wrapper:", e)
raise
except Exception as e:
print("betterConnection NoWorked", e)
raise e
# finally: # they run even after return! try finally gon go crazy
# conn.close()
print("Connection wrapper failed:", e)
raise
return huh
return wrapper
return ONETHING
return decorator
@better_connection_actuallyworking(connectionSettings)
def funnying_funnytheFunnier(
conn: sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection,
*,
conn: Optional[
sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection
] = None,
):
return conn # WHAT NOT TO DO
@@ -135,19 +133,22 @@ def funnying_funnytheFunnier(
# print(cur.fetchall())
@better_connection_actuallyworking(connectionSettings)
@better_connection_actuallyworking(connectionSettings, conn_name="_conn")
def fulltable(
conn: sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection,
tbaleName: str,
returnType: Literal["zip", "dict"] = "dict",
*,
_conn: Optional[
sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection
] = None,
) -> dict | tuple[list[tuple], list[str]]: # connection is inserted in by the thing
print(tbaleName)
if not (tableName := ifTableInDB(db_name, tbaleName)):
raise sqlcon.DatabaseError(f"{tbaleName} where tELL ME")
ifdict = returnType == "dict"
try:
with conn.cursor(dictionary=ifdict, prepared=True) as cur:
res = cur.execute(f"select * from {tableName}")
with _conn.cursor(dictionary=ifdict, prepared=True) as cur:
_res = cur.execute(f"select * from {tableName}")
r = cur.fetchall()
if ifdict:
return r
@@ -161,14 +162,18 @@ def fulltable(
raise e
@better_connection_actuallyworking(connectionSettings)
@better_connection_actuallyworking(connectionSettings, conn_name="_conn")
def getColumename(
conn: sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection, tbaleName: str
tbaleName: str,
*,
_conn: Optional[
sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection
] = None,
) -> list[str]:
print(tbaleName)
try:
with conn.cursor(prepared=True) as cur:
res = cur.execute(
with _conn.cursor(prepared=True) as cur:
_res = cur.execute(
"select column_name from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = ?",
(tbaleName,),
)
@@ -184,13 +189,17 @@ def getColumename(
raise e
@better_connection_actuallyworking(connectionSettings)
@better_connection_actuallyworking(connectionSettings, conn_name="_conn")
def getTableNmaes(
conn: sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection, db_name: str
db_name: str,
*,
_conn: Optional[
sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection
] = None,
) -> list[str]:
try:
with conn.cursor(prepared=True) as cur:
res = cur.execute(
with _conn.cursor(prepared=True) as cur:
_res = cur.execute(
"select table_name from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA = ?",
(db_name,),
)
@@ -217,19 +226,22 @@ csTrtb = dict(zip(clietColum, severColum))
print(scTrtb, csTrtb)
@better_connection_actuallyworking(connectionSettings)
@better_connection_actuallyworking(connectionSettings, "_conn")
def ifTableInDB(
conn: sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection,
db_name: str,
tabN: str,
*,
_conn: Optional[
sqlcon.MySQLConnection | sqlcon.pooling.PooledMySQLConnection
] = None,
) -> str | None:
"""you dont believe it but it works like a true false, as python is good enough
if (vari := ifTableInDB(dbname, tablename)):"""
try:
with conn.cursor(prepared=True) as cur:
with _conn.cursor(prepared=True) as cur:
res = cur.execute(
_res = cur.execute(
"select table_name from information_schema.tables where table_schema = ? and table_name = ? Limit 1;",
(db_name, tabN),
)
@@ -253,13 +265,13 @@ def openFileManually(
theGuy: ServerLogic,
webDir: str,
defaultFile: str | None = "index.html",
dir: str | None = None,
dir_: str | None = None,
headers: dict | None = None,
rootDir: str | None = curdir,
) -> None:
print(webDir, dir, headers)
if dir:
filename = dir
print(webDir, dir_, headers)
if dir_:
filename = dir_
else:
filename = webDir.lstrip("/")
path = Path(rootDir, filename)
@@ -295,28 +307,26 @@ def openFileManually(
with open(path, "rb") as file:
asfd = file.read()
headers |= {(gay or "content-type"): finalMime,
"content-length": str(len(asfd))
}
headers |= {(gay or "content-type"): finalMime, "content-length": str(len(asfd))}
theGuy.header_setup(headers=headers)
return
theGuy.wfile.write(asfd)
def openFileSemiAutomatically(
theGuy: ServerLogic,
webDir: str,
defaultFile: str | list[str] | tuple[str] | None = "index.html",
dir: str | None = None,
dir_: str | None = None,
headers: dict | None = None,
rootDir: str | None = curdir,
):
c = bytes()
pf = Path()
a = Path(dir) if dir else Path(webDir.lstrip("/"))
a = Path(dir_) if dir_ else Path(webDir.lstrip("/"))
if not a.exists():
c = notfound404
elif a.is_dir():
if type(defaultFile) == str:
if isinstance(defaultFile, str):
p = a / defaultFile
if p.is_file():
with open(p, "rb") as f:
@@ -338,19 +348,17 @@ def openFileSemiAutomatically(
else:
c = notfound404
mt, enct = mimetypes.guess_type(pf)
mt, _enct = mimetypes.guess_type(pf)
if not headers:
headers = {}
if mt.split("/")[0] == "text":
fg = mt + "; charset=utf-8"
theGuy.header_setup(
200,
headers
| {
"content-type": fg or mt,
mt = mt + "; charset=utf-8"
if mt:
headers |= {
"content-type": mt,
# "content-length": str(len(c))
},
)
}
theGuy.header_setup(200, headers)
theGuy.wfile.write(c)
@@ -360,8 +368,8 @@ def openFileSemiAutomatically(
class ServerLogic(serverhttp.BaseHTTPRequestHandler):
def __init__(self, *a, **kw): # AHAHHAHAHAHAHAHAHA
super().__init__(*a, **kw)
# def __init__(self, *a, **kw): # AHAHHAHAHAHAHAHAHA
# super().__init__(*a, **kw)
def reallyEveryTime(self) -> tuple:
print("all headers:\n", self.headers)
@@ -401,8 +409,8 @@ class ServerLogic(serverhttp.BaseHTTPRequestHandler):
self.send_response(code)
for key, value in headers.items():
self.send_header(key, value) # why!
else:
pass
# else:
# pass
self.end_headers()
def do_GET(self):
@@ -519,11 +527,11 @@ class ServerLogic(serverhttp.BaseHTTPRequestHandler):
"""
super().__init__(rc, case, *a, **kw)
self.stupid = case
if type(rc) == int:
if isinstance(rc, int):
print("what")
self.ldarescode = rescode(rc) # why do i have to do this
print(self.ldarescode)
elif type(rc) == rescode:
elif isinstance(rc, rescode):
print("good")
self.ldarescode = rc
print(self.ldarescode)
@@ -620,7 +628,7 @@ class ServerLogic(serverhttp.BaseHTTPRequestHandler):
)
conn.commit() # WHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWHYWH
cur.execute(
f"select * from tbale where neme = ?",
"select * from tbale where neme = ?",
(data_dict["neme"],),
)
print("res of:", cur.fetchone())
+26 -12
View File
@@ -1,10 +1,11 @@
from collections import defaultdict
import datetime
import random
import string
from typing import Callable, Dict, Any, List, Literal, Tuple, Union
from collections import defaultdict
from itertools import zip_longest
import datetime
import copy
from typing import Any, Callable, Dict, List, Literal, Tuple, Union
# import copy
# import os, sys
@@ -142,12 +143,19 @@ def function_splitter(
def funny_trycatch_wrapper(
tries: list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]],
excepts: dict[
BaseException,
list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]],
] = {BaseException: [(lambda x: print(f"Error: {x}"))]},
elses: list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]] = [],
finallies: list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]] = [],
excepts: (
dict[
BaseException,
list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]],
]
| None
) = None,
elses: (
list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]] | None
) = None,
finallies: (
list[tuple[Callable | str, tuple[Any, ...] | Any, Dict[str, Any]]] | None
) = None,
):
"""
Try, except, else, and finally wrapper for multiple functions or exec strings.
@@ -165,6 +173,11 @@ def funny_trycatch_wrapper(
"rfinallies": [],
}
"""
# tries = tries or []
excepts = excepts or {BaseException: [lambda x: print(f"Error: {x}")]}
elses = elses or []
finallies = finallies or []
superreturn = {
"rtries": [],
"rexcepts": {},
@@ -273,9 +286,10 @@ def process_datetime_DICTS(
dict[k] = v.strftime("%Y-%m-%d %H:%M:%S")
elif action == "timestamp":
dict[k] = v.timestamp()
else:
raise ValueError(f"Unsupported action {action}. Use 'string' or 'timestamp'.") # bet this will run
raise ValueError(
f"Unsupported action {action}. Use 'string' or 'timestamp'."
) # bet this will run
return dicts # in place processing