moonlette 0.2.0__tar.gz → 0.2.1__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.
Files changed (28) hide show
  1. moonlette-0.2.1/PKG-INFO +177 -0
  2. moonlette-0.2.1/README.md +151 -0
  3. moonlette-0.2.1/src/moonlette/__init__.py +1 -0
  4. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/auth_server.py +7 -11
  5. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/server.py +69 -27
  6. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/user_db.py +11 -6
  7. moonlette-0.2.1/src/moonlette.egg-info/PKG-INFO +177 -0
  8. moonlette-0.2.0/PKG-INFO +0 -83
  9. moonlette-0.2.0/README.md +0 -57
  10. moonlette-0.2.0/src/moonlette/__init__.py +0 -1
  11. moonlette-0.2.0/src/moonlette.egg-info/PKG-INFO +0 -83
  12. {moonlette-0.2.0 → moonlette-0.2.1}/LICENSE +0 -0
  13. {moonlette-0.2.0 → moonlette-0.2.1}/pyproject.toml +0 -0
  14. {moonlette-0.2.0 → moonlette-0.2.1}/setup.cfg +0 -0
  15. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/http_request_context.py +0 -0
  16. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/interfaces/__init__.py +0 -0
  17. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/interfaces/ws_session.py +0 -0
  18. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/static/auth_status.js +0 -0
  19. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/static/forbidden.html +0 -0
  20. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/static/login.html +0 -0
  21. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/static/profile.html +0 -0
  22. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/static/style.css +0 -0
  23. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/user.py +0 -0
  24. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette/ws_request_context.py +0 -0
  25. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette.egg-info/SOURCES.txt +0 -0
  26. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette.egg-info/dependency_links.txt +0 -0
  27. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette.egg-info/requires.txt +0 -0
  28. {moonlette-0.2.0 → moonlette-0.2.1}/src/moonlette.egg-info/top_level.txt +0 -0
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.4
2
+ Name: moonlette
3
+ Version: 0.2.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
+ Provides-Extra: auth
24
+ Requires-Dist: authlib; extra == "auth"
25
+ Dynamic: license-file
26
+
27
+ # moonlette
28
+
29
+ A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
30
+
31
+ HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
32
+
33
+ ## Installation
34
+
35
+ ```
36
+ pip install moonlette
37
+ ```
38
+
39
+ To use `AuthServer` (login via OpenID Connect providers), install the optional `AUTH` dependencies:
40
+
41
+ ```
42
+ pip install "moonlette[AUTH]"
43
+ ```
44
+
45
+ ## Example usage (http)
46
+
47
+ An HTTP handler receives an `HTTPRequestContext` and returns a tuple of
48
+ `(status-code, response-bytes, mime-type, custom-headers)`.
49
+
50
+ ```python
51
+ from moonlette.http_request_context import HTTPRequestContext
52
+ from moonlette.server import Server
53
+
54
+ server = Server(port=8081, host="localhost")
55
+
56
+
57
+ def hello(ctx: HTTPRequestContext):
58
+ return (200, b"It Worked!", "text/plain", {})
59
+
60
+
61
+ def echo(ctx: HTTPRequestContext):
62
+ # ctx.request_body holds the request body as bytes
63
+ return (200, ctx.request_body, "application/octet-stream", {})
64
+
65
+
66
+ server.attach_http_handler("GET", "/test", hello)
67
+ server.attach_http_handler("POST", "/echo", echo)
68
+
69
+ # serve files from a local folder, for example /static/index.html
70
+ server.attach_webroot("/static", "/path/to/static/files")
71
+
72
+ # run() blocks until the server is closed. The callback is called with True
73
+ # once the server is accepting requests, or False if it failed to start
74
+ server.run(lambda started: print("server started" if started else "server failed to start"))
75
+ ```
76
+
77
+ Call `server.close()` from another thread (or from a handler) to stop the server.
78
+
79
+ ### Path patterns
80
+
81
+ Handler paths can capture parts of the request path, which are passed to the handler in `ctx.path_parameters`:
82
+
83
+ | Pattern | Matches | Example |
84
+ |-------------|-------------------------------|-----------------------------------------------|
85
+ | `$name` | exactly one path segment | `/users/$id` matches `/users/42` |
86
+ | `$$name` | one or more path segments | `/files/$$path` matches `/files/a/b.txt` |
87
+ | `$$$name` | zero or more path segments | `/app/$$$rest` matches `/app` and `/app/x/y` |
88
+
89
+ Query parameters are available in `ctx.query_parameters` and request headers in `ctx.headers`.
90
+
91
+ ## Example usage (websockets)
92
+
93
+ A websocket handler receives a `WSRequestContext` and returns an object implementing `WSSession`.
94
+ Send messages back by awaiting `ctx.sender(msg)` with `bytes` or `str`; `await ctx.sender(None)` closes the websocket.
95
+
96
+ ```python
97
+ from moonlette.server import Server
98
+ from moonlette.ws_request_context import WSRequestContext
99
+ from moonlette.interfaces.ws_session import WSSession
100
+
101
+ server = Server(port=8081, host="localhost")
102
+
103
+
104
+ class EchoSession(WSSession):
105
+
106
+ def __init__(self, ctx: WSRequestContext):
107
+ self.ctx = ctx
108
+
109
+ async def recv(self, msg: bytes):
110
+ # echo the message back
111
+ await self.ctx.sender(msg)
112
+
113
+ async def close(self):
114
+ # called when the websocket is closed
115
+ pass
116
+
117
+
118
+ server.attach_ws_handler("/echo", EchoSession)
119
+ server.run(None)
120
+ ```
121
+
122
+ ## Authentication
123
+
124
+ `AuthServer` is a drop-in replacement for `Server` that requires users to log in before accessing handlers,
125
+ web roots and websockets. Login providers are defined in a TOML file, where `${NAME}` is replaced by the value
126
+ of the environment variable `NAME`:
127
+
128
+ ```toml
129
+ [google]
130
+ provider_type = "oidc"
131
+ label = "Login with Google"
132
+ client_id = "${GOOGLE_CLIENT_ID}"
133
+ client_secret = "${GOOGLE_CLIENT_SECRET}"
134
+ redirect_url = "http://localhost:8080/moonlette_auth/authorised"
135
+ server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration"
136
+ client_kwargs = { scope = "openid email profile" }
137
+ token_settings = { user_id = "email", user_email = "email", user_name = ["given_name", "family_name"] }
138
+ ```
139
+
140
+ Roles are assigned to users in a `UserDB`, and each role is granted within a group:
141
+
142
+ ```python
143
+ from moonlette.auth_server import AuthServer
144
+ from moonlette.user_db import UserDB
145
+
146
+ user_db = UserDB("users.db")
147
+ user_db.assign_role("someone@example.com", "EDITOR", "GROUP1")
148
+
149
+ server = AuthServer(port=8080, secret_key="<a long random secret>", user_db=user_db,
150
+ auth_provider_config_path="auth_providers.toml")
151
+
152
+ # pages anyone can see, without logging in
153
+ server.attach_unauthorised_webroot("/public", "/path/to/public/files")
154
+
155
+ # pages that need a logged-in user with the EDITOR role in GROUP1
156
+ server.attach_webroot("/restricted", "/path/to/restricted/files", required_roles=[("EDITOR", "GROUP1")])
157
+
158
+ server.run(None)
159
+ ```
160
+
161
+ Users who are not logged in are redirected to `/moonlette_auth/login.html`. Handlers attached to an `AuthServer`
162
+ can read the logged-in user from `ctx.user`.
163
+
164
+ The roles database can also be managed from the command line:
165
+
166
+ ```
167
+ python -m moonlette.user_db users.db --add someone@example.com EDITOR GROUP1
168
+ python -m moonlette.user_db users.db --list-for-user someone@example.com
169
+ python -m moonlette.user_db users.db --load-from-csv roles.csv
170
+ python -m moonlette.user_db users.db --save-to-csv roles.csv
171
+ ```
172
+
173
+ CSV files have the columns `user_id,role_name,group_name` and a header row.
174
+
175
+ ## Documentation
176
+
177
+ Coming Soon
@@ -0,0 +1,151 @@
1
+ # moonlette
2
+
3
+ A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
4
+
5
+ HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
6
+
7
+ ## Installation
8
+
9
+ ```
10
+ pip install moonlette
11
+ ```
12
+
13
+ To use `AuthServer` (login via OpenID Connect providers), install the optional `AUTH` dependencies:
14
+
15
+ ```
16
+ pip install "moonlette[AUTH]"
17
+ ```
18
+
19
+ ## Example usage (http)
20
+
21
+ An HTTP handler receives an `HTTPRequestContext` and returns a tuple of
22
+ `(status-code, response-bytes, mime-type, custom-headers)`.
23
+
24
+ ```python
25
+ from moonlette.http_request_context import HTTPRequestContext
26
+ from moonlette.server import Server
27
+
28
+ server = Server(port=8081, host="localhost")
29
+
30
+
31
+ def hello(ctx: HTTPRequestContext):
32
+ return (200, b"It Worked!", "text/plain", {})
33
+
34
+
35
+ def echo(ctx: HTTPRequestContext):
36
+ # ctx.request_body holds the request body as bytes
37
+ return (200, ctx.request_body, "application/octet-stream", {})
38
+
39
+
40
+ server.attach_http_handler("GET", "/test", hello)
41
+ server.attach_http_handler("POST", "/echo", echo)
42
+
43
+ # serve files from a local folder, for example /static/index.html
44
+ server.attach_webroot("/static", "/path/to/static/files")
45
+
46
+ # run() blocks until the server is closed. The callback is called with True
47
+ # once the server is accepting requests, or False if it failed to start
48
+ server.run(lambda started: print("server started" if started else "server failed to start"))
49
+ ```
50
+
51
+ Call `server.close()` from another thread (or from a handler) to stop the server.
52
+
53
+ ### Path patterns
54
+
55
+ Handler paths can capture parts of the request path, which are passed to the handler in `ctx.path_parameters`:
56
+
57
+ | Pattern | Matches | Example |
58
+ |-------------|-------------------------------|-----------------------------------------------|
59
+ | `$name` | exactly one path segment | `/users/$id` matches `/users/42` |
60
+ | `$$name` | one or more path segments | `/files/$$path` matches `/files/a/b.txt` |
61
+ | `$$$name` | zero or more path segments | `/app/$$$rest` matches `/app` and `/app/x/y` |
62
+
63
+ Query parameters are available in `ctx.query_parameters` and request headers in `ctx.headers`.
64
+
65
+ ## Example usage (websockets)
66
+
67
+ A websocket handler receives a `WSRequestContext` and returns an object implementing `WSSession`.
68
+ Send messages back by awaiting `ctx.sender(msg)` with `bytes` or `str`; `await ctx.sender(None)` closes the websocket.
69
+
70
+ ```python
71
+ from moonlette.server import Server
72
+ from moonlette.ws_request_context import WSRequestContext
73
+ from moonlette.interfaces.ws_session import WSSession
74
+
75
+ server = Server(port=8081, host="localhost")
76
+
77
+
78
+ class EchoSession(WSSession):
79
+
80
+ def __init__(self, ctx: WSRequestContext):
81
+ self.ctx = ctx
82
+
83
+ async def recv(self, msg: bytes):
84
+ # echo the message back
85
+ await self.ctx.sender(msg)
86
+
87
+ async def close(self):
88
+ # called when the websocket is closed
89
+ pass
90
+
91
+
92
+ server.attach_ws_handler("/echo", EchoSession)
93
+ server.run(None)
94
+ ```
95
+
96
+ ## Authentication
97
+
98
+ `AuthServer` is a drop-in replacement for `Server` that requires users to log in before accessing handlers,
99
+ web roots and websockets. Login providers are defined in a TOML file, where `${NAME}` is replaced by the value
100
+ of the environment variable `NAME`:
101
+
102
+ ```toml
103
+ [google]
104
+ provider_type = "oidc"
105
+ label = "Login with Google"
106
+ client_id = "${GOOGLE_CLIENT_ID}"
107
+ client_secret = "${GOOGLE_CLIENT_SECRET}"
108
+ redirect_url = "http://localhost:8080/moonlette_auth/authorised"
109
+ server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration"
110
+ client_kwargs = { scope = "openid email profile" }
111
+ token_settings = { user_id = "email", user_email = "email", user_name = ["given_name", "family_name"] }
112
+ ```
113
+
114
+ Roles are assigned to users in a `UserDB`, and each role is granted within a group:
115
+
116
+ ```python
117
+ from moonlette.auth_server import AuthServer
118
+ from moonlette.user_db import UserDB
119
+
120
+ user_db = UserDB("users.db")
121
+ user_db.assign_role("someone@example.com", "EDITOR", "GROUP1")
122
+
123
+ server = AuthServer(port=8080, secret_key="<a long random secret>", user_db=user_db,
124
+ auth_provider_config_path="auth_providers.toml")
125
+
126
+ # pages anyone can see, without logging in
127
+ server.attach_unauthorised_webroot("/public", "/path/to/public/files")
128
+
129
+ # pages that need a logged-in user with the EDITOR role in GROUP1
130
+ server.attach_webroot("/restricted", "/path/to/restricted/files", required_roles=[("EDITOR", "GROUP1")])
131
+
132
+ server.run(None)
133
+ ```
134
+
135
+ Users who are not logged in are redirected to `/moonlette_auth/login.html`. Handlers attached to an `AuthServer`
136
+ can read the logged-in user from `ctx.user`.
137
+
138
+ The roles database can also be managed from the command line:
139
+
140
+ ```
141
+ python -m moonlette.user_db users.db --add someone@example.com EDITOR GROUP1
142
+ python -m moonlette.user_db users.db --list-for-user someone@example.com
143
+ python -m moonlette.user_db users.db --load-from-csv roles.csv
144
+ python -m moonlette.user_db users.db --save-to-csv roles.csv
145
+ ```
146
+
147
+ CSV files have the columns `user_id,role_name,group_name` and a header row.
148
+
149
+ ## Documentation
150
+
151
+ Coming Soon
@@ -0,0 +1 @@
1
+ __version__ = ("0.2.1")
@@ -49,7 +49,7 @@ class AuthServer(Server):
49
49
  host: str = "localhost",
50
50
  port: int = 8889,
51
51
  startup_timeout_s: int = 5,
52
- log_level: str = "info",
52
+ log_level: str = "warning",
53
53
  secret_key:str = None,
54
54
  user_db:UserDB = None,
55
55
  auth_provider_config_path: str = None,
@@ -180,8 +180,7 @@ class AuthServer(Server):
180
180
  required_roles: optional list of roles to which the authenticated user should belong
181
181
  """
182
182
  def serve_static(request_context):
183
- filepath = os.path.join(static_folder,request_context.path_parameters["path"])
184
- return self.serve_file(filepath)
183
+ return self.serve_static_file(static_folder, request_context.path_parameters["path"])
185
184
  self.attach_http_handler("GET", path_prefix + "/$$path", serve_static, required_roles=required_roles)
186
185
 
187
186
 
@@ -198,8 +197,8 @@ class AuthServer(Server):
198
197
  user_roles = request_context.user.get_roles()
199
198
  if required_roles:
200
199
  for (role,group) in required_roles:
201
- if role not in user_roles:
202
- return (403, b"FORBIDDEN", "text/plain", {})
200
+ if (role,group) not in user_roles:
201
+ return None # the server closes the websocket when no session is returned
203
202
  return handler(request_context)
204
203
  super().attach_ws_handler(path, checked_handler)
205
204
 
@@ -224,8 +223,7 @@ class AuthServer(Server):
224
223
  static_folder: the directory to serve matching sub-paths from
225
224
  """
226
225
  def serve_static(request_context):
227
- filepath = os.path.join(static_folder,request_context.path_parameters["path"])
228
- return self.serve_file(filepath)
226
+ return self.serve_static_file(static_folder, request_context.path_parameters["path"])
229
227
  self.attach_unauthorised_http_handler("GET", path_prefix + "/$$path", serve_static)
230
228
 
231
229
  async def _http_endpoint(self, request:Request, user:User|None=None):
@@ -238,8 +236,6 @@ class AuthServer(Server):
238
236
  if path == "/.well-known/appspecific/com.chrome.devtools.json":
239
237
  return HTMLResponse(b"Not Found", 404)
240
238
 
241
- print("***:"+path)
242
-
243
239
  if path == self.login_urls[0]:
244
240
  (status, content, mimetype, headers) = self.serve_file(os.path.join(self.auth_folder,"login.html"))
245
241
  return HTMLResponse(content, status_code=status, headers=headers, media_type=mimetype)
@@ -327,13 +323,13 @@ class AuthServer(Server):
327
323
 
328
324
  user_id = websocket.session.get('user_id')
329
325
  if not user_id:
330
- await websocket.send_denial_response(Response(401, b"UNAUTHORIZED", "text/plain", {}))
326
+ await websocket.send_denial_response(Response(b"UNAUTHORIZED", status_code=401, media_type="text/plain"))
331
327
  return
332
328
 
333
329
  user_name = websocket.session.get('user_name', "")
334
330
  user_email = websocket.session.get('user_email', "")
335
331
  roles = self.user_db.get_roles_for_user(user_id)
336
- user = User(user_id, user_name, user_email, roles, {})
332
+ user = User(user_id, user_name, user_email, [(role,group) for (user_id, role, group) in roles], {})
337
333
 
338
334
  return await super()._websocket_endpoint(websocket, user)
339
335
 
@@ -34,9 +34,8 @@ from typing import Callable
34
34
  from starlette.applications import Starlette
35
35
  from starlette.requests import Request
36
36
  from starlette.responses import Response, RedirectResponse, HTMLResponse
37
- from starlette.websockets import WebSocket
37
+ from starlette.websockets import WebSocket, WebSocketDisconnected
38
38
  from starlette.routing import Route, WebSocketRoute
39
- from starlette.websockets import WebSocketDisconnect
40
39
 
41
40
  import logging
42
41
  import uvicorn
@@ -55,7 +54,7 @@ WSHandler:TypeAlias = Callable[[WSRequestContext],WSSession]
55
54
 
56
55
  class Server:
57
56
 
58
- def __init__(self, host:str="localhost", port:int=8889, startup_timeout_s:int=5, log_level:str="info"):
57
+ def __init__(self, host:str="localhost", port:int=8889, startup_timeout_s:int=5, log_level:str="warning"):
59
58
  """
60
59
 
61
60
  Args:
@@ -108,7 +107,8 @@ class Server:
108
107
 
109
108
  Args:
110
109
  path: the path to connect a websocket
111
- handler: a function which receives a WSRequestContext and returns an object sub-classing WSSession to handle websocket messages
110
+ handler: a function which receives a WSRequestContext and returns an object sub-classing WSSession to handle websocket messages,
111
+ or None to reject the connection (the websocket is closed with code 1008)
112
112
  """
113
113
  self.ws_handlers.append((path, handler))
114
114
 
@@ -121,10 +121,28 @@ class Server:
121
121
  static_folder: the directory to serve matching sub-paths from
122
122
  """
123
123
  def serve_static(request_context):
124
- filepath = os.path.join(static_folder,request_context.path_parameters["path"])
125
- return self.serve_file(filepath)
124
+ return self.serve_static_file(static_folder, request_context.path_parameters["path"])
126
125
  self.attach_http_handler("GET", path_prefix + "/$$path", serve_static)
127
126
 
127
+ def serve_static_file(self, static_folder:str, sub_path:str) -> tuple[int,bytes,str,dict[str,str]]:
128
+ """
129
+ Utility function to serve a file from within a static folder
130
+
131
+ Args:
132
+ static_folder: the directory to serve files from
133
+ sub_path: the path of the file, relative to static_folder
134
+
135
+ Returns:
136
+ tuple containing (response-code,response-bytes,mime-type,custom-response-headers)
137
+ a 404 response is returned if sub_path resolves to a location outside static_folder
138
+ """
139
+ root = os.path.abspath(static_folder)
140
+ filepath = os.path.abspath(os.path.join(root, sub_path))
141
+ # reject absolute sub-paths and ".." segments that escape the static folder
142
+ if os.path.commonpath([root, filepath]) != root:
143
+ return (404, b"NOT FOUND", "text/plain", {})
144
+ return self.serve_file(filepath)
145
+
128
146
  def serve_file(self, filesystem_path:str) -> tuple[int,bytes,str,dict[str,str]]:
129
147
  """
130
148
  Utility function to serve a file
@@ -149,7 +167,8 @@ class Server:
149
167
 
150
168
  headers = {k: v for (k, v) in request.headers.items()}
151
169
 
152
- request_body = request.body
170
+ # read the body here, as handlers run in a worker thread and cannot await it
171
+ request_body = await request.body()
153
172
 
154
173
  for (from_path, to_path) in self.redirects:
155
174
  if path == from_path:
@@ -191,28 +210,46 @@ class Server:
191
210
  matched = True
192
211
 
193
212
  async def sender(msg):
194
- if msg is None:
195
- await websocket.close()
196
- else:
197
- if isinstance(msg, bytes):
198
- await websocket.send_bytes(msg)
213
+ try:
214
+ if msg is None:
215
+ await websocket.close()
199
216
  else:
200
- await websocket.send_text(msg)
217
+ if isinstance(msg, bytes):
218
+ await websocket.send_bytes(msg)
219
+ else:
220
+ await websocket.send_text(msg)
221
+ except WebSocketDisconnected:
222
+ pass
201
223
 
202
224
  session_id = str(uuid.uuid4())
203
225
  ctx = WSRequestContext(session_id, sender, path, path_parameters, websocket.query_params, headers, user)
204
226
  session = handler(ctx)
227
+ if session is None:
228
+ # the handler rejected the connection, for example because the user lacks a required role
229
+ await websocket.close(code=1008) # policy violation
230
+ break
205
231
 
206
- while True:
232
+ try:
233
+ while True:
234
+ message = await websocket.receive()
235
+ if message["type"] == "websocket.disconnect":
236
+ break
237
+ # text frames are passed to the session as UTF-8 encoded bytes
238
+ data = message.get("bytes")
239
+ if data is None:
240
+ data = (message.get("text") or "").encode("utf-8")
241
+ if data != b"":
242
+ try:
243
+ await session.recv(data)
244
+ except Exception:
245
+ # keep the session open, as with HTTP handlers one failed message does not stop the server
246
+ self.logger.exception("Exception while handling websocket message")
247
+ finally:
248
+ # always let the session clean up, however the receive loop ended
207
249
  try:
208
- message = await websocket.receive_bytes()
209
- if message != b"":
210
- await session.recv(message)
211
- except WebSocketDisconnect:
212
- break
213
-
214
- if session is not None:
215
- await session.close()
250
+ await session.close()
251
+ except Exception:
252
+ self.logger.exception("Exception while closing websocket session")
216
253
  break
217
254
  if not matched:
218
255
  await websocket.close()
@@ -264,7 +301,8 @@ class Server:
264
301
 
265
302
  self.app = Starlette(debug=True, routes=[
266
303
  WebSocketRoute("/{path:path}", websocket_endpoint),
267
- Route("/{path:path}", http_endpoint),
304
+ # starlette routes only GET (and HEAD) unless methods are listed
305
+ Route("/{path:path}", http_endpoint, methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]),
268
306
  ], lifespan=lifespan)
269
307
 
270
308
  self.loop = asyncio.new_event_loop()
@@ -272,8 +310,10 @@ class Server:
272
310
  self.register_middleware(self.app)
273
311
 
274
312
  config = uvicorn.Config(
275
- self.app,port=self.port,
276
- log_level="warning",
313
+ self.app,
314
+ host=self.host,
315
+ port=self.port,
316
+ log_level=self.log_level,
277
317
  loop=lambda : self.loop)
278
318
  self.server = uvicorn.Server(config)
279
319
  self.server.run()
@@ -306,10 +346,12 @@ class Server:
306
346
  matched = pathlist == []
307
347
  return matched
308
348
 
309
- if pathlist == []:
349
+ matchexp = handlerpathlist[0]
350
+
351
+ # only $$$ can match when no path names remain
352
+ if pathlist == [] and not matchexp.startswith("$$$"):
310
353
  return False
311
354
 
312
- matchexp = handlerpathlist[0]
313
355
  # $$$ matches a path with zero or more names
314
356
  if matchexp.startswith("$$$"):
315
357
  key = matchexp[3:]
@@ -32,21 +32,26 @@ class UserDB:
32
32
  self.db.commit()
33
33
 
34
34
  def load_from_csv(self, csv_path, has_headers=True):
35
- with open(csv_path,encoding="utf-8") as f, self.lock:
35
+ with open(csv_path, encoding="utf-8", newline="") as f:
36
36
  rdr = csv.reader(f)
37
- idx = 0
37
+ if has_headers:
38
+ next(rdr, None)
38
39
  for line in rdr:
39
- if has_headers and idx == 0:
40
- continue
40
+ if not line:
41
+ continue # skip blank lines
42
+ # assign_role acquires self.lock, so it must not be held here
41
43
  self.assign_role(line[0], line[1], line[2], defer_commit=True)
44
+ with self.lock:
42
45
  self.db.commit()
43
46
 
44
47
  def save_to_csv(self, csv_path, with_headers=True):
45
- with open(csv_path, "w", encoding="utf-8") as f, self.lock:
48
+ # read the rows directly - get_roles_for_user("*") only matches wildcard user IDs
49
+ with self.lock:
50
+ all_roles = self.db.execute("SELECT USER_ID, ROLE_NAME, GROUP_NAME FROM USER_ROLES").fetchall()
51
+ with open(csv_path, "w", encoding="utf-8", newline="") as f:
46
52
  wtr = csv.writer(f)
47
53
  if with_headers:
48
54
  wtr.writerow(["user_id","role_name","group_name"])
49
- all_roles = self.get_roles_for_user("*")
50
55
  for (user_id, role_name, group_name) in all_roles:
51
56
  wtr.writerow([user_id,role_name,group_name])
52
57
 
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.4
2
+ Name: moonlette
3
+ Version: 0.2.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
+ Provides-Extra: auth
24
+ Requires-Dist: authlib; extra == "auth"
25
+ Dynamic: license-file
26
+
27
+ # moonlette
28
+
29
+ A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
30
+
31
+ HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
32
+
33
+ ## Installation
34
+
35
+ ```
36
+ pip install moonlette
37
+ ```
38
+
39
+ To use `AuthServer` (login via OpenID Connect providers), install the optional `AUTH` dependencies:
40
+
41
+ ```
42
+ pip install "moonlette[AUTH]"
43
+ ```
44
+
45
+ ## Example usage (http)
46
+
47
+ An HTTP handler receives an `HTTPRequestContext` and returns a tuple of
48
+ `(status-code, response-bytes, mime-type, custom-headers)`.
49
+
50
+ ```python
51
+ from moonlette.http_request_context import HTTPRequestContext
52
+ from moonlette.server import Server
53
+
54
+ server = Server(port=8081, host="localhost")
55
+
56
+
57
+ def hello(ctx: HTTPRequestContext):
58
+ return (200, b"It Worked!", "text/plain", {})
59
+
60
+
61
+ def echo(ctx: HTTPRequestContext):
62
+ # ctx.request_body holds the request body as bytes
63
+ return (200, ctx.request_body, "application/octet-stream", {})
64
+
65
+
66
+ server.attach_http_handler("GET", "/test", hello)
67
+ server.attach_http_handler("POST", "/echo", echo)
68
+
69
+ # serve files from a local folder, for example /static/index.html
70
+ server.attach_webroot("/static", "/path/to/static/files")
71
+
72
+ # run() blocks until the server is closed. The callback is called with True
73
+ # once the server is accepting requests, or False if it failed to start
74
+ server.run(lambda started: print("server started" if started else "server failed to start"))
75
+ ```
76
+
77
+ Call `server.close()` from another thread (or from a handler) to stop the server.
78
+
79
+ ### Path patterns
80
+
81
+ Handler paths can capture parts of the request path, which are passed to the handler in `ctx.path_parameters`:
82
+
83
+ | Pattern | Matches | Example |
84
+ |-------------|-------------------------------|-----------------------------------------------|
85
+ | `$name` | exactly one path segment | `/users/$id` matches `/users/42` |
86
+ | `$$name` | one or more path segments | `/files/$$path` matches `/files/a/b.txt` |
87
+ | `$$$name` | zero or more path segments | `/app/$$$rest` matches `/app` and `/app/x/y` |
88
+
89
+ Query parameters are available in `ctx.query_parameters` and request headers in `ctx.headers`.
90
+
91
+ ## Example usage (websockets)
92
+
93
+ A websocket handler receives a `WSRequestContext` and returns an object implementing `WSSession`.
94
+ Send messages back by awaiting `ctx.sender(msg)` with `bytes` or `str`; `await ctx.sender(None)` closes the websocket.
95
+
96
+ ```python
97
+ from moonlette.server import Server
98
+ from moonlette.ws_request_context import WSRequestContext
99
+ from moonlette.interfaces.ws_session import WSSession
100
+
101
+ server = Server(port=8081, host="localhost")
102
+
103
+
104
+ class EchoSession(WSSession):
105
+
106
+ def __init__(self, ctx: WSRequestContext):
107
+ self.ctx = ctx
108
+
109
+ async def recv(self, msg: bytes):
110
+ # echo the message back
111
+ await self.ctx.sender(msg)
112
+
113
+ async def close(self):
114
+ # called when the websocket is closed
115
+ pass
116
+
117
+
118
+ server.attach_ws_handler("/echo", EchoSession)
119
+ server.run(None)
120
+ ```
121
+
122
+ ## Authentication
123
+
124
+ `AuthServer` is a drop-in replacement for `Server` that requires users to log in before accessing handlers,
125
+ web roots and websockets. Login providers are defined in a TOML file, where `${NAME}` is replaced by the value
126
+ of the environment variable `NAME`:
127
+
128
+ ```toml
129
+ [google]
130
+ provider_type = "oidc"
131
+ label = "Login with Google"
132
+ client_id = "${GOOGLE_CLIENT_ID}"
133
+ client_secret = "${GOOGLE_CLIENT_SECRET}"
134
+ redirect_url = "http://localhost:8080/moonlette_auth/authorised"
135
+ server_metadata_url = "https://accounts.google.com/.well-known/openid-configuration"
136
+ client_kwargs = { scope = "openid email profile" }
137
+ token_settings = { user_id = "email", user_email = "email", user_name = ["given_name", "family_name"] }
138
+ ```
139
+
140
+ Roles are assigned to users in a `UserDB`, and each role is granted within a group:
141
+
142
+ ```python
143
+ from moonlette.auth_server import AuthServer
144
+ from moonlette.user_db import UserDB
145
+
146
+ user_db = UserDB("users.db")
147
+ user_db.assign_role("someone@example.com", "EDITOR", "GROUP1")
148
+
149
+ server = AuthServer(port=8080, secret_key="<a long random secret>", user_db=user_db,
150
+ auth_provider_config_path="auth_providers.toml")
151
+
152
+ # pages anyone can see, without logging in
153
+ server.attach_unauthorised_webroot("/public", "/path/to/public/files")
154
+
155
+ # pages that need a logged-in user with the EDITOR role in GROUP1
156
+ server.attach_webroot("/restricted", "/path/to/restricted/files", required_roles=[("EDITOR", "GROUP1")])
157
+
158
+ server.run(None)
159
+ ```
160
+
161
+ Users who are not logged in are redirected to `/moonlette_auth/login.html`. Handlers attached to an `AuthServer`
162
+ can read the logged-in user from `ctx.user`.
163
+
164
+ The roles database can also be managed from the command line:
165
+
166
+ ```
167
+ python -m moonlette.user_db users.db --add someone@example.com EDITOR GROUP1
168
+ python -m moonlette.user_db users.db --list-for-user someone@example.com
169
+ python -m moonlette.user_db users.db --load-from-csv roles.csv
170
+ python -m moonlette.user_db users.db --save-to-csv roles.csv
171
+ ```
172
+
173
+ CSV files have the columns `user_id,role_name,group_name` and a header row.
174
+
175
+ ## Documentation
176
+
177
+ Coming Soon
moonlette-0.2.0/PKG-INFO DELETED
@@ -1,83 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: moonlette
3
- Version: 0.2.0
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
- Provides-Extra: auth
24
- Requires-Dist: authlib; extra == "auth"
25
- Dynamic: license-file
26
-
27
- from moonlette.ws_request_context import WSRequestContext
28
-
29
- # moonlette
30
-
31
- A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
32
-
33
- HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
34
-
35
- ## Installation
36
-
37
- ```
38
- pip install moonlette
39
- ```
40
-
41
- ## Example usage (http)
42
-
43
- ```python
44
- from webserver.http_request_context import HTTPRequestContext
45
- from webserver.server import Server
46
-
47
- server = Server(port=8081, host="localhost")
48
-
49
-
50
- def handler(request_context: HTTPRequestContext):
51
- return (200, b"It Worked!", "text/plain", {})
52
-
53
-
54
- server.attach_handler("GET", "/test", handler)
55
- server.run()
56
- ```
57
-
58
- ## Example usage (websockets)
59
-
60
- ```python
61
- from webserver.server import Server
62
- from webserver.ws_request_context import WSRequestContext
63
-
64
- server = Server(port=8081, host="localhost")
65
-
66
-
67
- class EchoHandler:
68
-
69
- def __init__(self, ctx: WSRequestContext):
70
- self.ctx = ctx
71
-
72
- async def recv(self, msg):
73
- # echo the message back
74
- self.ctx.sender(msg)
75
-
76
-
77
- server.attach_ws_handler("/echo", EchoHandler)
78
- server.run()
79
- ```
80
-
81
- ## Documentation
82
-
83
- Coming Soon
moonlette-0.2.0/README.md DELETED
@@ -1,57 +0,0 @@
1
- from moonlette.ws_request_context import WSRequestContext
2
-
3
- # moonlette
4
-
5
- A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
6
-
7
- HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
8
-
9
- ## Installation
10
-
11
- ```
12
- pip install moonlette
13
- ```
14
-
15
- ## Example usage (http)
16
-
17
- ```python
18
- from webserver.http_request_context import HTTPRequestContext
19
- from webserver.server import Server
20
-
21
- server = Server(port=8081, host="localhost")
22
-
23
-
24
- def handler(request_context: HTTPRequestContext):
25
- return (200, b"It Worked!", "text/plain", {})
26
-
27
-
28
- server.attach_handler("GET", "/test", handler)
29
- server.run()
30
- ```
31
-
32
- ## Example usage (websockets)
33
-
34
- ```python
35
- from webserver.server import Server
36
- from webserver.ws_request_context import WSRequestContext
37
-
38
- server = Server(port=8081, host="localhost")
39
-
40
-
41
- class EchoHandler:
42
-
43
- def __init__(self, ctx: WSRequestContext):
44
- self.ctx = ctx
45
-
46
- async def recv(self, msg):
47
- # echo the message back
48
- self.ctx.sender(msg)
49
-
50
-
51
- server.attach_ws_handler("/echo", EchoHandler)
52
- server.run()
53
- ```
54
-
55
- ## Documentation
56
-
57
- Coming Soon
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"
@@ -1,83 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: moonlette
3
- Version: 0.2.0
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
- Provides-Extra: auth
24
- Requires-Dist: authlib; extra == "auth"
25
- Dynamic: license-file
26
-
27
- from moonlette.ws_request_context import WSRequestContext
28
-
29
- # moonlette
30
-
31
- A simple web server with websockets support based on starlette, anyio, uvicorn and authlib.
32
-
33
- HTTP requests are handled synchronously in threads. Websockets are handled asynchronously.
34
-
35
- ## Installation
36
-
37
- ```
38
- pip install moonlette
39
- ```
40
-
41
- ## Example usage (http)
42
-
43
- ```python
44
- from webserver.http_request_context import HTTPRequestContext
45
- from webserver.server import Server
46
-
47
- server = Server(port=8081, host="localhost")
48
-
49
-
50
- def handler(request_context: HTTPRequestContext):
51
- return (200, b"It Worked!", "text/plain", {})
52
-
53
-
54
- server.attach_handler("GET", "/test", handler)
55
- server.run()
56
- ```
57
-
58
- ## Example usage (websockets)
59
-
60
- ```python
61
- from webserver.server import Server
62
- from webserver.ws_request_context import WSRequestContext
63
-
64
- server = Server(port=8081, host="localhost")
65
-
66
-
67
- class EchoHandler:
68
-
69
- def __init__(self, ctx: WSRequestContext):
70
- self.ctx = ctx
71
-
72
- async def recv(self, msg):
73
- # echo the message back
74
- self.ctx.sender(msg)
75
-
76
-
77
- server.attach_ws_handler("/echo", EchoHandler)
78
- server.run()
79
- ```
80
-
81
- ## Documentation
82
-
83
- Coming Soon
File without changes
File without changes
File without changes