Commits

Adam Knight committed 4c15154

Cleaned up a lot of code relating to looking for Sections and Pages. Now Pages are looked for before urls.py is consulted.
Removed SITE_URL as a setting.

Comments (0)

Files changed (7)

context_preprocessors/__init__.py

-from django.conf import settings
 from django.contrib.sites.models import Site
-from milton.models import Story, Section
 
 def general(request):
     return {
         "site": Site.objects.get_current(),
-        "stories": Story.published.all(),
-        "sections": Section.objects.all(),
     }
 # http://www.allyourpixel.com/post/metaweblog-38-django/
 
 import urlparse
+from django.conf import settings
 from django.contrib.auth.models import User
+from django.contrib.site.models import Site
+from django.core.urlresolvers import reverse
 from milton.models import *
+from milton.xmlrpc import public
 from tagging.models import Tag
 from tagging.utils import parse_tag_input
-from milton.xmlrpc import public
-from django.conf import settings
-from django.core.urlresolvers import reverse
 import xmlrpclib # import DateTime
 
 def authenticated(pos=1):
         return _wrapper
     return _decorate
 
-def full_url(url):
-    return urlparse.urljoin(settings.SITE_URL, url)
+def full_url(url=''):
+    return urlparse.urljoin("http://"+str(Site.objects.get_current_site().domain, url)
 
 # example... this is what wordpress returns:
 # {'permaLink': 'http://gabbas.wordpress.com/2006/05/09/hello-world/',
     result = [{
             'blogid': section.slug,
             'blogName': section.name,
-            'url': settings.SITE_URL + reverse('story-archive', kwargs={'section':section.slug})
+            'url': full_url(reverse('story-archive', kwargs={'section':section.slug}))
             } for section in sections]
     print "results:", result
     return result
     return {
         'nickname':user.username,
         'userid':user.id,
-        'url':settings.SITE_URL,
+        'url':full_url(),
         'email':user.email,
         'lastname':user.last_name,
         'firstname':user.first_name,

middleware/__init__.py

+from logging import getLogger
+
 from django.conf import settings
 from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect, HttpResponseGone, Http404
-from django.template import Template, RequestContext, loader
+from django.template import RequestContext, loader
+
+from milton.models import Redirect, Page
+from milton.views import story_archive, view_page
 
-from milton.models import Redirect, Page, Story
-from milton.views import view_page
+
+logger = getLogger(__name__)
 
 class RedirectionMiddleware(object):
     def process_response(self, request, response):
             path = request.path
             paths = [path]
             
-            # Also try without the trailing slash if someone tacked it on for us
-            if settings.APPEND_SLASH:
-                paths.append(path[:path.rfind('/')] + path[path.rfind('/')+1:])
-            
+            logger.debug("Redirect: Looking for %s" % (path,))
+
             r = Redirect.objects.get(site__id__exact=settings.SITE_ID, original__in=paths)
             
             # If the destination is not visible, let the 404 shine.
             if hasattr(r.target_object, 'visible') and r.target_object.visible == False:
+                logger.debug("Redirect: Object exists, but is unpublished.")
                 return response
             
             # If there's a redirect, process it
         
         except Redirect.DoesNotExist, e:
             # Otherwise, return the original response
+            logger.debug("Redirect: No redirect found for for %s" % (path,))
             return response
         except:
             if settings.DEBUG:
                 raise
         # If we're here, we didn't catch something -- just pass along the 404.
+        logger.debug("Redirect: No alternate plan for %s; passing along the NotFound." % (path,))
         return response
 
 
 class PageMiddleware(object):
-    def process_response(self, request, response):
-        # If the response found something, return it.
-        if response.status_code != 404:
-            return response
-        # Otherwise, see if we can get a response from the view
+    def process_request(self, request):
+        path = request.path_info
+        page = None
+        
+        # Look for a Page that matches; pass on failure.
         try:
-            return view_page(request, request.path_info)
-        # If the view couldn't find a page, then return the original response (don't pollute)
-        except Http404:
-            return response
-        # If anything else goes wrong here, just ignore it and return the original response (again, don't pollute)
-        except:
-            if settings.DEBUG:
-                raise
-            return response
+            logger.debug("PageMiddleware: Looking for a page for %s" % (path,))
+            page = Page.published.get(url=path)
+        except Page.DoesNotExist, e:
+            return None
+        
+        logger.debug("PageMiddleware: Found for a page for %s" % (path,))
+        return view_page(request, path)

middleware/page.py

-from django.conf import settings
-from django.http import Http404
-
-from milton.models import Page
-from milton.views import view_page
-
-
-class PageMiddleware(object):
-    def process_response(self, request, response):
-        # If the response found something, return it.
-        if response.status_code != 404:
-            return response
-        # Otherwise, see if we can get a response from the view
-        try:
-            return view_page(request, request.path_info)
-        # If the view couldn't find a page, then return the original response (don't pollute)
-        except Http404:
-            return response
-        # If anything else goes wrong here, just ignore it and return the original response (again, don't pollute)
-        except:
-            if settings.DEBUG:
-                raise
-            return response

middleware/redirection.py

-from django.conf import settings
-from django.http import HttpResponsePermanentRedirect, HttpResponseRedirect, HttpResponseGone
-from django.template import RequestContext, loader
-from milton.models import Redirect
-
-class RedirectionMiddleware(object):
-    def process_response(self, request, response):
-        # If the response found something, return it.
-        if response.status_code != 404:
-            return response
-        try:
-            # Look for an exact redirect
-            path = request.path
-            paths = [path]
-            
-            # Also try without the trailing slash if someone tacked it on for us
-            if settings.APPEND_SLASH:
-                paths.append(path[:path.rfind('/')] + path[path.rfind('/')+1:])
-            
-            r = Redirect.objects.get(site__id__exact=settings.SITE_ID, original__in=paths)
-            
-            # If the destination is not visible, let the 404 shine.
-            if hasattr(r.target_object, 'visible') and r.target_object.visible == False:
-                return response
-            
-            # If there's a redirect, process it
-            destination = r.destination()
-            
-            # If we're about to tell someone to go where we already are, stop and think...
-            if destination == request.path_info:
-                return response
-            
-            if destination == None:
-                # No destination means it's been removed, so make it a dead end.
-                context = RequestContext(request, {
-                    'title':'410 Gone',
-                    'content':'the resource you seek / has lost its battle with time / seek answers within'
-                })
-                template = loader.get_template("error.html")
-                return HttpResponseGone(template.render(context))
-            
-            if r.permanent == True:
-                # 301 Moved
-                return HttpResponsePermanentRedirect(destination)
-            else:
-                # 302 Found
-                return HttpResponseRedirect(destination)
-        
-        except Redirect.DoesNotExist, e:
-            # Otherwise, return the original response
-            return response
-        except:
-            if settings.DEBUG:
-                raise
-        # If we're here, we didn't catch something -- just pass along the 404.
-        return response
 from django.conf.urls.defaults import *
-from models import Story
 from django.conf import settings
 from django.views.decorators.csrf import csrf_exempt
+
 from milton.xmlrpc import view as xmlrpc_view
 
+
+# Enter the regular expressions once.
+section = r'(?P<section>[^0-9][^/]+)'
+year = r'(?P<year>\d{4})'
+month = r'(?P<month>\d{1,2})'
+day = r'(?P<day>\d{1,2})'
+slug = r'(?P<slug>.+)'
+
 urlpatterns = patterns('',
     # MetaWeblog access point
     url(r'^api/', csrf_exempt(xmlrpc_view), kwargs={'module':'milton.metaweblog'}),
     # Comments
     (r'^comments/', include('django.contrib.comments.urls')),
     
-    # Front page
-    #  Enable this if you want the front page to not be an index of Stories, but a static Page.
-    # (r'^$', 'view_page', {'url':'/'}),
-    
     # Articles
     url(
-        regex  = r'^(?:(?P<section>[^0-9][^/]+)/)?(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>.+)/$',
+        regex  = '^(?:%s/)?%s/%s/%s/%s/$' % (section, year, month, day, slug),
         view   = 'story_detail',
         name   = "story-detail"
     ),
     url(
-        regex  = r'^(?:(?P<section>[^0-9][^/]+)/)?(?:(?P<year>\d{4})/)?(?:(?P<month>\d{1,2})/)?(?:(?P<day>\d{1,2})/)?$',
+        regex  = "^(?:%s/)?(?:%s/)?(?:%s/)?(?:%s/)?$" % (section, year, month, day),
         view   = 'story_archive',
-        kwargs = { "teasers": True },
         name   = "story-archive"
     ),
     
         name   = 'tag',
     )
 )
-
-urlpatterns += patterns('milton.views',
-    (r'^(?P<url>.*)$', 'view_page'),
-)
+from logging import getLogger
+
 from django.core.paginator import Paginator, InvalidPage, EmptyPage
 from django.core.xheaders import populate_xheaders
 from django.http import HttpResponse, HttpResponseRedirect, Http404, ImproperlyConfigured
 from tagging.models import Tag, TaggedItem
 from tagging.utils import get_tag_list
 
+
+logger = getLogger(__name__)
+
 ### Stories ###
 
 def story_detail(request, section=None, year=None, month=None, day=None, slug=None):
     return response
 
 
-def story_archive(request, section=None, year=None, month=None, day=None, teasers=False):
+def story_archive(request, section=None, year=None, month=None, day=None, teasers=None):
+    if teasers == None:
+        teasers = settings.ARCHIVES_SHOW_TEASERS_ONLY
+    
     # If there's a section, try and load it then filter the stories by it
     try:
         if section and len(section):
+            logger.debug("story_archive: fetching the section named %s" % (section,))
             section = Section.objects.get(slug=section)
         else:
             section = None
     except Section.DoesNotExist:
-        section = None
-    
-    if section:
-        stories = Story.published.filter(section=section)
-    else:
-        stories = Story.published.all()
+        raise Http404
     
     # Fetch a list of stories
+    logger.debug("story_archive: fetching the list of stories")
+    stories = Story.published.filter(section=section)
     if year:
         stories = stories.filter(date_published__year=int(year))
         if month:
                 stories = stories.filter(date_published__day=int(day))
     
     # Paginate the results
+    logger.debug("story_archive: paginating the list of stories")
     page = int(request.GET.get('page', 1))        # Requested page number
-    paginator = Paginator(stories.select_related(depth=2), settings.SP_PAGE_SIZE)
+    paginator = Paginator(stories, settings.SP_PAGE_SIZE)
     
     try:
         stories_page = paginator.page(page)
         templates.append("section/" + section.slug + "/" + template_name)
     templates.append(template_name)
     
+    logger.debug("story_archive: generating response")
     return render_to_response(templates, context, context_instance=RequestContext(request))
 
 
         page = Page.published.get(url__exact=url, sites__id__exact=settings.SITE_ID)
     
     except Page.DoesNotExist, e:
-        # If there's no trailing slash, and we're using it, then try that URL next.
-        if settings.APPEND_SLASH and not url.endswith('/'):
-            return HttpResponseRedirect("%s/" % request.path_info)
-        
-        # Otherwise, give up.
-        # print request.path_info, url
         raise Http404
     
     except Page.MultipleObjectsReturned, e: