-
Notifications
You must be signed in to change notification settings - Fork 3
/
__init__.py
110 lines (88 loc) · 2.41 KB
/
__init__.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
VERSION = (0,1,2)
def get_version():
return ".".join(map(str, VERSION))
_default_patterns_ = {
# Keys
'pk': r'\d+',
'id': r'\d+',
'slug': r'[A-Za-z0-9_-]+',
# Date
'day': r'(([0-2])?([1-9])|[1-3]0|31)',
'month': r'(0?[1-9]|10|11|12)',
'year': r'\w{4}',
'date': r'\w{4}-(0?([1-9])|10|11|12)-((0|1|2)?([1-9])|[1-3]0|31)',
# filters
'page': r'\d+',
'filename': r'[\w,\s-]+\.[A-Za-z]{2,4}',
}
"""
Classname: Djurl
Description: Django Url
Author: Christopher Ventura Aguiar <venturachrisdev@gmail.com>
Date: Jun 22, 2017
Long description:
"""
class Djurl():
def __init__(self, pattern, exact=True):
self.pattern = pattern
self.exact = exact
if self.pattern.startswith('/'):
self.pattern = self.pattern[1:]
def normalize(self, path):
stpath = path.lstrip("^\n")
if len(stpath) > 1:
stpath = stpath.lstrip("//");
stpath = stpath.rstrip(" $\n")
result = "^%s"
if self.exact:
result += "$"
# Trim
return result % stpath
def trim(self, path):
return path.replace(" ", "")
def create_pattern(self, key, pattern):
return "(?P<%s>%s)" % (key, pattern)
#core
def build(self):
built = self.trim(self.pattern)
if len(built) > 1:
import re
paramkeys = re.findall('(:([a-z_\d]+))', built)
for matches, key in paramkeys:
if key in _default_patterns_:
newpattern = self.create_pattern(key, _default_patterns_[key])
built = built.replace(":%s" % key, newpattern)
print(built)
else:
for x in _default_patterns_:
if key.endswith('_%s' % x):
newpattern = self.create_pattern(key, _default_patterns_[x])
built = built.replace(":%s" % key, newpattern)
if not built.endswith('/') and not built.endswith('$'):
built += '/'
result = self.normalize(built)
return result
@property
def built(self):
if not hasattr(self, '_built'):
setattr(self, '_built', self.build())
return getattr(self, '_built')
def __str__(self):
return self.built
#compatibily with python 2
def __unicode__(self):
return self.__str__()
def register_pattern(key, pattern):
_default_patterns_[key] = pattern
def url(pattern, view, kwargs=None, name=None):
exact = True
v = view
# Class Based Views
if isinstance(view, type):
if hasattr(view, 'as_view'):
v = view.as_view()
# include
if isinstance(v, tuple):
exact = False
from django.conf.urls import url as BaseUrl
return BaseUrl(Djurl(pattern, exact=exact), v, kwargs=kwargs, name=name)