Plain is headed towards 1.0! Subscribe for development updates →

urls

Route requests to views.

 1import functools
 2import uuid
 3
 4
 5class IntConverter:
 6    regex = "[0-9]+"
 7
 8    def to_python(self, value):
 9        return int(value)
10
11    def to_url(self, value):
12        return str(value)
13
14
15class StringConverter:
16    regex = "[^/]+"
17
18    def to_python(self, value):
19        return value
20
21    def to_url(self, value):
22        return value
23
24
25class UUIDConverter:
26    regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
27
28    def to_python(self, value):
29        return uuid.UUID(value)
30
31    def to_url(self, value):
32        return str(value)
33
34
35class SlugConverter(StringConverter):
36    regex = "[-a-zA-Z0-9_]+"
37
38
39class PathConverter(StringConverter):
40    regex = ".+"
41
42
43DEFAULT_CONVERTERS = {
44    "int": IntConverter(),
45    "path": PathConverter(),
46    "slug": SlugConverter(),
47    "str": StringConverter(),
48    "uuid": UUIDConverter(),
49}
50
51
52REGISTERED_CONVERTERS = {}
53
54
55def register_converter(converter, type_name):
56    REGISTERED_CONVERTERS[type_name] = converter()
57    get_converters.cache_clear()
58
59
60@functools.cache
61def get_converters():
62    return {**DEFAULT_CONVERTERS, **REGISTERED_CONVERTERS}
63
64
65def get_converter(raw_converter):
66    return get_converters()[raw_converter]