/
itty3.py
1471 lines (1170 loc) · 42.8 KB
/
itty3.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
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
# -*- coding: utf-8 -*-
"""
itty3
=====
The itty-bitty Python web framework... **Now Rewritten For Python 3!**
"""
import functools
import http.cookies
import io
import json
import logging
import mimetypes
import os
import re
import sys
import urllib.parse
import wsgiref.headers
import wsgiref.util
__author__ = "Daniel Lindsley"
__version__ = (
1,
1,
1,
)
__license__ = "New BSD"
def get_version(full=False):
"""
Fetches the current version of itty3.
Args:
full (bool): Chooses between the short semver version and the
longer/full version, including release information.
Returns:
str: The version string
"""
short = ".".join([str(v) for v in __version__[:3]])
if full:
long = "-".join([str(v) for v in __version__[3:]])
return "{}-{}".format(short, long) if long else short
return short
# Default logging config for itty3.
# We attach a NullHandler by default, so that we don't produce logs.
# The user can choose to add new handlers to capture logs, at the
# level/location they wish.
log = logging.getLogger(__name__)
null_handler = logging.NullHandler()
log.addHandler(null_handler)
PY_VERSION = sys.version_info
# Constants
GET = "GET"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
PATCH = "PATCH"
HEAD = "HEAD"
OPTIONS = "OPTIONS"
TRACE = "TRACE"
PLAIN = "text/plain"
HTML = "text/html"
JSON = "application/json"
FORM = "application/x-www-form-urlencoded"
AJAX = "X-Requested-With"
COOKIE_HEADER = "HTTP-COOKIE"
SAME_SITE_NONE = "None"
SAME_SITE_LAX = "Lax"
SAME_SITE_STRICT = "Strict"
UUID_PATTERN = (
r"[A-Fa-f0-9]{{8}}-"
r"[A-Fa-f0-9]{{4}}-"
r"[A-Fa-f0-9]{{4}}-"
r"[A-Fa-f0-9]{{4}}-"
r"[A-Fa-f0-9]{{12}}"
)
# Borrowed & modified from Django.
RESPONSE_CODES = {
100: "Continue",
101: "Switching Protocols",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
306: "Reserved",
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",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported",
}
# Exceptions
class IttyException(Exception):
"""
The base exception for all itty3 exceptions.
"""
pass
class ResponseFailed(IttyException):
"""
Raised when a response could not be returned to the server/user.
"""
pass
class RouteNotFound(IttyException):
"""
Raised when no method/path combination could be found.
"""
pass
# Request/Response bits
class QueryDict(object):
"""
Simulates a dict-like object for query parameters.
Because HTTP allows for query strings to provide the same name for a
parameter more than once, this object smoothes over the day-to-day usage
of those queries.
You can act like it's a plain `dict` if you only need a single value.
If you need all the values, `QueryDict.getlist` & `QueryDict.setlist`
are available to expose the full list.
"""
def __init__(self, data=None):
self._data = data
if self._data is None:
self._data = {}
def __str__(self):
return "<QueryDict: {} keys>".format(len(self._data))
def __repr__(self):
return str(self)
def __iter__(self):
return iter(self._data)
def __contains__(self, name):
return name in self._data
def __getitem__(self, name):
values = self.getlist(name)
return values[0]
def __setitem__(self, name, value):
self._data.setdefault(name, [])
self._data[name][0] = value
def get(self, name, default=None):
"""
Tries to fetch a value for a given name.
If not found, this returns the provided `default`.
Args:
name (str): The name of the parameter you'd like to fetch
default (bool, defaults to `None`): The value to return if the
`name` isn't found.
Returns:
Any: The found value for the `name`, or the `default`.
"""
try:
return self[name]
except KeyError:
return default
def getlist(self, name):
"""
Tries to fetch all values for a given name.
Args:
name (str): The name of the parameter you'd like to fetch
Returns:
list: The found values for the `name`.
Raises:
KeyError: If the `name` isn't found
"""
if name not in self._data:
raise KeyError("{} not found".format(name))
return self._data[name]
def setlist(self, name, values):
"""
Sets all values for a given name.
Args:
name (str): The name of the parameter you'd like to fetch
values (list): The list of all values
Returns:
None
"""
self._data[name] = values
def keys(self):
"""
Returns all the parameter names.
Returns:
list: A list of all the parameter names
"""
return self._data.keys()
def items(self):
"""
Returns all the parameter names & values.
Returns:
list: A list of two-tuples. The parameter names & the *first*
value for that name.
"""
results = []
for key, values in self._data.items():
if len(values) < 1:
results.append((key, None))
else:
results.append((key, values[0]))
return results
class HttpRequest(object):
"""
A request object, representing all the portions of the HTTP request.
Args:
uri (str): The URI being requested.
method (str): The HTTP method ("GET|POST|PUT|DELETE|PATCH|HEAD")
headers (dict, Optional): The received HTTP headers
body (str, Optional): The body of the HTTP request
scheme (str, Optional): The HTTP scheme ("http|https")
host (str, Optional): The hostname of the request
port (int, Optional): The port of the request
content_length (int, Optional): The length of the body of the request
request_protocol (str, Optional): The protocol of the request
cookies (http.cookies.SimpleCookie, Optional): The cookies sent as
part of the request.
"""
def __init__(
self,
uri,
method,
headers=None,
body="",
scheme="http",
host="",
port=80,
content_length=0,
request_protocol="HTTP/1.0",
cookies=None,
):
self.raw_uri = uri
self.method = method.upper()
self.body = body
self.scheme = scheme
self.host = host
self.port = int(port)
self.content_length = int(content_length)
self.request_protocol = request_protocol
self._cookies = cookies or http.cookies.SimpleCookie()
self.COOKIES = {}
# For caching.
self._GET, self._POST, self._PUT = None, None, None
if not headers:
headers = {}
# `Headers` is specific about wanting a list of tuples, so just doing
# `headers.items()` isn't good enough here.
self.headers = wsgiref.headers.Headers(
[(k, v) for k, v in headers.items()]
)
for key, morsel in self._cookies.items():
self.COOKIES[key] = morsel.value
uri_bits = self.split_uri(self.raw_uri)
domain_bits = uri_bits.get("netloc", ":").split(":", 1)
self.path = uri_bits["path"]
self.query = uri_bits.get("query", {})
self.fragment = uri_bits.get("fragment", "")
if not self.host:
self.host = domain_bits[0]
if len(domain_bits) > 1 and domain_bits[1]:
self.port = int(domain_bits[1])
def __str__(self):
return "<HttpRequest: {} {}>".format(self.method, self.raw_uri)
def __repr__(self):
return str(self)
def get_status_line(self):
return "{} {} {}".format(
self.method, self.path, self.request_protocol
)
def split_uri(self, full_uri):
"""
Breaks a URI down into components.
Args:
full_uri (str): The URI to parse
Returns:
dict: A dictionary of the components. Includes `path`, `query`
`fragment`, as well as `netloc` if host/port information is
present.
"""
bits = urllib.parse.urlparse(full_uri)
uri_data = {
"path": bits.path,
"query": {},
"fragment": bits.fragment,
}
# We need to do a bit more work to make the query portion useful.
if bits.query:
uri_data["query"] = urllib.parse.parse_qs(
bits.query, keep_blank_values=True
)
if bits.netloc:
uri_data["netloc"] = bits.netloc
return uri_data
@classmethod
def from_wsgi(cls, environ):
"""
Builds a new HttpRequest from the provided WSGI `environ`.
Args:
environ (dict): The bag of YOLO that is the WSGI environment
Returns:
HttpRequest: A fleshed out request object, based on what was
present.
"""
headers = {}
cookies = {}
non_http_prefixed_headers = [
"CONTENT-TYPE",
"CONTENT-LENGTH",
# TODO: Maybe in the future, add support for...?
# 'GATEWAY_INTERFACE',
# 'REMOTE_ADDR',
# 'REMOTE_HOST',
# 'SCRIPT_NAME',
# 'SERVER_NAME',
# 'SERVER_PORT',
]
for key, value in environ.items():
mangled_key = key.replace("_", "-")
if mangled_key == COOKIE_HEADER:
cookies = http.cookies.SimpleCookie()
cookies.load(value)
elif mangled_key.startswith("HTTP-"):
headers[mangled_key[5:]] = value
elif mangled_key in non_http_prefixed_headers:
headers[mangled_key] = value
body = ""
wsgi_input = environ.get("wsgi.input", io.StringIO(""))
content_length = environ.get("CONTENT_LENGTH", 0)
if content_length not in ("", 0):
# StringIO & the built-in server have this attribute, but things
# like gunicorn do not. Give it our best effort.
if not getattr(wsgi_input, "closed", False):
body = wsgi_input.read(int(content_length))
else:
content_length = 0
return cls(
uri=wsgiref.util.request_uri(environ),
method=environ.get("REQUEST_METHOD", GET),
headers=headers,
body=body,
scheme=wsgiref.util.guess_scheme(environ),
port=environ.get("SERVER_PORT", "80"),
content_length=content_length,
request_protocol=environ.get("SERVER_PROTOCOL", "HTTP/1.0"),
cookies=cookies,
)
def content_type(self):
"""
Returns the received Content-Type header.
Returns:
str: The content-type header or "text/html" if it was absent.
"""
return self.headers.get("Content-Type", HTML)
def _ensure_unicode(self, body):
raw_data = urllib.parse.parse_qs(body)
revised_data = {}
# `urllib.parse.parse_qs` can be a very BYTESTRING-Y BOI.
# Ensure all the keys/value are Unicode.
for key, value in raw_data.items():
if isinstance(key, bytes):
key = key.decode("utf-8")
if isinstance(value, bytes): # pragma: no cover
value = value.decode("utf-8")
elif isinstance(value, (list, tuple)):
new_value = []
for v in value:
if isinstance(v, bytes):
v = v.decode("utf-8")
new_value.append(v)
value = new_value
revised_data[key] = value
return revised_data
@property
def GET(self):
"""
Returns a `QueryDict` of the GET parameters.
"""
if self._GET is not None:
return self._GET
self._GET = QueryDict(self.query)
return self._GET
@property
def POST(self):
"""
Returns a `QueryDict` of the POST parameters from the request body.
Useless if the body isn't form-encoded data, like JSON bodies.
"""
if self._POST is not None:
return self._POST
self._POST = QueryDict(self._ensure_unicode(self.body))
return self._POST
@property
def PUT(self):
"""
Returns a `QueryDict` of the PUT parameters from the request body.
Useless if the body isn't form-encoded data, like JSON bodies.
"""
if self._PUT is not None:
return self._PUT
self._PUT = QueryDict(self._ensure_unicode(self.body))
return self._PUT
def is_ajax(self):
"""
Identifies if the request came from an AJAX call.
Returns:
bool: True if sent via AJAX, False otherwise
"""
return AJAX in self.headers
def is_secure(self):
"""
Identifies whether or not the request was secure.
Returns:
bool: True if the environment specified HTTPs, False otherwise
"""
return self.scheme == "https"
def json(self):
"""
Decodes a JSON body if present.
Returns:
dict: The data
"""
if self.content_type() != JSON:
return {}
return json.loads(self.body)
class HttpResponse(object):
"""
A response object, to make responding to requests easier.
A lightly-internal `start_response` attribute must be manually set on the
response object when in a WSGI environment in order to send the response.
Args:
body (str, Optional): The body of the response. Defaults to "".
status_code (int, Optional): The HTTP status code (without the
reason). Default is `200`.
headers (dict, Optional): The headers to supply with the response.
Default is empty headers.
content_type (str, Optional): The content-type of the response.
Default is `text/plain`.
"""
def __init__(
self, body="", status_code=200, headers=None, content_type=PLAIN,
):
self.body = body
self.status_code = int(status_code)
self.headers = headers or {}
self.content_type = content_type
self._cookies = http.cookies.SimpleCookie()
self.start_response = None
self.set_header("Content-Type", self.content_type)
def __str__(self):
return "<HttpResponse: {}>".format(self.status_code)
def __repr__(self):
return str(self)
def set_header(self, name, value):
"""
Sets a header on the response.
If the `Content-Type` header is provided, this also updates the
value of `HttpResponse.content_type`.
Args:
name (str): The name of the header.
value (Any): The value of the header.
"""
self.headers[name] = value
if name.lower() == "content-type":
self.content_type = value
def set_cookie(
self,
key,
value="",
max_age=None,
expires=None,
path="/",
domain=None,
secure=False,
httponly=False,
samesite=None,
):
"""
Sets a cookie on the response.
Takes the same parameters as the `http.cookies.Morsel` object from
the Python stdlib.
Args:
key (str): The name of the cookie.
value (Any): The value of the cookie.
max_age (int, Optional): How many seconds the cookie lives for.
Default is `None`
(expires at the end of the browser session).
expires (str or datetime, Optional): A specific date/time (in
UTC) when the cookie should expire. Default is `None`
(expires at the end of the browser session).
path (str, Optional): The path the cookie is valid for.
Default is `"/"`.
domain (str, Optional): The domain the cookie is valid for.
Default is `None` (only the domain that set it).
secure (bool, Optional): If the cookie should only be served by
HTTPS. Default is `False`.
httponly (bool, Optional): If `True`, prevents the cookie from
being provided to Javascript requests. Default is `False`.
samesite (str, Optional): How the cookie should behave under
cross-site requests. Options are `itty3.SAME_SITE_NONE`,
`itty3.SAME_SITE_LAX`, and `itty3.SAME_SITE_STRICT`.
Default is `None`.
Only for Python 3.8+.
"""
morsel = http.cookies.Morsel()
# TODO: In the future, signed cookies might be nice here.
morsel.set(key, value, value)
# Allow setting expiry w/ a `datetime`.
if hasattr(expires, "strftime"):
expires = expires.strftime("%a, %-d %b %Y %H:%M:%S GMT")
# Always update the meaningful params.
morsel.update({"path": path, "secure": secure, "httponly": httponly})
# Ensure the max-age is an `int`.
if max_age is not None:
morsel["max-age"] = int(max_age)
if expires is not None:
morsel["expires"] = expires
if domain is not None:
morsel["domain"] = domain
if PY_VERSION[1] >= 8 and samesite is not None:
# `samesite` is only supported in Python 3.8+.
morsel["samesite"] = samesite
self._cookies[key] = morsel
def delete_cookie(self, key, path="/", domain=None):
"""
Removes a cookie.
Succeed regards if the cookie is already set or not.
Args:
key (str): The name of the cookie.
path (str, Optional): The path the cookie is valid for.
Default is `"/"`.
domain (str, Optional): The domain the cookie is valid for.
Default is `None` (only the domain that set it).
"""
self.set_cookie(
key,
value="",
# We set a Max-Age of `0` to expire the cookie immediately,
# thus "deleting" it.
max_age=0,
path=path,
domain=domain,
)
def write(self):
"""
Begins the transmission of the response.
The lightly-internal `start_response` attribute **MUST** be manually
set on the object **BEFORE** calling this method! This callable is
called during execution to set the status line & headers of the
response.
Returns:
iterable: An iterable of the content
Raises:
ResponseFailed: If no `start_response` was set before calling.
"""
if not self.start_response:
raise ResponseFailed(
"{}.write called before being provided a callable".format(
self.__class__.__name__
)
)
status = "{} {}".format(
self.status_code,
RESPONSE_CODES.get(self.status_code, RESPONSE_CODES[500]),
)
headers = [(k, v) for k, v in self.headers.items()]
possible_cookies = self._cookies.output()
# Update the headers to include the cookies.
if possible_cookies:
for line in possible_cookies.splitlines():
headers.append(tuple(line.split(": ", 1)))
self.start_response(status, headers)
return [self.body.encode("utf-8")]
# Routing
class Route(object):
"""
Handles setting up a given route. Composed of a HTTP method, a URI path
& "view" (a callable function that takes a `request` & returns a
`response` object) for handling a matching request.
Variables can be added to the path using a `<type:variable_name>` syntax.
For instance, if you wanted to capture a UUID & an integer in a URI, you
could provide the following `path`::
"/app/<uuid:app_id>/version/<int:major_version>/"
These would be added onto the call to the view as additional arguments.
In the case of the previous `path`, the view's signature should look
like::
def app_info(request, app_id, major_version): ...
Supported types include:
* `str`
* `int`
* `float`
* `slug`
* `uuid`
Args:
method (str): The HTTP method
path (str): The URI path to match against
func (callable): The view function to handle a matching request
"""
known_types = [
"str",
"int",
"float",
"uuid",
"slug",
]
def __init__(self, method, path, func):
self.method = method.upper()
self.path = path
self.func = func
self._regex, self._type_conversions = self.create_re(self.path)
def __str__(self):
return "<Route: {} for '{}'>".format(self.method, self.path,)
def __repr__(self):
return str(self)
def get_re_for_int(self):
return r"[\d]+"
def get_re_for_float(self):
return r"[\d]+.[\d]+"
def get_re_for_uuid(self):
return UUID_PATTERN
def get_re_for_slug(self):
return r"[\w\d._-]+"
def get_re_for_any(self):
return r".+"
def get_re_for_type(self, desired_type):
"""
Fetches the correct regex for a given type.
Args:
desired_type (str): The provided type to get a regex for
Returns:
str: A raw string of the regex (minus the variable name)
"""
pattern = r"[^/]+"
get_re_method_name = "get_re_for_{}".format(desired_type)
get_re_method = getattr(self, get_re_method_name, None)
if get_re_method is not None:
pattern = get_re_method()
regex_frag = r"(?P<{{var_name}}>{})".format(pattern)
return regex_frag
def create_re(self, path):
"""
Creates a compiled regular expression of a `path`.
It'd be unusual to need this as an end-user, but who am I to stop
you? :)
Args:
path (str): A URI path, potentially with `<type:variable_name>`
bits in it.
Returns:
tuple: A tuple of the compiled regular expression that suits the
path & dict of the variable names/type conversions to be done
upon matching.
"""
# Start out assuming there will be no kwargs.
raw_regex = path
type_conversions = {}
# Next, check for any variables
variable_re = re.compile(r"\<(?P<ts>\w+):(?P<var_name>[\w\d]+)\>")
var_matches = variable_re.findall(path)
# Iterate over the two tuple, add to the type conversions &
# spruce up the path regex.
for var_type, var_name in var_matches:
type_conversions[var_name] = var_type
search = "<{}:{}>".format(var_type, var_name)
# Get the type-appropriate replacement regex.
replacement_raw_re = self.get_re_for_type(var_type)
replacement = replacement_raw_re.format(var_name=var_name)
# Swap out the pattern match for the regular expression
# for matching.
raw_regex = raw_regex.replace(search, replacement)
regex = re.compile("^" + raw_regex + "$")
return regex, type_conversions
def can_handle(self, method, path):
"""
Determines if the route can handle a specific request.
Args:
method (str): The HTTP method coming from the request
path (str): The URI path coming from the request
Returns:
bool: True if this route can handle the request, False otherwise
"""
if self.method != method:
return False
if not self._regex.match(path):
return False
return True
def extract_kwargs(self, path):
"""
Pulls variables out of the requested URI path.
Args:
path (str): The URI path coming from the request
Returns:
dict: A dictionary of the variable names from the path &
converted data found for them. Empty dict if no variables
were present.
"""
matches = self._regex.match(path)
if matches:
return self.convert_types(matches.groupdict())
return {}
def convert_types(self, matches):
"""
Takes raw matched from requested URI path & converts the data to
their proper type.
Args:
matches (dict): The variable names & the *string* data found
for them from the URI path.
Returns:
dict: The converted data
"""
for name, value in matches.items():
if name not in self._type_conversions:
continue
if self._type_conversions[name] == "int":
matches[name] = int(value)
elif self._type_conversions[name] == "float":
matches[name] = float(value)
return matches
# App!
class App(object):
"""
An orchestration object that handles routing & request processing.
Args:
debug (bool): Allows for controlling a debugging mode.
"""
def __init__(self, debug=False):
self._routes = []
self.debug = debug
self.static_root = None
self.static_url_path = None
self.log = self.get_log()
def get_log(self):
"""
Returns a `logging.Logger` instance.
By default, we return the `itty3` module-level logger. Users are
free to override this to meet their needs.
Returns:
logging.Logger: The module-level logger
"""
return log
def __call__(self, environ, start_response):
# Allows providing the `App` instance as the WSGI handler to
# many WSGI servers.
return self.process_request(environ, start_response)
def add_route(self, method, path, func):
"""
Adds a given HTTP method, URI path & view to the routing.
Args:
method (str): The HTTP method to handle
path (str): The URI path to handle
func (callable): The view function to process a matching request
"""
route = Route(method, path, func)
self._routes.append(route)
self.log.debug("Added {} - {}".format(route, func.__name__))
def find_route(self, method, path):
"""
Determines the routing offset for a given HTTP method & URI path.
Args:
method (str): The HTTP method to handle
path (str): The URI path to handle
Returns:
int: The offset of the matching route
Raises:
RouteNotFound: If a matching route is not found
"""
for offset, route in enumerate(self._routes):
if route.method == method:
if route.path == path:
return offset
raise RouteNotFound()
def remove_route(self, method, path):
"""
Removes a route from the routing.
Args:
method (str): The HTTP method to handle