Skip to content

Instantly share code, notes, and snippets.

@aipi
Last active May 18, 2017 14:18
Show Gist options
  • Save aipi/58cd71f914acfe040f2dfc42a680fe58 to your computer and use it in GitHub Desktop.
Save aipi/58cd71f914acfe040f2dfc42a680fe58 to your computer and use it in GitHub Desktop.
understanding and joking with Django URLs
from django.conf.urls import urlpatterns
from django.core.urlresolvers import set_urlconf, resolve, reverse
os.eviron.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
def index(request): pass
def auth(request): pass
def list_(request): pass
def edit(request): pass
def new(request): pass
def delete(request): pass
class LENDConf:
def __init__(self, model):
self.model = model_name
self.urlpatterns = [
url(r'^$', name='list'),
url(r'^(\d+)$', list_, name='edit'),
url(r'^new/$', edit, name='new'),
url(r'^delete/$', delete, name='delete'),
]
class MySiteURLConf:
urlpatterns = [
url(r'^/$', index, name='')
url(r'^login/$', auth, name='')
url(r'^logout/$', auth, name='')
url(r'^groups/$', include(LENDConf('groups'), namespace='groups'))
url(r'^users/$', include(LENDConf('users'), namespace='users'))
]
set_urlconf(MySiteURLConf)
print()
print('Resolve')
print(resolve('/index/'))
print(resolve('/login/'))
print(resolve('/logout/'))
print(resolve('/groups/'))
print(resolve('/groups/'))
print(resolve('/groups/new/'))
print(resolve('/groups/delete/'))
print(resolve('/users/'))
print(resolve('/users/1/'))
print(resolve('/users/new/'))
print(resolve('/users/delete/'))
print()
print('Reverse')
print(reverse('index'))
print(reverse('login'))
print(reverse('logout'))
print(reverse('list'))
print(reverse('edit'), args=[1])
print(reverse('new'))
print(reverse('delete'))
print(reverse('list'))
print(reverse('edit'), args=[1])
print(reverse('new'))
print(reverse('delete'))
# ---------------------------------------------------------
from django.core.urlresolvers import get_resolver
r = get_resolver()
print(r)
# r.url_patterns r.urlconf_module r.urlconf_name
print(r.url_patterns)
'''
[<RegexURLPattern None ^$>,
<RegexURLPattern None ^login/$>,
<RegexURLPattern None ^logout/$>,
<RegexURLPattern None ^groups/$>,
<RegexURLPattern None ^groups/(\d+)/$>,
<RegexURLPattern None ^groups/news/$>,
<RegexURLPattern None ^groups/delete/$>,
<RegexURLPattern None ^users/$>,
<RegexURLPattern None ^users/(\d+)/$>,
<RegexURLPattern None ^users/news/$>,
<RegexURLPattern None ^users/delete/$>,
<RegexURLResolver <RegexPattern list> (admin:admin) ^admin/>]
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment