2016-10-21 01:29:04 +08:00
|
|
|
import uuid
|
2019-02-05 09:07:49 +08:00
|
|
|
from functools import lru_cache
|
2016-10-21 01:29:04 +08:00
|
|
|
|
|
|
|
|
|
|
|
class IntConverter:
|
|
|
|
regex = '[0-9]+'
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
return int(value)
|
|
|
|
|
|
|
|
def to_url(self, value):
|
|
|
|
return str(value)
|
|
|
|
|
|
|
|
|
|
|
|
class StringConverter:
|
|
|
|
regex = '[^/]+'
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
return value
|
|
|
|
|
|
|
|
def to_url(self, value):
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
class UUIDConverter:
|
|
|
|
regex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
|
|
|
|
|
|
|
|
def to_python(self, value):
|
|
|
|
return uuid.UUID(value)
|
|
|
|
|
|
|
|
def to_url(self, value):
|
|
|
|
return str(value)
|
|
|
|
|
|
|
|
|
|
|
|
class SlugConverter(StringConverter):
|
|
|
|
regex = '[-a-zA-Z0-9_]+'
|
|
|
|
|
|
|
|
|
|
|
|
class PathConverter(StringConverter):
|
|
|
|
regex = '.+'
|
|
|
|
|
|
|
|
|
|
|
|
DEFAULT_CONVERTERS = {
|
|
|
|
'int': IntConverter(),
|
|
|
|
'path': PathConverter(),
|
|
|
|
'slug': SlugConverter(),
|
|
|
|
'str': StringConverter(),
|
|
|
|
'uuid': UUIDConverter(),
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
REGISTERED_CONVERTERS = {}
|
|
|
|
|
|
|
|
|
|
|
|
def register_converter(converter, type_name):
|
|
|
|
REGISTERED_CONVERTERS[type_name] = converter()
|
|
|
|
get_converters.cache_clear()
|
|
|
|
|
|
|
|
|
2019-02-05 09:07:49 +08:00
|
|
|
@lru_cache(maxsize=None)
|
2016-10-21 01:29:04 +08:00
|
|
|
def get_converters():
|
2017-02-18 08:45:34 +08:00
|
|
|
return {**DEFAULT_CONVERTERS, **REGISTERED_CONVERTERS}
|
2016-10-21 01:29:04 +08:00
|
|
|
|
|
|
|
|
|
|
|
def get_converter(raw_converter):
|
|
|
|
return get_converters()[raw_converter]
|