smdb-web-server 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 NightKey
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.1
2
+ Name: smdb_web_server
3
+ Version: 0.1.0
4
+ Summary: A really basic, not so safe web server.
5
+ Home-page: https://github.com/NightKey/smdb-server
6
+ Author: Janthó Dávid
7
+ Author-email: davidjantho@gmail.com
8
+ Project-URL: Bug Tracker, https://github.com/NightKey/smdb-server/issues
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: Freeware
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.7
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+
17
+ # SMDB Web Server
18
+ An easy to use, not secured web server, because I don't like the other options, and I like to create my own solutions most of the time.
@@ -0,0 +1,2 @@
1
+ # SMDB Web Server
2
+ An easy to use, not secured web server, because I don't like the other options, and I like to create my own solutions most of the time.
@@ -0,0 +1,7 @@
1
+ [build-system]
2
+ requires = [
3
+ "setuptools>=42",
4
+ "wheel",
5
+ "smdb_logger"
6
+ ]
7
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,25 @@
1
+ [metadata]
2
+ name = smdb_web_server
3
+ version = 0.1.0
4
+ author = Janthó Dávid
5
+ author_email = davidjantho@gmail.com
6
+ description = A really basic, not so safe web server.
7
+ long_description = file: README.md
8
+ long_description_content_type = text/markdown
9
+ url = https://github.com/NightKey/smdb-server
10
+ project_urls =
11
+ Bug Tracker = https://github.com/NightKey/smdb-server/issues
12
+ classifiers =
13
+ Development Status :: 4 - Beta
14
+ Programming Language :: Python :: 3
15
+ License :: Freeware
16
+ Operating System :: OS Independent
17
+
18
+ [options]
19
+ packages = find:
20
+ python_requires = >=3.7
21
+
22
+ [egg_info]
23
+ tag_build =
24
+ tag_date = 0
25
+
@@ -0,0 +1,260 @@
1
+ import asyncio
2
+ from typing import Callable, Dict, Optional, Union, Any, List
3
+ from os import path
4
+ from smdb_logger import Logger, LEVEL
5
+ from json import dumps
6
+ from threading import Thread
7
+ from time import perf_counter_ns
8
+
9
+ class KnownError(Exception):
10
+ def __init__(self, reason: str, response_code: int) -> None:
11
+ self.response = ResponseCode(response_code, reason)
12
+
13
+ def __str__(self) -> str:
14
+ return f"Reason: {self.response.name}, Code: {self.response.value}"
15
+
16
+ class ResponseCode():
17
+ def __init__(self, value: int, name: str):
18
+ self.value = value
19
+ self.name = name
20
+
21
+ def __str__(self) -> str:
22
+ return f"{self.value} {self.name}"
23
+
24
+ class Timer():
25
+ def __init__(self):
26
+ self.start = perf_counter_ns()
27
+ self.end = 0
28
+
29
+ def stop(self):
30
+ self.end = perf_counter_ns()
31
+
32
+ def __str__(self) -> str:
33
+ return f"{(self.end - self.start)/1000000}"
34
+
35
+ NotFound = ResponseCode(404, "Not Found")
36
+ Ok = ResponseCode(200, "Ok")
37
+ InternalServerError = ResponseCode(500, "Internal Server Error")
38
+ TPot = ResponseCode(418, "I'm a teapot")
39
+
40
+ get_rules: Dict[str, Callable[[Dict[str, str]], None]] = {}
41
+ put_rules: Dict[str, Callable[[bytes], None]] = {}
42
+ title: str = None
43
+ html_template: str = "<html><header><link rel='stylesheet' href='/static/style.css' /><title>{title}</title></header><body>{content}</body></html>"
44
+ http_header: str = "{version_info} {response_code}\r\nContent-Length: {length}\r\nContent-Type: {content_type};\r\nServer-Timing: {timing}\r\n\r\n"
45
+ cwd: str = "."
46
+
47
+ TEMPLATES: Dict[str, str] = {}
48
+ STATIC: Dict[str, str] = {}
49
+
50
+ class HTTPRequestHandler():
51
+ def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter, logger: Logger = None) -> None:
52
+ self.reader = reader
53
+ self.writer = writer
54
+ self.headers: Dict[str, str] = None
55
+ self.path: str = ""
56
+ self.path_params: str = ""
57
+ self.data: str = ""
58
+ self.version: str = "HTTP/1.0"
59
+ self.logger = logger
60
+
61
+ async def handle_request(self):
62
+ try:
63
+ tmp = await self.reader.readuntil("\r\n\r\n".encode())
64
+ tmp = tmp.decode().split("\r\n")
65
+ method, tmp_path, _ = tmp[0].split(" ")
66
+ tmp_path = tmp_path.split("?")
67
+ self.path_params = {item.split("=")[0]: item.split("=")[1] for item in tmp_path[-1].split("&") if len(item.split("=")) == 2}
68
+ self.path = tmp_path[0]
69
+ self.headers = {head.split(": ")[0]: head.split(": ")[1] for head in tmp[1:] if head != ''}
70
+ if (self.logger):
71
+ self.logger.debug(f"Headers retrived: {self.headers}")
72
+ if ("Content-Length" in self.headers):
73
+ self.data = await self.reader.read(int(self.headers["Content-Length"]))
74
+ if (self.logger):
75
+ self.logger.debug(f"Data retrived: {self.data}")
76
+ if (method == "GET"):
77
+ self.do_GET()
78
+ elif (method == "PUT"):
79
+ put_th = Thread(target=self.do_PUT)
80
+ put_th.start()
81
+ except Exception as ex :
82
+ self.logger.debug(f"Exception: {ex}")
83
+ html_file = html_template.format(title=title, content=ex)
84
+ response_code = InternalServerError
85
+ self.send_message(response_code, html_file)
86
+
87
+ def __404__(self, do_get: Timer) -> None:
88
+ if (self.logger):
89
+ self.logger.debug("Sending 404 page.")
90
+ _404_time = Timer()
91
+ _404_file = ""
92
+ if ("404" in TEMPLATES):
93
+ _404_file = TEMPLATES["404"].format(title=title)
94
+ else:
95
+ _404_file = html_template.format(title=title, content="404 NOT FOUND")
96
+ _404_time.stop()
97
+ do_get.stop()
98
+ self.send_message(NotFound, _404_file, f"full;dur={do_get}, process;dur={_404_time}")
99
+
100
+ @staticmethod
101
+ def render_static_file(name: str) -> bytes:
102
+ data: Union[str, bytes] = STATIC[".".join(name.split(".")[:-1])]
103
+ if (isinstance(data, str) and data.startswith("PATH")):
104
+ _path = data.split("|")[-1]
105
+ with open(path.join(cwd, _path), "r") as fp:
106
+ data = fp.read()
107
+ return data
108
+
109
+ def send_message(self, response_code: ResponseCode, payload: Union[str, Dict[Any, Any], bytes], timing: str = "") -> None:
110
+ content_type = "text/html"
111
+ if isinstance(payload, (dict)):
112
+ content_type = "application/json"
113
+ payload = dumps(payload)
114
+ if isinstance(payload, bytes):
115
+ content_type = "image/ico"
116
+ data = http_header.format(version_info=self.version, response_code=str(response_code), content_type=content_type, length=len(payload), timing=timing).encode()
117
+ if (self.logger):
118
+ self.logger.debug(f"Sending data: {data.decode()} with payload: {payload}")
119
+ self.writer.write(data)
120
+ self.writer.write(payload.encode() if not isinstance(payload, bytes) else payload)
121
+
122
+ def do_GET(self) -> None:
123
+ do_get = Timer()
124
+ if (self.path in get_rules.keys()):
125
+ get_rules_time = Timer()
126
+ html_file = ""
127
+ response_code: ResponseCode = None
128
+ if (self.logger):
129
+ self.logger.debug(f"Calling GET {self.path} with params: {self.path_params}")
130
+ try:
131
+ html_file = get_rules[self.path](self.path_params)
132
+ response_code = Ok
133
+ except KnownError as ke:
134
+ html_file = html_template.format(title=title, content=ke.response.name)
135
+ response_code = ke.response
136
+ if (self.logger):
137
+ self.logger.warning(f"Known Exception: {ke}")
138
+ except Exception as ex:
139
+ html_file = html_template.format(title=title, content=ex)
140
+ response_code = InternalServerError
141
+ if (self.logger):
142
+ self.logger.error(f"Exception: {ex}")
143
+ finally:
144
+ do_get.stop()
145
+ get_rules_time.stop()
146
+ self.send_message(response_code, html_file, f"full;dur={do_get}, process;dur={get_rules_time}")
147
+ return
148
+ if self.path.startswith("/static") or self.path == "/favicon.ico":
149
+ if (self.logger):
150
+ self.logger.debug(f"Serving static file from path: {self.path}")
151
+ static = Timer()
152
+ html_file = HTTPRequestHandler.render_static_file(self.path.split("/")[-1])
153
+ if html_file is None:
154
+ self.__404__(do_get)
155
+ return
156
+ static.stop()
157
+ do_get.stop()
158
+ self.send_message(Ok, html_file, f"full;dur={do_get}, process;dur={static}")
159
+ return
160
+ self.__404__(do_get)
161
+
162
+ def do_PUT(self) -> None:
163
+ do_put = Timer()
164
+ if (self.path not in put_rules.keys()):
165
+ self.__404__(do_put)
166
+ return
167
+ if (self.logger):
168
+ self.logger.debug(f"Calling PUT {self.path}")
169
+ message_return: ResponseCode = None
170
+ try:
171
+ put_rules[self.path](self.data)
172
+ message_return = Ok
173
+ except KnownError as ke:
174
+ message_return = ke.response
175
+ if (self.logger):
176
+ self.logger.warning(f"Known Exception: {ke}")
177
+ except Exception as ex:
178
+ message_return = InternalServerError
179
+ if (self.logger):
180
+ self.logger.error(f"Exception: {ex}")
181
+ do_put.stop()
182
+ self.send_message(message_return, "", f"full={do_put}")
183
+
184
+ class HTMLServer:
185
+ def __init__(self, host: str, port: int, root_path: str = ".", logger: Optional[Logger] = None, _title: str = "HTML Server"):
186
+ global title
187
+ global cwd
188
+ self.host = host
189
+ self.port = port
190
+ self.logger = logger
191
+ self.handler: HTTPRequestHandler = HTTPRequestHandler
192
+ self.server = None
193
+ title = _title
194
+ cwd = root_path
195
+
196
+ def try_log(self, data: str, log_level: LEVEL = LEVEL.INFO) -> None:
197
+ if self.logger == None:
198
+ return
199
+ self.logger.log(log_level, data)
200
+
201
+ def render_template_file(self, name: str, **kwargs) -> str:
202
+ data: str = TEMPLATES[name.replace(".html", "")]
203
+ if (data.startswith("PATH")):
204
+ _path = data.split("|")[-1]
205
+ with open(path.join(cwd, _path), "r") as fp:
206
+ data = fp.read()
207
+ for template, value in kwargs.items():
208
+ if isinstance(value, str):
209
+ data = data.replace("{{ " + template + " }}", value)
210
+ elif isinstance(value, list):
211
+ items = self.render_template_list(template, value)
212
+ data = data.replace("{{[ " + template + " ]}}", items)
213
+ return data
214
+
215
+ def render_template_list(self, name: str, values: List[str]) -> str:
216
+ original = TEMPLATES[name]
217
+ ret = ["<option disabled selected value></option>"]
218
+ for val in values:
219
+ tmp = original.replace("{{VALUE}}", val.split('|')[0])
220
+ tmp = tmp.replace("{{SELECTED}}", "selected" if len(val.split('|')) > 1 else "")
221
+ ret.append(tmp)
222
+ return "\n".join(ret)
223
+
224
+ def add_url_rule(self, rule: str, callback: Union[Callable[[Dict[str, str]], None], Callable[[bytes], None]], protocol: str = "GET") -> None:
225
+ if (protocol == "GET"):
226
+ get_rules[rule] = callback
227
+ if (protocol == "PUT"):
228
+ put_rules[rule] = callback
229
+
230
+ async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
231
+ addr = writer.get_extra_info('peername')
232
+ self.try_log(f'Accepted connection from {addr[0]}:{addr[1]}')
233
+ handler = self.handler(reader, writer, self.logger)
234
+ await handler.handle_request()
235
+
236
+ async def start(self):
237
+ try:
238
+ self.server = await asyncio.start_server(
239
+ self.handle_client,
240
+ self.host,
241
+ self.port
242
+ )
243
+ self.try_log(f'Serving on {self.host}:{self.port}')
244
+ async with self.server:
245
+ await self.server.serve_forever()
246
+ except asyncio.CancelledError:
247
+ pass
248
+ finally:
249
+ self.server = None
250
+
251
+ def stop(self):
252
+ try:
253
+ self.try_log("Stopping server")
254
+ if self.server:
255
+ self.server.close()
256
+ except:
257
+ pass
258
+
259
+ def serve_forever(self):
260
+ asyncio.run(self.start())
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.1
2
+ Name: smdb_web_server
3
+ Version: 0.1.0
4
+ Summary: A really basic, not so safe web server.
5
+ Home-page: https://github.com/NightKey/smdb-server
6
+ Author: Janthó Dávid
7
+ Author-email: davidjantho@gmail.com
8
+ Project-URL: Bug Tracker, https://github.com/NightKey/smdb-server/issues
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: Freeware
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.7
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+
17
+ # SMDB Web Server
18
+ An easy to use, not secured web server, because I don't like the other options, and I like to create my own solutions most of the time.
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.cfg
5
+ smdb_web_server/__init__.py
6
+ smdb_web_server.egg-info/PKG-INFO
7
+ smdb_web_server.egg-info/SOURCES.txt
8
+ smdb_web_server.egg-info/dependency_links.txt
9
+ smdb_web_server.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ smdb_web_server