diff options
| author | Andrew <saintruler@gmail.com> | 2019-07-06 14:36:55 +0400 |
|---|---|---|
| committer | Andrew <saintruler@gmail.com> | 2019-07-06 14:36:55 +0400 |
| commit | 1e6967f8c4f1ef64947d7f2b95268339d78db454 (patch) | |
| tree | b2ebf1ccb160e3c58f277dfec4bae8f83b03ec45 /day9/task5/router.py | |
| parent | f1a923860c02c69d9e67d15da24f90d7306223e0 (diff) | |
WIP: Изменена структура сервера.
Diffstat (limited to 'day9/task5/router.py')
| -rw-r--r-- | day9/task5/router.py | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/day9/task5/router.py b/day9/task5/router.py new file mode 100644 index 0000000..c3857f7 --- /dev/null +++ b/day9/task5/router.py @@ -0,0 +1,40 @@ +import re +from utils import NOT_FOUND_CODE, BAD_REQUEST_CODE + + +def route(url_format, methods=None): + if methods is None: + methods = ['GET'] + + def wrapper(func): + def inner(url, query, *args, **kwargs): + pattern = re.compile(url_format) + match = re.fullmatch(pattern, url) + + if match is None or len(match.groups()) != pattern.groups: + return BAD_REQUEST_CODE + + return func(query, *match.groups(), *args, **kwargs) + + _router_tree[url_format] = _router_tree.get(url_format, {}) + for method in methods: + _router_tree[url_format][method] = inner + + return inner + + return wrapper + + +def run(request): + res = NOT_FOUND_CODE + + method, url = request['method'], request['url'] + for url_pattern in _router_tree: + if re.fullmatch(url_pattern, url) and method in _router_tree[url_pattern]: + res = _router_tree[url_pattern][method](url, request['query']) + break + + return res + + +_router_tree = {} |