moonlette 0.0.1__py3-none-any.whl

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.

Potentially problematic release.


This version of moonlette might be problematic. Click here for more details.

moonlette/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
moonlette/server.py ADDED
@@ -0,0 +1,306 @@
1
+ # Moonlette - a simple web server
2
+ #
3
+ # MIT License - Copyright (C) 2026 Visual Topology Ltd
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy of this software
6
+ # and associated documentation files (the "Software"), to deal in the Software without
7
+ # restriction, including without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
9
+ # Software is furnished to do so, subject to the following conditions:
10
+ #
11
+ # The above copyright notice and this permission notice shall be included in all copies or
12
+ # substantial portions of the Software.
13
+ #
14
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
15
+ # BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17
+ # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+
20
+ import os
21
+ import asyncio
22
+ import uuid
23
+ import contextlib
24
+ import urllib.parse
25
+ import mimetypes
26
+ import signal
27
+ import threading
28
+ import requests
29
+ import time
30
+
31
+ from starlette.applications import Starlette
32
+ from starlette.requests import Request
33
+ from starlette.responses import Response, RedirectResponse, HTMLResponse
34
+ from starlette.websockets import WebSocket
35
+ from starlette.routing import Route, WebSocketRoute
36
+ from starlette.middleware.sessions import SessionMiddleware
37
+
38
+ import logging
39
+ import uvicorn
40
+
41
+ class Server:
42
+
43
+ def __init__(self, host="localhost", port=8889, startup_timeout_s=5, **kwargs):
44
+ self.host = host
45
+ self.port = port
46
+ self.startup_timeout_s = startup_timeout_s
47
+ self.configuration = kwargs
48
+ self.redirects = []
49
+ self.handlers = []
50
+ self.handler_registry = {}
51
+ self.ws_handlers = []
52
+ self.default_handlers = {}
53
+ self.app = None
54
+ self.loop = None
55
+ self.is_running = False
56
+ self.logger = logging.getLogger("moonlette.server")
57
+ self.attach_handler("GET", "/moonlette_status", lambda *args: (200, b"OK", "text/plain", {}))
58
+
59
+ def get_ws_handlers(self):
60
+ return self.ws_handlers
61
+
62
+ def get_http_handlers(self):
63
+ return self.handlers
64
+
65
+ def get_redirects(self):
66
+ return self.redirects
67
+
68
+ def get_default_handlers(self):
69
+ return self.default_handlers
70
+
71
+ def add_redirect(self, from_path, to_path):
72
+ self.redirects.append((from_path,to_path))
73
+
74
+ def attach_handler(self, method, path, handler):
75
+ handler_id = str(uuid.uuid4())
76
+ t = (method, path, handler)
77
+ self.handler_registry[handler_id] = t
78
+ self.handlers.append(t)
79
+ return handler_id
80
+
81
+ def detach_handler(self, handler_id):
82
+ t = self.handler_registry.get(handler_id, None)
83
+ if t is not None:
84
+ self.handlers.remove(t)
85
+
86
+ def attach_ws_handler(self, path, handler):
87
+ self.ws_handlers.append((path, handler))
88
+
89
+ def attach_webroot(self, path_prefix, static_folder):
90
+
91
+ def serve_static(path, headers, path_parameters, query_parameters, request_body):
92
+ filepath = os.path.join(static_folder,path_parameters["path"])
93
+ return self.serve_file(filepath)
94
+
95
+ self.attach_handler("GET", path_prefix + "/$$path", serve_static)
96
+
97
+ def serve_file(self, path):
98
+ if os.path.exists(path):
99
+ with open(path, "rb") as f:
100
+ (mimetype, encoding) = mimetypes.guess_type(path)
101
+ content = f.read()
102
+ return (200, content, mimetype, {})
103
+ else:
104
+ return (404, b"NOT FOUND", "text/plain", {})
105
+
106
+ async def http_endpoint(self, request:Request, user=None):
107
+
108
+ path = "/" + request.path_params["path"]
109
+
110
+ headers = {k: v for (k, v) in request.headers.items()}
111
+ if user is not None:
112
+ headers["X-User-ID"] = user
113
+ request_body = request.body
114
+ redirects = self.get_redirects()
115
+ for (from_path, to_path) in redirects:
116
+ if path == from_path:
117
+ return RedirectResponse(url=to_path)
118
+
119
+ for (handlermethod, handlerpath, handler) in self.get_http_handlers():
120
+ if handlermethod.lower() != request.method.lower():
121
+ continue
122
+ path_parameters = {}
123
+
124
+ if self.__match_path(handlerpath, path, path_parameters):
125
+
126
+ try:
127
+ handled = handler(path, headers, path_parameters, request.query_params, request_body)
128
+ if handled:
129
+ (code, content, mimetype, custom_headers) = handled
130
+ return Response(content=content, status_code=code, media_type=mimetype,
131
+ headers=custom_headers)
132
+
133
+ except Exception as ex:
134
+ logging.exception("Exception while handling request")
135
+ return Response(status_code=500, content=str(ex), media_type="text/plain", headers={})
136
+ break
137
+
138
+ return Response(status_code=404, content="NOT FOUND", media_type="text/plain", headers={})
139
+
140
+ async def websocket_endpoint(self, websocket: WebSocket, user=None):
141
+
142
+ await websocket.accept()
143
+ path = "/"+websocket.path_params["path"]
144
+
145
+ headers = {k: v for (k, v) in websocket.headers.items()}
146
+ if user is not None:
147
+ headers["X-User-ID"] = user
148
+ matched = False
149
+ for (handlerpath, handler) in self.get_ws_handlers():
150
+ path_parameters = {}
151
+ if self.__match_path(handlerpath, path, path_parameters):
152
+ matched = True
153
+ executing_tasks = set()
154
+ def sender(msg):
155
+ if msg is None:
156
+ async def close_ws():
157
+ await websocket.close()
158
+
159
+ task = self.loop.create_task(close_ws())
160
+ else:
161
+ async def send_ws():
162
+ if isinstance(msg, bytes):
163
+ await websocket.send_bytes(msg)
164
+ else:
165
+ await websocket.send_text(msg)
166
+
167
+ task = self.loop.create_task(send_ws())
168
+ task.add_done_callback(executing_tasks.discard)
169
+ executing_tasks.add(task)
170
+
171
+ session_id = str(uuid.uuid4())
172
+ session = handler(session_id, sender, path, path_parameters, websocket.query_params,
173
+ headers)
174
+ try:
175
+ async for message in websocket.iter_bytes():
176
+ if message != b"":
177
+ session.recv(message)
178
+ else:
179
+ pass # heartbeat?
180
+ except Exception as ex:
181
+ self.logger.exception("Exception while handling request")
182
+ break
183
+ if not matched:
184
+ await websocket.close()
185
+
186
+ def register_middleware(self, app):
187
+ pass
188
+
189
+ def run(self, callback):
190
+
191
+
192
+
193
+ self.is_running = True
194
+
195
+ @contextlib.asynccontextmanager
196
+ async def lifespan(app):
197
+
198
+ def check_running():
199
+ url = f"http://{self.host}:{self.port}/moonlette_status"
200
+
201
+ max_retries = 5
202
+ retry_interval = self.startup_timeout_s
203
+ for r in range(max_retries):
204
+ retry_interval /= 2
205
+
206
+ retry = 0
207
+ while retry < max_retries:
208
+ try:
209
+ time.sleep(retry_interval)
210
+ response = requests.get(url)
211
+ if response.status_code == 200:
212
+ self.is_running = True
213
+ if callback:
214
+ callback(True)
215
+ return
216
+ except:
217
+ pass
218
+ retry += 1
219
+ retry_interval *= 2
220
+ if callback:
221
+ callback(False)
222
+
223
+ t = threading.Thread(target=check_running)
224
+ t.start()
225
+ yield
226
+
227
+ async def websocket_endpoint(ws:WebSocket):
228
+ return await self.websocket_endpoint(ws)
229
+
230
+ async def http_endpoint(request:Request):
231
+ return await self.http_endpoint(request)
232
+
233
+ self.app = Starlette(debug=True, routes=[
234
+ WebSocketRoute("/{path:path}", websocket_endpoint),
235
+ Route("/{path:path}", http_endpoint),
236
+ ], lifespan=lifespan)
237
+
238
+ self.loop = asyncio.new_event_loop()
239
+
240
+ self.register_middleware(self.app)
241
+
242
+ config = uvicorn.Config(self.app,port=self.port, log_level="info", loop=lambda : self.loop)
243
+ self.server = uvicorn.Server(config)
244
+ self.server.run()
245
+
246
+ def close(self):
247
+ self.server.handle_exit(signal.SIGINT,None)
248
+ self.is_running = False
249
+ self.logger.info('Closing ...')
250
+
251
+ def check_running(self):
252
+ return self.is_running
253
+
254
+ def __match_path(self, handlerpath, path, parameters):
255
+ handlerpathlist = handlerpath.split("/")
256
+ pathlist = path.split("/")
257
+ matched = self.__match(handlerpathlist,pathlist, parameters, True)
258
+ if not matched:
259
+ # if the match fails, clear away any data collected on a partial match
260
+ parameters.clear()
261
+ return matched
262
+
263
+ def __match(self, handlerpathlist, pathlist, parameters,required):
264
+ if handlerpathlist == [] and pathlist == []:
265
+ return True
266
+ if len(handlerpathlist) > 0 and not required:
267
+ # allow empty match
268
+ parameters1 = {}
269
+ if self.__match(handlerpathlist[1:], pathlist, parameters1, True):
270
+ parameters.update(parameters1)
271
+ return True
272
+ if handlerpathlist == [] or pathlist == []:
273
+ return False
274
+
275
+ matchexp = handlerpathlist[0]
276
+ if matchexp.startswith("$$"):
277
+ key = matchexp[2:]
278
+ parameters[key] = pathlist[0]
279
+ parameters1 = {}
280
+ if self.__match(handlerpathlist, pathlist[1:], parameters1, False):
281
+ parameters.update(parameters1)
282
+ if key in parameters1:
283
+ parameters[key] = pathlist[0]+ "/" + parameters1[key]
284
+ return True
285
+ else:
286
+ return False
287
+ elif matchexp.startswith("$"):
288
+ key = matchexp[1:]
289
+ parameters[key] = pathlist[0]
290
+ else:
291
+ if matchexp != pathlist[0]:
292
+ return False
293
+
294
+ return self.__match(handlerpathlist[1:], pathlist[1:], parameters, True)
295
+
296
+ def __collect_parameters(self, query, parameters):
297
+ if query != "":
298
+ qargs = query.split("&")
299
+ for qarg in qargs:
300
+ argsplit = qarg.split("=")
301
+ if len(argsplit) == 2:
302
+ key = urllib.parse.unquote(argsplit[0])
303
+ value = urllib.parse.unquote(argsplit[1])
304
+ parameters[key] = value
305
+
306
+
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.4
2
+ Name: moonlette
3
+ Version: 0.0.1
4
+ Summary: A simple web server with websocket support based on starlette and uvicorn
5
+ Author-email: Visual Topology <dev@visualtopology.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://codeberg.org/visual-topology/moonlette
8
+ Project-URL: Documentation, https://codeberg.org/visual-topology/moonlette
9
+ Project-URL: Repository, https://codeberg.org/visual-topology/moonlette
10
+ Project-URL: Issues, https://codeberg.org/visual-topology/moonlette/issues
11
+ Project-URL: Changelog, https://codeberg.org/visual-topology/moonlette/src/branch/main/CHANGELOG.md
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: JavaScript
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
16
+ Classifier: Development Status :: 3 - Alpha
17
+ Requires-Python: >=3.11
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: starlette[full]
21
+ Requires-Dist: uvicorn[standard]
22
+ Requires-Dist: requests
23
+ Dynamic: license-file
24
+
25
+ # moonlette
26
+
27
+ A simple web server with websockets support based on starlette, uvicorn and authlib.
28
+
29
+ ## Installation
30
+
31
+ ```
32
+ pip install moonlette
33
+ ```
34
+
35
+ ## Example usage (http)
36
+
37
+ ```
38
+ from mooonlette.server import Server
39
+ server = Server(port=8081, host="localhost")
40
+
41
+ def handler(path, headers, path_parameters, query_parameters, request_body):
42
+ return (200, b"It Worked!", "text/plain", {})
43
+
44
+ server.attach_handler("GET", "/test", handler)
45
+ server.run()
46
+ ```
47
+
48
+ ## Example usage (websocckets)
49
+
50
+ Coming soon
51
+
52
+ ## Documentation
53
+
54
+ Coming Soon
@@ -0,0 +1,7 @@
1
+ moonlette/__init__.py,sha256=ugyuFliEqtAwQmH4sTlc16YXKYbFWDmfyk87fErB8-8,21
2
+ moonlette/server.py,sha256=fr3USmlApYVqFvCQQk4rcQRftQmSEwK5BOcjT4NXppg,11309
3
+ moonlette-0.0.1.dist-info/licenses/LICENSE,sha256=hEKBsH4KN-i4e0Q3HskgVsaZ1xqaqIBNypJqsz5zD-U,1072
4
+ moonlette-0.0.1.dist-info/METADATA,sha256=_W0VObCBaq7arkuU0Zb_soCSjr21On434rhsZySUOyE,1604
5
+ moonlette-0.0.1.dist-info/WHEEL,sha256=qELbo2s1Yzl39ZmrAibXA2jjPLUYfnVhUNTlyF1rq0Y,92
6
+ moonlette-0.0.1.dist-info/top_level.txt,sha256=EEuXG3KNz9eYkixhVgNgfAY88SMANhClXyBOEoaow8c,10
7
+ moonlette-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 visual-topology
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ moonlette