This function takes a pattern with groups and replaces them with the given args and/or kwargs. Example:
IMPORTANT: this code is NOT to use replacing Django's reverse function. The example below is just to illustrate how it works.
For a given pattern '/docs/(\d+)/rev/(\w+)/', args=(123,'abc') and kwargs={}, returns '/docs/123/rev/abc/'.
For '/docs/(?P<id>\d+)/rev/(?P<rev>\w+)/', args=() and kwargs={'rev':'abc', 'id':123}, returns '/docs/123/rev/abc/' as well.
When both args and kwargs are given, raises a ValueError.
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 | import re
def replace_groups(pattern, args=None, kwargs=None):
"""
This function takes a pattern with groups and replace them with the given args and/or
kwargs. Example:
IMPORTANT: this code is NOT to use replacing Django's reverse function. The
example below is just to illustrate how it works.
For a given pattern '/docs/(\d+)/rev/(\w+)/', args=(123,'abc') and kwargs={},
returns '/docs/123/rev/abc/'.
For '/docs/(?P<id>\d+)/rev/(?P<rev>\w+)/', args=() and kwargs={'rev':'abc', 'id':123}
returns '/docs/123/rev/abc/' as well.
For now, when both args and kwargs are given, raises a ValueError.
"""
if args and kwargs:
raise ValueError("Informed both *args and **kwargs it's not supported.")
exp_kwarg = re.compile('^\(\?P<(\w+)>(.+)\)$') # Used to check named arguments
new = ''
cur_group = ''
group_count = 0
for ch in pattern:
if ch == '(':
group_count += 1
cur_group += ch
elif ch == ')':
group_count -= 1
cur_group += ch
if not group_count:
m_kwarg = exp_kwarg.match(cur_group)
if m_kwarg:
value = str(kwargs.pop(m_kwarg.group(1)))
else:
value = str(args[0])
args = args[1:]
if re.match('^%s$'%cur_group, value):
new += value
cur_group = ''
elif group_count:
cur_group += ch
else:
new += ch
return new
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
I guess you've looked at django.core.urlresolvers.reverse?
#
Adam, yes, I know it, but it's totally another approach for this, and actually, I disagree the way it does and I see it as a really ugly code (one of the ugliest in Django code).
#
But, BTW, this is not being used as a replacement for reverse. I used the URL example just to make it easier to understand for who is reading :)
#
hey
#
Please login first before commenting.