-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
executable file
·336 lines (284 loc) · 11.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
"""
## Example project structure:
```txt
./Main Folder
/server.py
/pages
.html
.css
.js
/subfolder
.html
...
/errors
/404
.html
.css
.js
...
```
In order to access the url `/`, the server will look for `./pages/.html`.
Smiliarly, requests to `/subfolder` will look for `./pages/subfolder/.html`.
You can customize error pages by creating a folder in `./errors` with the name of the error code.
"""
__version__ = "0.2.4"
NAME = "http_plus_purplelemons_dev"
from http.server import HTTPServer, ThreadingHTTPServer
from typing import Callable
from .auth import Auth
from .communications import *
from .asyncServer import AsyncHandler
class Server:
"""
Main class for the HTTP Plus server library.
* Initialize the server with `server = Server(host, port)`.
* Listen to HTTP methods with `@server.<method>(path)`,
for example `@server.get("/")`.
"""
def __init__(self, /, *, brython:bool=True, page_dir:str="./pages", error_dir="./errors", debug:bool=False, **kwargs):
"""
Listen to HTTP methods with `@server.<method>(path)`, for example...
```
@server.get("/")
def _(req, res):
return res.send("Hello, world!")
```
More about the `req` and `res` objects can be found in `http_plus.communications`.
Args:
brython (bool): Whether or not the server should ship brython files.
page_dir (str): The directory to serve pages from.
error_dir (str): The directory to serve error pages from.
debug (bool): Whether or not to print debug messages.
"""
self.debug = debug
self.handler = Handler
self.handler.responses
self.handler.debug = debug
self.handler.brython = brython
self.handler.page_dir = page_dir[:-1] if page_dir.endswith("/") else page_dir
self.handler.error_dir = error_dir[:-1] if error_dir.endswith("/") else error_dir
def listen(self, port:int, ip:str=None) -> None:
"""
Starts the server, a blocking loop on the current thread.
The IP will default to all interfaces (`0.0.0.0`) if not specified, unless if the
server was initialized with `debug=True`, in which case it will default to loopback
(`127.0.0.1`).
Args:
port (int): The port to listen on. Must be available, otherwise the server will raise a binding error.
ip (str): String in the form of an IP address to listen on. Must be an address on the current machine.
"""
if self.debug:
if ip is None:
# Debug and no IP specified, use loopback
ip = "127.0.0.1"
print(f"Listening on http://{ip}{':'+str(port) if port != 80 else ''}/")
elif ip is None:
# No debug and no IP specified, use all interfaces
ip = "0.0.0.0"
try:
ThreadingHTTPServer((ip,port), self.handler).serve_forever()
except KeyboardInterrupt:
print("\nServer stopped.")
except Exception as e:
print(f"Server error: {e}")
@staticmethod
def _make_method(server_wrapper:Callable):
"""
Wrapper for wrapping `@server.<METHOD>` methods.
"""
# can someone confirm if this is a 3rd order function?
# if not, idk what this is and lord forgive me for my sins
def method(self:"Server", path:str):
def decorator(func:Callable):
try:
self.handler.responses[server_wrapper.__name__][path] = func
except KeyError:
raise RouteExistsError(path)
return decorator
return method
def log(self, func:Callable):
"""
A decorator that adds a custom logger to the server.
Your logger function should take in a `Handler` object as its only argument.
"""
self.handler.custom_logger = func
def all(self, path:str, exclude:list[str]=[]):
"""
A decorator that adds a route to the server. Listens to all HTTP methods.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.get("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
def decorator(func:Callable):
funcs = [self.get, self.post, self.put, self.delete, self.patch, self.options, self.head, self.trace]
if exclude:
# by far one of my most clever lines of code
funcs.remove(*exclude)
for method in funcs:
try:
method(path)(func)
except KeyError:
raise RouteExistsError(path)
return decorator
def gql(self, schema:str, endpoint:str="/api/graphql"):
"""
A decorator that adds a route to the server. Listens *ONLY* to GET requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.gql("/product/:id")` passes in `{"id": "..."}`).
Args:
endpoint (str): The endpoint that the server will listen on.
"""
def decorator(func:Callable):
try:
self.handler.gql_endpoints[endpoint] = func
self.handler.gql_schemas[endpoint] = schema
except KeyError:
raise RouteExistsError(endpoint)
return decorator
@_make_method
def stream(self, path:str):
"""
A decorator that adds a route to the server. Listens *ONLY* to GET requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.stream("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def get(self, path:str):
"""
A decorator that adds a route to the server. Listens to GET requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.get("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def post(self, path:str):
"""
A decorator that adds a route to the server. Listens to POST requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.post("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def put(self, path:str):
"""
A decorator that adds a route to the server. Listens to PUT requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.put("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def delete(self, path:str):
"""
A decorator that adds a route to the server. Listens to DELETE requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.delete("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def patch(self, path:str):
"""
A decorator that adds a route to the server. Listens to PATCH requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.patch("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def options(self, path:str):
"""
A decorator that adds a route to the server. Listens to OPTIONS requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.options("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def head(self, path:str):
"""
A decorator that adds a route to the server. Listens to HEAD requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.head("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
@_make_method
def trace(self, path:str):
"""
A decorator that adds a route to the server. Listens to TRACE requests.
If you use a keyword wildcard in the route url, arguments will be passed into
the function via **kwargs (e.g. `@server.trace("/product/:id")` passes in `{"id": "..."}`).
Args:
path (str): The path to respond to.
"""
class AsyncServer(Server):
def __init__(self, /, *, brython: bool = True, page_dir: str = "./pages", error_dir="./errors", debug: bool = False, **kwargs):
super().__init__(brython=brython, page_dir=page_dir, error_dir=error_dir, debug=debug, **kwargs)
self.handler = AsyncHandler
self.handler.debug = debug
self.handler.brython = brython
self.handler.page_dir = page_dir[:-1] if page_dir.endswith("/") else page_dir
self.handler.error_dir = error_dir[:-1] if error_dir.endswith("/") else error_dir
self.handler.protocol = "HTTP/1.1"
self.handler.server_version = f"http+/{__version__}"
def listen(self, port:int, ip:str=None) -> None:
"""
Starts the server, a blocking loop on the current thread.
The IP will default to all interfaces (`0.0.0.0`) if not specified, unless if the
server was initialized with `debug=True`, in which case it will default to loopback
(`127.0.0.1`).
Args:
port (int): The port to listen on. Must be available, otherwise the server will raise a binding error.
ip (str): String in the form of an IP address to listen on. Must be an address on the current machine.
"""
if self.debug:
if ip is None:
# Debug and no IP specified, use loopback
ip = "127.0.0.1"
print(f"Listening on http://{ip}{':'+str(port) if port != 80 else ''}/")
elif ip is None:
# No debug and no IP specified, use all interfaces
ip = "0.0.0.0"
try:
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.handler.create_task = loop.create_task
coro = loop.create_server(self.handler, ip, port)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
except Exception as e:
print(f"Server error: {e}")
raise e
def init():
"""
Initializes the current directory for HTTP+
"""
import os
if not os.path.exists("pages"):
os.mkdir("pages")
if not os.path.exists("errors"):
os.mkdir("errors")
if not os.path.exists("server.py"):
with open("server.py", "w") as f:
print("""
import http_plus
server = http_plus.Server()
@server.get("/")
def _(req:http_plus.Request, res:http_plus.Response):
res.set_header("Content-type", "text/html")
return res.set_body("<h2>Hello, world!</h2>")
server.listen()
""", file=f)