Skip to content

Instantly share code, notes, and snippets.

@mx-moth
Created February 16, 2015 23:15
Show Gist options
  • Save mx-moth/a3da93a1d9c433ee66bd to your computer and use it in GitHub Desktop.
Save mx-moth/a3da93a1d9c433ee66bd to your computer and use it in GitHub Desktop.
Wagtail view proxy
from wagtail.contrib.wagtailroutablepage.models import RoutablePageMixin
from wagtail.wagtailcore.models import Page
from .viewproxy import ViewModuleProxy
views = ViewModuleProxy('myapp.views')
class MyPage(Page):
serve = views.mypage
class MyRoutablePage(RoutablePageMixin, Page):
subpage_urls = (
url(r'^$', 'v_list', name='list'),
url(r'^(?P<id>\d+)/$', 'v_detail', name='detail'),
)
v_list = views.myroutablepage_list
v_detail = views.myroutablepage_detail
class Item(models.Model):
pass
from __future__ import absolute_import, unicode_literals, print_function
from django.utils.module_loading import import_module
class ViewModuleProxy(object):
"""
A lazy loading proxy of a view module
"""
view_module = None
def __init__(self, view_path):
self.view_path = view_path
def views(self):
"""Import the views module named in self.view_path"""
if self.view_module is None:
self.view_module = import_module(self.view_path)
return self.view_module
def __getattr__(self, name):
"""Get a proxy to a view in the proxied module"""
return ViewProxy(self, name).proxy()
class ViewProxy(object):
"""
A lazy loading proxy of a view
"""
view = None
def __init__(self, view_module_proxy, name):
self.view_module_proxy = view_module_proxy
self.name = name
def proxy(self):
"""
Return a view function that loads the real view lazily.
Note the order of the page and request arguments is swapped when calling the real view,
to match standard Django views.
"""
def proxy(page, request, *args, **kwargs):
if self.view is None:
self.view = getattr(self.view_module_proxy.views(), self.name)
return self.view(request, page, *args, **kwargs)
return proxy
from django.shortcuts import render
# Views are lazy loaded, so importing from models is fine
from .models import Item
def mypage(request, mypage):
return render(request, 'myapp/mypage.html', {'page': mypage})
def myroutablepage_list(request, myroutablepage):
item_list = Item.objects.all()
return render(request, 'myapp/myroutablepage_list.html', {'page': myroutablepage, 'item_list': item_list})
def myroutablepage_detail(request, myroutablepage, id):
item = Item.objects.get(pk=id)
return render(request, 'myapp/myroutablepage_list.html', {'page': myroutablepage, 'item': item})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment