-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwsgi.py
More file actions
1239 lines (985 loc) · 41 KB
/
wsgi.py
File metadata and controls
1239 lines (985 loc) · 41 KB
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import hashlib
import json
import logging
import re
import http.cookies
import pickle
import queue
import urllib.parse
import random
import sys
import threading
import time
import traceback
import os
from collections.abc import MutableMapping
from datetime import datetime
from functools import wraps
from typing import Any, Type, Sequence
try:
from jinja2 import Environment, FileSystemLoader, select_autoescape
_templating_available = True
except ImportError:
Environment = FileSystemLoader = select_autoescape = None
_templating_available = False
HTTP_STATUS_CODES = {
100: "Continue",
101: "Switching Protocols",
102: "Processing",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
207: "Multi Status",
218: "This is fine",
226: "IM Used",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request URI Too Long",
415: "Unsupported Media Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
418: "I'm a teapot",
419: "Page Expired",
420: "Method Failure",
421: "Misdirected Request",
422: "Unprocessable Entity",
423: "Locked",
424: "Failed Dependency",
425: "Too Early",
426: "Upgrade Required",
428: "Precondition Required",
429: "Too Many Requests",
430: "Request Header Fields Too Large",
431: "Request Header Fields Too Large",
440: "Login Time-out",
444: "No Response",
449: "Retry With",
451: "Unavailable For Legal Reasons",
494: "Request header too large",
495: "SSL Certificate Error",
496: "SSL Certificate Required",
497: "HTTP Request Sent to HTTPS Port",
498: "Invalid Token",
499: "Token Required",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
506: "Variant Also Negotiates",
507: "Insufficient Storage",
508: "Loop Detected",
509: "Bandwidth Limit Exceeded",
510: "Not Extended",
511: "Network Authentication Required"}
class TimeoutLockError(Exception):
"""Raised by `TimeoutLock` when no lock can be acquired."""
pass
class TimeoutLock:
"""A wrapper around a single-entry FIFO queue with a context manager.
A thread-safe way to ensure that only one caller at a time can perform a
task, while other threads/callers are put in a queue and are given access
in turn.
While a caller holds a lock, others attempting to gain the lock either
block until timeout (default 30 seconds) is reached and a `TimeoutLockError`
is raised, or access to the lock is granted.
>>> lock = TimeoutLock()
>>> # from thread #1
>>> with lock:
>>> time.sleep(32)
>>> # from thread #2, this will raise a TimeoutLockerror, as thread#1 holds
>>> # lock for over 30 seconds
>>> with lock:
>>> print("my turn")
When creating multiple locks on the fly, `TimeoutLockManager` can automate
lock creation and removal.
"""
def __init__(self, timeout: int = 30):
self._lock = queue.Queue(1)
self.timeout = timeout
def __enter__(self):
self.lock()
return self
def __exit__(self, exittype, value, traceback):
self.unlock()
def wait(self):
"""Block until nobody holds a lock anymore."""
self._lock.join()
def lock(self):
"""Acquire a lock."""
try:
self._lock.put(1, block=True, timeout=self.timeout)
except queue.Full as e:
raise TimeoutLockError().with_traceback(e.__traceback__) from None
def unlock(self):
"""Release a lock."""
self._lock.get()
self._lock.task_done()
class TimeoutLockManager:
"""A callable dictionary to manage and automatically create timeout locks.
Calling a lock manager with a named lock will automatically create a new
lock object, if one does not yet exist and returns an instance of
`TimeoutLock`.
Locks can optionally expire by setting the `lock_ttl` to a non-None value
(i.e lock time to live, in seconds). If set, will launch a background
thread that periodically cleans up locks that have not been accessed since
`lock_ttl` seconds.
If `lock_ttl` is set, and it is expected that TimeoutLockManagers are created
and removed on the fly, the stop() method should be called before deleting
the lock manager in order to clean up the background thread.
Examples:
>>> locks = TimeoutLockManager()
>>> locks("sim_12").wait() # blocks, if someone is locking
>>> with locks("sim_22", 10):
>>> # locks, causing anyone currently calling "sim_22" to block and
>>> # fail with a TimeOutLockError after a 10 second wait
>>> pass
"""
def __init__(self, lock_ttl: int = None):
self._locks = {}
self._lock_ttl = lock_ttl
self._stop_timer = False
if self._lock_ttl is not None:
self.expiration_timer = threading.Thread(target=self._expire_locks)
self.expiration_timer.daemon = True
self.expiration_timer.start()
def __call__(self, lock_name: str, timeout: int = 30):
if lock_name not in self._locks:
self._locks[lock_name] = {"lock": TimeoutLock(timeout),
"atime": time.time()}
else:
self._locks[lock_name]["atime"] = time.time()
return self._locks[lock_name]["lock"]
def __len__(self):
return len(self._locks)
def _expire_locks(self):
while True:
if self._stop_timer:
return
time.sleep(random.randint(30, 60))
interval = int(time.time())
expired_locks = []
for lock_name, lock in self._locks.items():
if interval - lock["atime"] > self._lock_ttl:
expired_locks.append(lock_name)
for lock_name in expired_locks:
self.remove(lock_name)
def remove(self, lock_name: str):
"""Remove an unused lock."""
if lock_name in self._locks:
del self._locks[lock_name]
def stop(self):
"""Stop cleanup thread."""
self._stop_timer = True
session_locks = TimeoutLockManager(lock_ttl=30)
class FileSession(MutableMapping):
"""A file-based session.
Automatically saves and loads session state to disk using pickle whenever
dictionary entries change.
The session class needs to be initiated at least once, and that instance
has to be called for each session ID:
>>> session_class = FileSession("/tmp")
>>> s1 = session_class("1") # get a session
>>> s2 = session_class("2") # get a different session
"""
def __call__(self, sid: str, *args, **kwargs):
return FileSession(self.dir_path, sid, *args, **kwargs)
def __init__(self, dir_path: str, sid: str = None, *args: Any, **kwargs: Any):
"""Create a new file-based session storage.
Args:
dir_path: Location on the system to store session files in
sid: Session ID
*args: Optional initial session data as values
**kwargs: Optional initial session data as key-value pairs
"""
self.exists = False
self.dir_path = self.file_path = dir_path
if sid:
self.file_path = os.path.join(dir_path, sid)
self.sid = sid
if args:
self._data = dict(args)
elif kwargs:
self._data = kwargs
else:
self._data = {}
self._load()
def __delitem__(self, key):
del self._data[key]
self._save()
def __getitem__(self, key):
self._load()
return self._data[key]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def __setitem__(self, key, value):
self._data[key] = value
self._save()
self.modified = True
def _load(self):
if self.sid:
try:
with open(self.file_path, "rb") as f:
self._data = pickle.load(f)
self.exists = True
except (IOError, EOFError, pickle.UnpicklingError):
pass
except Exception as e:
logging.getLogger("wsgi.FileSession").warning(
f"failed to load session: {e}")
def _save(self):
if self.sid:
with open(self.file_path, "wb") as f:
try:
pickle.dump(self._data, f, pickle.HIGHEST_PROTOCOL)
self.exists = True
except Exception as e:
logging.getLogger("wsgi.FileSession").warning(
f"failed to save session: {e}")
def destroy(self):
"""Erase session and its data on disk."""
self._data = {}
try:
if self.sid:
os.remove(self.file_path)
except Exception:
pass
def save(self):
"""Force a session save.
Session is automatically saved whenever one of its top-level attributes
is altered. A session will not save if one contents of its mutable
properties are altered.
>>> s = FileSession("/tmp", "1")
>>> s["customer"] = "Anonymous" # auto-saved
>>> s["cart"] = {"item_count": 0} # auto-saved
>>> s["cart"]["item_count"] += 1 # NOT auto-saved
>>> s.save()
"""
self._save()
class LockingFileSession(FileSession):
"""A thread-safe file session.
Wraps `FileSession`, allowing only a single thread at a time to load a
session or update session keys. Other threads attempting to alter the
session at the same time will block until the session is again accessible,
or a timeout occurs (30 seconds).
"""
def _load(self):
with session_locks(self.sid, timeout=2):
super()._load()
def __getitem__(self, key):
return self._data[key]
def __setitem__(self, key, value):
with session_locks(self.sid, timeout=2):
super().__setitem__(key, value)
def destroy(self):
"""Destroy and erase session data."""
with session_locks(self.sid, timeout=2):
super().destroy()
memory_sessions = {}
class MemorySession(MutableMapping):
"""A memory-based session.
A very simple memory-based session that does not persist over restarts.
Does by default nothing at all until the first session entry is saved.
"""
def __init__(self, sid: str, *args: Any, **kwargs: Any):
"""Create a new memory-based session.
Args:
sid: Session ID
*args: Initial session data as a value list
**kwargs: Initial session data as a key-value list
"""
self.sid = sid
if self.sid in memory_sessions:
self._data = memory_sessions[self.sid]
elif args:
self._data = dict(args)
elif kwargs:
self._data = kwargs
else:
self._data = {}
def __delitem__(self, key):
del self._data[key]
def __getitem__(self, key):
return self._data[key]
def __iter__(self):
return iter(self._data)
def __len__(self):
return len(self._data)
def __setitem__(self, key, value):
self._check_and_create()
self._data[key] = value
def _check_and_create(self):
if self.sid not in memory_sessions:
memory_sessions[self.sid] = {}
self._data = memory_sessions[self.sid]
def destroy(self):
self._data = {}
def save(self):
pass
class WsgiApp:
"""Basic WSGI HTTP request handler application.
To be used together with a WSGI compliant web server, this class can be
passed as a parameter to the WSGI server to catch all HTTP requests and
process them. Implementing parties should subclass this and put
user-functionality in the DELETE, GET, POST and PUT methods. The implemented
methods should return two values: content to be returned to browser and a
list of headers as tuples to be set.
This handler also sets automatically a session cookie for each request and
exposes the session id in `self.env["SESSION_ID"]`. To store data in session,
the implementing class should use the self.session dictionary, which by
default is a MemorySession object (does not persist over server restarts).
Normally this class is never called directly, it is intended to be used
together with the WsgiAppDispatcher, which maps request paths to
applications.
Sample usage:
>>> import cheroot.wsgi
>>> class MyApp(WsgiApp):
>>> def GET(self, path=None):
>>> return str(path), [("Content-Type", "text/html")]
>>>
>>> # map all URLs to MyApp, catching the part after /
>>> urls = [("/(.*)?", MyApp)]
>>>
>>> app = WsgiAppDispatcher(urls)
>>>
>>> server = cheroot.wsgi.Server(("localhost", 8080), app)
>>> server.start()
"""
args: dict
"""URL query parameters, or an empty dictionary."""
headers: dict
"""Request headers, with header names written in Header-Notation."""
debug: bool = False
"""Debug mode.
When True, detailed errors are shown in browser. When False, only 500
Server errors are returned.
"""
request_uri: str
"""Full, (almost) original request URI. If provided by the HTTP server, as
either the REQUEST_URI (mod_wsgi, uwsgi) or the RAW_URI (gunicorn)
environment variable, it is used as-is. If neither is present, it is
re-constructed from various environment variables, according to PEP-3333.
"""
server_version: str = "Python/WSGI"
"""Server version, set as the "Server" header in all responses."""
session_class: Type[MutableMapping] = MemorySession
"""Session class to use.
Overwrite this to change from `MemorySession` to e.g `FileSession`. Can
be any dict-like mutable interface.
"""
routes = {"GET": [], "POST": [], "PUT": [], "DELETE": [], "OPTIONS": []}
template_path: str = "templates/"
"""Path for templates.
Either an absolute path or a path relative to the current python module.
See `render_template` for details.
"""
url: urllib.parse.ParseResult
"""Request URL as a result of `urllib.parse.urlparse`."""
def __init__(self, dispatcher_matches: list[str] = None):
"""Creates a new app request instance.
A new instance should never be created manually. Instead, pass the class
itself as an argument to `WsgiAppDispatcher`, which will create a new
app instance for each incoming request.
Args:
dispatcher_matches: List of matched capture groups in a URL. Filled
in automatically by WsgiAppDispatcher when a new request is
created.
"""
self.dispatcher_matches = dispatcher_matches or []
self.template_env = None
if _templating_available:
self.template_env = Environment(
loader=FileSystemLoader(self.template_path),
autoescape=select_autoescape(["html", "xml"]))
def __call__(self, env, start_response):
time_start = time.time()
headercookie = env.get("HTTP_COOKIE")
cookie = http.cookies.SimpleCookie()
if headercookie:
cookie.load(headercookie)
if "session_id" not in cookie:
session_id = hashlib.sha1("{}{}{}".format(
os.urandom(16), time.time(), env.get("REMOTE_ADDR")).encode())
cookie["session_id"] = session_id.hexdigest()
session_cookie = cookie["session_id"]
env["SESSION_ID"] = cookie["session_id"].value
self._input = None
self.base_path = ""
self.env = env
if "REQUEST_URI" in env:
# mod_wsgi, uwsgi
self.url = urllib.parse.urlparse(env["REQUEST_URI"])
self.request_uri = env["REQUEST_URI"]
elif "RAW_URI" in env:
# gunicorn
self.url = urllib.parse.urlparse(env["RAW_URI"])
self.request_uri = env["RAW_URI"]
else:
# fallback is attempting to do it ourselves, this is straight from
# PEP-3333
url = env["wsgi.url_scheme"] + "://"
if env.get("HTTP_HOST"):
url += env["HTTP_HOST"]
else:
url += env["SERVER_NAME"]
if env["wsgi.url_scheme"] == "https":
if env["SERVER_PORT"] != "443":
url += ":" + env["SERVER_PORT"]
else:
if env["SERVER_PORT"] != "80":
url += ":" + env["SERVER_PORT"]
url += urllib.parse.quote(env.get("SCRIPT_NAME", ""))
url += urllib.parse.quote(env.get("PATH_INFO", ""))
if env.get("QUERY_STRING"):
url += "?" + env["QUERY_STRING"]
self.url = urllib.parse.urlparse(url)
self.request_uri = url
self.session = self.session_class(env["SESSION_ID"])
if self.url.query:
self.args = parse_qs_dict(self.url.query)
else:
self.args = {}
self.headers: dict[str, str] = {}
for key, value in env.items():
if key.startswith("HTTP_"):
header_name = "-".join(w.capitalize() for w in key.split("_")[1:])
self.headers[header_name] = value
headers = [("Content-Type", "text/html")]
http_status = "200 OK"
conversion_methods = {
"int": int, "str": str, "float": float,
"bool": lambda b: b.lower() in ("true", "yes")}
patterns = {"int:": r"[\d]+", "float:": r"[\d\.]+",
"bool:": r"true|false|yes|no"}
word_pattern = r"[^/]+"
try:
routed_method = None
route_path_matches = None
if self.routes and self.routes[env["REQUEST_METHOD"]]:
for p, method in self.routes[env["REQUEST_METHOD"]]:
# since routes are defined on the class level, and the
# routes don't have any knowledge of the class that
# WsgiAppDispatcher has picked, path collisions may exist.
# This filters out routes that don't actually belong to
# "self".
method_classname = method.__qualname__.split(".")[0]
if method_classname != self.__class__.__name__:
continue
try:
# look for <type>:<param_name> pairs in the route path
# and replace them with just <param_name>
convert: dict = {}
param_conversions = re.findall(r"<(int|str|bool|float):(.+?)>", p)
if param_conversions:
for t, param_name in param_conversions:
convert[param_name] = conversion_methods[t]
# convert <type:param_name> and <param_name> to
# python regex capture groups that match the specific
# type. I.e (?P<param_name>\d+), (?P<param_name>\w+) etc
path_match = re.sub(
"<(int:|str:|bool:|float:)?(.+?)>",
lambda m: f"(?P<{m[2]}>{patterns.get(m[1], word_pattern)})",
p)
else:
# there are no conversions, just convert <param_name>
# to a python regex named capture group that matches
# any word, i.e (?P<param_name>\w+)
path_match = re.sub("<(.+?)>", "(?P<\\1>[^/]+)", p)
if self.dispatcher_matches:
match_against = self.dispatcher_matches[0]
self.base_path = env["PATH_INFO"].replace(match_against, "")
else:
match_against = env["PATH_INFO"]
self.base_path = ""
result = re.match("^" + path_match + "$", match_against,
flags=re.IGNORECASE)
if result:
routed_method = method
route_path_matches = result.groupdict()
break
except re.error as e:
print(f"Path regular expression error: {str(e)} for "
f"path {env['PATH_INFO']}")
self.before_request()
if routed_method:
for match_param, match_value in route_path_matches.items():
if match_param in convert:
try:
route_path_matches[match_param] = convert[match_param](match_value)
except Exception:
pass
response = routed_method(self, **route_path_matches)
elif env["REQUEST_METHOD"] == "POST":
response = self.POST(*self.dispatcher_matches)
elif env["REQUEST_METHOD"] == "GET":
response = self.GET(*self.dispatcher_matches)
elif env["REQUEST_METHOD"] == "OPTIONS":
response = self.OPTIONS(*self.dispatcher_matches)
elif env["REQUEST_METHOD"] == "PUT":
response = self.PUT(*self.dispatcher_matches)
elif env["REQUEST_METHOD"] == "DELETE":
response = self.DELETE(*self.dispatcher_matches)
else:
raise WsgiMethodNotallowed()
if isinstance(response, tuple):
response, headers = response
elif isinstance(response, WsgiHttpResponse):
http_status = response.http_status
headers = response.headers
response = response.data or ""
except WsgiHttpError as e:
http_status = e.http_status
response = e.html_body
headers = e.headers
except Exception as e:
http_status = "500 Internal Server Error"
if self.debug:
response = repr(e)
else:
response = ""
logging.getLogger("WsgiApp").warning(
f"WSGI app raised an exception: {repr(e)}")
exc_info = sys.exc_info()
logging.getLogger("WsgiApp").error(
"".join(traceback.format_exception(*exc_info)))
set_cookie = "-"
if session_cookie is not None:
set_cookie = session_cookie.OutputString()
headers.append(("Set-Cookie", set_cookie))
if not response:
response = ""
if isinstance(response, str):
response = response.encode("utf-8")
length = str(len(response))
headers.append(("Content-Length", length))
headers.append(("Server", self.server_version))
self.before_response(http_status, headers, response)
start_response(http_status, headers)
time_finish = time.time()
delta = f"{time_finish - time_start:6f}"
print('{} - - [{}] "{}" {} {} {} {}'.format(
env.get("REMOTE_ADDR") or "-",
datetime.now().replace(microsecond=0),
env.get("PATH_INFO") or "",
(http_status or "000").split()[0],
length,
delta,
set_cookie))
return [response]
def _read_input(self):
if self._input is None:
if "CONTENT_LENGTH" in self.env:
length = int(self.env.get("CONTENT_LENGTH", 0))
self._input = self.env["wsgi.input"].read(length)
else:
# chunked transfer encoding, so read the whole input anyway
self._input = self.env["wsgi.input"].read()
return self._input
@property
def data(self) -> bytes:
"""HTTP request body in raw format"""
return self._read_input()
@property
def form_data(self) -> dict:
"""HTTP request body parsed as a dict.
This does not expect a form-data Content-Type header, but in order for
the parsing to work, the request body needs to be in a format at least
similar to form-data.
"""
return parse_qs_dict(self._read_input().decode())
@property
def json(self) -> dict:
"""HTTP request body parsed as JSON.
Assumes that the request body is a well-formed JSON string. No check for
headers is made, attempting to read JSON input when the request contains
no actual JSON data will raise an exception.
"""
return json.loads(self._read_input())
@classmethod
def route(cls, path: str, methods: list[str] | str | None = None):
"""Route specific paths inside an app to a method.
For apps that handle multiple different paths with different logic, this
method can be used to "sub" route them further, instead of attempting
to parse self.url.path inside the app, or instead of creating an app for
every possible path.
Args:
path: The request path to route to the method. If the path
pattern in the `WsgiAppDispatcher` setup has a capture group, the
path is matched against that group. If no capture group is
defined, the match is done against whole URL. The path can
contain placeholders for parts that are dynamic, enclosed in `<`
and `>`, e.g `<user_name>` or `<int:user_id>`. If placeholder is
prefixed with an "int:", "bool:", "float:" or "str:", the value
is converted respectively. Any placeholders are passed onto the
routed method as keyword arguments.
methods: A list of HTTP methods to route to method, or a single
method, defaults to GET
Usage:
>>> class CustomerApp(WsgiApp):
>>>
>>> # this matches /customer_service/customers
>>> @WsgiApp.route("customers")
>>> def get_customers(self):
>>> return json_response()
>>>
>>> # this matches /customer_service/customer
>>> @WsgiApp.route("customer", methods=["PUT"])
>>> def create_customer(self):
>>> return json_response()
>>>
>>> # this matches /customer_service/customer/4545
>>> @WsgiApp.route("customer/<int:customer_id>")
>>> def get_customer_by_id(self, customer_id):
>>> return json_response(id=customer_id)
>>>
>>> def GET(self, *args, **kwargs):
>>> return WsgiNotFound("Fallback when path not found")
>>>
>>> class SimApp(WsgiApp):
>>>
>>> # this matches /sim_service/sims. Note that the path given in
>>> # WsgiAppDispatcher has no capture group, so the .route path
>>> # matches the whole path instead
>>> @WsgiApp.route("/sim_service/sims")
>>> def get_sims(self):
>>> return json_response()
>>>
>>> app = WsgiAppDispatcher([
>>> ("/customer_service/(.+)", CustomerApp),
>>> ("/sim_service/.+", SimApp)
>>> ])
"""
if not methods:
methods = ["GET"]
if not isinstance(methods, list):
methods = [methods]
def wrapper(f):
for method in methods:
cls.routes[method].append((path, f))
@wraps(f)
def decorator(self, *args, **kwargs):
return f(self, *args, **kwargs)
return decorator
return wrapper
def DELETE(self, *args):
"""Method called for an HTTP DELETE request.
This method is called if the HTTP REQUEST_METHOD is "DELETE", unless a
method routed using `route` is called instead. Should be overwritten by
the implementing class, otherwise will raise `WsgiMethodNotAllowed`.
"""
raise WsgiMethodNotallowed()
def GET(self, *args):
"""Method called for an HTTP GET request.
This method is called if the HTTP REQUEST_METHOD is "GET", unless a
method routed using `route` is called instead. Should be overwritten by
the implementing class, otherwise will raise `WsgiMethodNotAllowed`.
"""
raise WsgiMethodNotallowed()
def OPTIONS(self, *args):
"""Method called for an HTTP OPTIONS request.
This method is called if the HTTP REQUEST_METHOD is "OPTIONS", unless a
method routed using `route` is called instead. Should be overwritten by
the implementing class, otherwise will raise `WsgiMethodNotAllowed`.
"""
raise WsgiMethodNotallowed()
def POST(self, *args):
"""Method called for an HTTP POST request.
This method is called if the HTTP REQUEST_METHOD is "POST", unless a
method routed using `route` is called instead. Should be overwritten by
the implementing class, otherwise will raise `WsgiMethodNotAllowed`.
"""
raise WsgiMethodNotallowed()
def PUT(self, *args):
"""Method called for an HTTP PUT request.
This method is called if the HTTP REQUEST_METHOD is "PUT", unless a
method routed using `route` is called instead. Should be overwritten by
the implementing class, otherwise will raise `WsgiMethodNotAllowed`.
"""
raise WsgiMethodNotallowed()
def before_request(self):
"""Called before request is handed over to a handling method.
This method is called right after parsing headers and input values,
after routing is done, but right before the request is passed on to a
GET, DELETE, PUT, POST or a routed method. By default does nothing.
"""
pass
def before_response(self, http_status: str, http_headers: list,
response_body: bytes):
"""Called before a handled response is returned to browser.
This method is called after a request has been fully processed by a
handling method, right before WSGI start_response method is called, i.e
before data is given back to the handling web server.
This method is called *in any case*, even if the handling request
returns or raises an exception. By default does nothing.
"""
pass
def render_template(self, template_name: str, **kwargs: Any) -> tuple[str, tuple]:
"""Render a template file and return a WSGI compliant response.
Loads a template file located in the template folder and renders it as
a jinja2 template.
Any keyword arguments are passed straight to the template context and
are available as local variables within the template. In addition the
variable "app" is available, which points to the WSGI app itself, i.e:
* app.form_data
* app.json
* app.session
..etc are available within the template.
If keyword argument "headers" is set, it is used as the headers for
the response instead. If not, the headers will be set to
Content-Type: text/html.
Args:
template_name: Name or path of a template to load
**kwargs: Variables to pass to the jinja2 template
Returns:
A tuple of rendered template content (string) and a list of headers
(tuple), that can be passed directly as the return value in a WSGI
app
Sample usage:
>>> class WebUi(WsgiApp):
>>> template_path = "ui/static/templates/"
>>> @WsgiApp.route("start")
>>> def start_page(self):
>>> return self.render_template("start.html")
"""
if not self.template_env:
raise RuntimeError("jinja2 templating is not available. Is it installed?")
template = self.template_env.get_template(template_name)
kwargs["app"] = self
headers = kwargs.get("headers", [])
header_dict = dict(headers)
if "Content-Type" not in header_dict:
headers.append(("Content-Type", "text/html"))
return template.render(**kwargs), headers
class WsgiAppDispatcher:
"""A callable WSGI application mapper.
An instance of WsgiAppDispatcher is what should be passed on to a
WSGI-compliant web server. The web server will call the app dispatcher for
every incoming request, and the dispatcher will forward the request to an
appropriate WSGI app, and then returns the return values from the app back
to the server.
"""
def __init__(self, pathmap: Sequence[tuple[str, Type[WsgiApp]]]):
"""Create a new app dispatcher.
Args:
pathmap: A list of path-class pairs, where the path is a string that
may contain regular expressions, which is matched against the
current request URL path. When a path matches, a new instance of
the given class is created and executed
Usage examples:
>>> class UiApp(WsgiApp):
>>> pass
>>> class ServiceApp(WsgiApp):
>>> pass
>>> class StatusApp(WsgiApp):
>>> pass
>>>
>>> app = WsgiAppDispatcher([
>>> ("/service/(.+)", ServiceApp),
>>> ("/status", StatusApp),
>>> ("/(.+)", UiApp)
>>> ])
"""
self.pathmap = pathmap