Skip to content

Instantly share code, notes, and snippets.

@jaddison
Last active August 29, 2015 14:28
Show Gist options
  • Save jaddison/18dea1bf93767f326aa5 to your computer and use it in GitHub Desktop.
Save jaddison/18dea1bf93767f326aa5 to your computer and use it in GitHub Desktop.
Django URL Dispatcher example
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import Constraint, Resolver404
"""
where the following in in the project settings.py:
SITE_DOMAIN_MY = ('http', 'my.example.com')
SITE_DOMAIN_WWW = ('http', 'www.example.com')
SITE_DOMAIN_MANAGE = ('http', 'manage.example.com')
"""
class ConstraintBase(Constraint):
"""
This exists purely as a way to ensure MRO mixin inheritance will work
"""
def match(self, path, request=None):
return path, (), {}
def construct(self, url, *args, **kwargs):
return url, args, kwargs
class SchemeConstraintMixin(object):
scheme = ''
def match(self, path, request=None):
if request and request.scheme == self.scheme:
return super(SchemeConstraintMixin, self).match(path, request)
raise Resolver404()
def construct(self, url, *args, **kwargs):
url.scheme = self.scheme
return super(SchemeConstraintMixin, self).construct(url, *args, **kwargs)
class HostConstraintMixin(object):
host = ''
def match(self, path, request=None):
if request and request.get_host() == self.host:
return super(HostConstraintMixin, self).match(path, request)
raise Resolver404()
def construct(self, url, *args, **kwargs):
url.host = self.host
return super(HostConstraintMixin, self).construct(url, *args, **kwargs)
class SchemeHostConstraint(SchemeConstraintMixin, HostConstraintMixin, ConstraintBase):
def __init__(self, scheme, host):
self.scheme = scheme
self.host = host
www_urlpatterns = [
url(r'^$', 'images.views.homepage', name='homepage'),
url(r'^users/', include('users.urls.profiles')),
url(r'^', include('images.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
my_urlpatterns = [
url(r'^businesses/', include('businesses.urls.manage')),
url(r'^user/', include('users.urls.auth')),
url(r'^user/', include('users.urls.social')),
]
manage_urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns = [
url(SchemeHostConstraint(*settings.SITE_DOMAIN_WWW), include(www_urlpatterns)),
url(SchemeHostConstraint(*settings.SITE_DOMAIN_MY), include(my_urlpatterns)),
url(SchemeHostConstraint(*settings.SITE_DOMAIN_MANAGE), include(manage_urlpatterns))
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment