changeset 2406:31754fe5172b

Make the Wiki class leaner
author Radomir Dopieralski <sheep-devel@sheep.art.pl>
date Sat, 18 May 2013 13:46:04 +0200
parents 552aff3613a8
children a7054f5ff46f
files hatta/page.py hatta/response.py hatta/views.py hatta/wiki.py
diffstat 4 files changed, 108 insertions(+), 136 deletions(-) [+]
line wrap: on
line diff
--- a/hatta/page.py	Sat May 18 13:20:40 2013 +0200
+++ b/hatta/page.py	Sat May 18 13:46:04 2013 +0200
@@ -31,8 +31,55 @@
 except ImportError:
     pass
 
-from hatta import error
-from hatta import parser
+import hatta.error
+import hatta.parser
+
+
+def check_lock(wiki, title):
+    _ = wiki.gettext
+    restricted_pages = [
+        'scripts.js',
+        'robots.txt',
+    ]
+    if wiki.read_only:
+        raise hatta.error.ForbiddenErr(_(u"This site is read-only."))
+    if title in restricted_pages:
+        raise hatta.error.ForbiddenErr(_(u"""Can't edit this page.
+It can only be edited by the site admin directly on the disk."""))
+    if title in wiki.index.page_links(wiki.locked_page):
+        raise hatta.error.ForbiddenErr(_(u"This page is locked."))
+
+
+
+def get_page(request, title):
+    """Creates a page object based on page's mime type"""
+
+    if title:
+        try:
+            page_class, mime = request.wiki.filename_map[title]
+        except KeyError:
+            mime = page_mime(title)
+            major, minor = mime.split('/', 1)
+            try:
+                page_class = request.wiki.mime_map[mime]
+            except KeyError:
+                try:
+                    plus_pos = minor.find('+')
+                    if plus_pos > 0:
+                        minor_base = minor[plus_pos:]
+                    else:
+                        minor_base = ''
+                    base_mime = '/'.join([major, minor_base])
+                    page_class = request.wiki.mime_map[base_mime]
+                except KeyError:
+                    try:
+                        page_class = request.wiki.mime_map[major]
+                    except KeyError:
+                        page_class = request.wiki.mime_map['']
+    else:
+        page_class = WikiPageSpecial
+        mime = ''
+    return page_class(request.wiki, request, title, mime)
 
 
 def page_mime(title):
@@ -121,7 +168,7 @@
             classes = [class_]
         else:
             classes = []
-        if parser.external_link(addr):
+        if hatta.parser.external_link(addr):
             classes.append('external')
             if addr.startswith('mailto:'):
                 # Obfuscate e-mails a little bit.
@@ -164,7 +211,7 @@
         addr = addr.strip()
         html = werkzeug.html
         chunk = ''
-        if parser.external_link(addr):
+        if hatta.parser.external_link(addr):
             return html.img(src=werkzeug.url_fix(addr), class_="external",
                             alt=alt)
         if '#' in addr:
@@ -209,9 +256,9 @@
         edit_url = None
         if self.title:
             try:
-                self.wiki._check_lock(self.title)
+                check_lock(self.wiki, self.title)
                 edit_url = self.get_url(self.title, self.wiki.edit)
-            except error.ForbiddenErr:
+            except hatta.error.ForbiddenErr:
                 pass
         context = {
             'request': self.request,
@@ -244,10 +291,10 @@
         return dependencies
 
     def get_edit_help(self):
-        page = self.wiki.get_page(self.request, self.wiki.help_page)
+        page = get_page(self.request, self.wiki.help_page)
         try:
             return ''.join(page.view_content())
-        except error.NotFoundErr:
+        except hatta.error.NotFoundErr:
             return ''
 
     def render_editor(self, preview=None, captcha_error=None):
@@ -320,10 +367,10 @@
             comment = _(u'modified')
             if old_author == author:
                 comment = old_comment
-        except error.NotFoundErr:
+        except hatta.error.NotFoundErr:
             comment = _(u'created')
             rev = -1
-        except error.ForbiddenErr, e:
+        except hatta.error.ForbiddenErr, e:
             return werkzeug.html.p(werkzeug.html(unicode(e)))
         if preview:
             lines = preview
@@ -450,9 +497,9 @@
     def __init__(self, *args, **kw):
         super(WikiPageWiki, self).__init__(*args, **kw)
         if self.config.get_bool('wiki_words', False):
-            self.parser = parser.WikiWikiParser
+            self.parser = hatta.parser.WikiWikiParser
         else:
-            self.parser = parser.WikiParser
+            self.parser = hatta.parser.WikiParser
         if self.config.get_bool('ignore_indent', False):
             try:
                 del self.parser.block['indent']
@@ -465,7 +512,7 @@
         if text is None:
             try:
                 text = self.storage.page_text(self.title)
-            except error.NotFoundErr:
+            except hatta.error.NotFoundErr:
                 text = u''
         return self.parser.extract_links(text)
 
@@ -515,7 +562,7 @@
 
     def view_content(self, lines=None):
         if self.title not in self.storage:
-            raise error.NotFoundErr()
+            raise hatta.error.NotFoundErr()
         content = ['<p>Download <a href="%s">%s</a> as <i>%s</i>.</p>' %
                    (self.request.get_download_url(self.title),
                     werkzeug.escape(self.title), self.mime)]
@@ -529,7 +576,7 @@
 
     def view_content(self, lines=None):
         if self.title not in self.storage:
-            raise error.NotFoundErr()
+            raise hatta.error.NotFoundErr()
         content = ['<img src="%s" alt="%s">'
                    % (self.request.get_url(self.title, self.wiki.render),
                       werkzeug.escape(self.title))]
@@ -556,7 +603,7 @@
             im.thumbnail((128, 128), Image.ANTIALIAS)
             im.save(cache_file, 'PNG')
         except IOError:
-            raise error.UnsupportedMediaTypeErr('Image corrupted')
+            raise hatta.error.UnsupportedMediaTypeErr('Image corrupted')
         cache_file.close()
         return cache_path
 
@@ -588,7 +635,7 @@
 
     def view_content(self, lines=None):
         if self.title not in self.storage:
-            raise error.NotFoundErr()
+            raise hatta.error.NotFoundErr()
         return self.content_iter(lines)
 
 
--- a/hatta/response.py	Sat May 18 13:20:40 2013 +0200
+++ b/hatta/response.py	Sat May 18 13:46:04 2013 +0200
@@ -3,6 +3,25 @@
 import werkzeug
 
 
+def response(request, title, content, etag='', mime='text/html',
+             rev=None, size=None):
+    """Create a hatta.request.WikiResponse for a page."""
+
+    response = WikiResponse(content, mimetype=mime)
+    if rev is None:
+        rev, date, author, comment = request.wiki.storage.page_meta(title)
+        response.set_etag(u'%s/%s/%d-%s' % (etag,
+                                            werkzeug.url_quote(title),
+                                            rev, date.isoformat()))
+    else:
+        response.set_etag(u'%s/%s/%s' % (etag, werkzeug.url_quote(title),
+                                         rev))
+    if size:
+        response.content_length = size
+    response.make_conditional(request)
+    return response
+
+
 class WikiResponse(werkzeug.BaseResponse, werkzeug.ETagResponseMixin,
                    werkzeug.CommonResponseDescriptorsMixin):
     """A typical HTTP response class made out of Werkzeug's mixins."""
--- a/hatta/views.py	Sat May 18 13:20:40 2013 +0200
+++ b/hatta/views.py	Sat May 18 13:46:04 2013 +0200
@@ -72,20 +72,6 @@
     return response
 
 
-def _check_lock(wiki, title):
-    _ = wiki.gettext
-    restricted_pages = [
-        'scripts.js',
-        'robots.txt',
-    ]
-    if wiki.read_only:
-        raise hatta.error.ForbiddenErr(_(u"This site is read-only."))
-    if title in restricted_pages:
-        raise hatta.error.ForbiddenErr(_(u"""Can't edit this page.
-It can only be edited by the site admin directly on the disk."""))
-    if title in wiki.index.page_links(wiki.locked_page):
-        raise hatta.error.ForbiddenErr(_(u"This page is locked."))
-
 
 @URL('/<title:title>')
 @URL('/')
@@ -93,7 +79,7 @@
     _ = request.wiki.gettext
     if title is None:
         title = request.wiki.front_page
-    page = request.wiki.get_page(request, title)
+    page = hatta.page.get_page(request, title)
     try:
         content = page.view_content()
     except hatta.error.NotFoundErr:
@@ -105,7 +91,7 @@
     html = page.template("page.html", content=content)
     dependencies = page.dependencies()
     etag = '/(%s)' % u','.join(dependencies)
-    return request.wiki.response(request, title, html, etag=etag)
+    return hatta.response.response(request, title, html, etag=etag)
 
 @URL('/+history/<title:title>/<int:rev>')
 def revision(request, title, rev):
@@ -121,10 +107,10 @@
         werkzeug.html.pre(werkzeug.html(text)),
     ]
     special_title = _(u'Revision of "%(title)s"') % {'title': title}
-    page = request.wiki.get_page(request, title)
+    page = hatta.page.get_page(request, title)
     html = page.template('page_special.html', content=content,
                          special_title=special_title)
-    response = request.wiki.response(request, title, html, rev=rev, etag='/old')
+    response = hatta.response.response(request, title, html, rev=rev, etag='/old')
     return response
 
 @URL('/+version/')
@@ -142,7 +128,7 @@
 @URL('/+edit/<title:title>', methods=['POST'])
 def save(request, title):
     _ = request.wiki.gettext
-    _check_lock(request.wiki, title)
+    hatta.page.check_lock(request.wiki, title)
     url = request.get_url(title)
     if request.form.get('cancel'):
         if title not in request.wiki.storage:
@@ -174,7 +160,7 @@
             parent = None
         request.wiki.storage.reopen()
         request.wiki.index.update(request.wiki)
-        page = request.wiki.get_page(request, title)
+        page = hatta.page.get_page(request, title)
         if text is not None:
             if title == request.wiki.locked_page:
                 for link, label in page.extract_links(text):
@@ -208,11 +194,11 @@
 
 @URL('/+edit/<title:title>', methods=['GET'])
 def edit(request, title, preview=None, captcha_error=None):
-    _check_lock(request.wiki, title)
+    hatta.page.check_lock(request.wiki, title)
     exists = title in request.wiki.storage
     if exists:
         request.wiki.storage.reopen()
-    page = request.wiki.get_page(request, title)
+    page = hatta.page.get_page(request, title)
     html = page.render_editor(preview, captcha_error)
     if not exists:
         response = hatta.response.WikiResponse(html, mimetype="text/html",
@@ -221,7 +207,7 @@
     elif preview:
         response = hatta.response.WikiResponse(html, mimetype="text/html")
     else:
-        response = request.wiki.response(request, title, html, '/edit')
+        response = hatta.response.response(request, title, html, '/edit')
     response.headers.add('Cache-Control', 'no-cache')
     return response
 
@@ -254,7 +240,7 @@
         feed.add(title, comment, content_type="text", author=author,
                  url=url, updated=date)
     rev = request.wiki.storage.repo_revision()
-    response = request.wiki.response(request, 'atom', feed.generate(), '/+feed',
+    response = hatta.response.response(request, 'atom', feed.generate(), '/+feed',
                              'application/xml', rev)
     response.make_conditional(request)
     return response
@@ -267,7 +253,7 @@
     if mime == 'text/x-wiki':
         mime = 'text/plain'
     data = request.wiki.storage.page_data(title)
-    response = request.wiki.response(request, title, data,
+    response = hatta.response.response(request, title, data,
                              '/download', mime, size=-1)
     response.direct_passthrough = True
     return response
@@ -306,7 +292,7 @@
         except OSError:
             pass
 
-    page = request.wiki.get_page(request, title)
+    page = hatta.page.get_page(request, title)
     try:
         cache_filename, cache_mime = page.render_mime()
         render = page.render_cache
@@ -332,7 +318,7 @@
     except AttributeError:
         wrap_file = lambda x, y: y
     f = wrap_file(request.environ, open(cache_file))
-    response = request.wiki.response(request, title, f, '/render', cache_mime,
+    response = hatta.response.response(request, title, f, '/render', cache_mime,
                              size=cache_size)
     response.direct_passthrough = True
     return response
@@ -342,7 +328,7 @@
     """Revert a change to a page."""
 
     _ = request.wiki.gettext
-    _check_lock(request.wiki, title)
+    hatta.page.check_lock(request.wiki, title)
     rev = None
     for key in request.form:
         try:
@@ -366,7 +352,7 @@
                 'rev': rev, 'title': title}
             data = request.wiki.storage.page_revision(title, rev - 1)
             request.wiki.storage.save_data(title, data, author, comment, parent)
-        page = request.wiki.get_page(request, title)
+        page = hatta.page.get_page(request, title)
         request.wiki.index.update_page(page, title, data=data)
     url = request.adapter.build(request.wiki.history, {'title': title},
                                 method='GET', force_external=True)
@@ -378,7 +364,7 @@
 
     max_rev = -1
     history = []
-    page = request.wiki.get_page(request, title)
+    page = hatta.page.get_page(request, title)
     for rev, date, author, comment in request.wiki.storage.page_history(title):
         if max_rev < rev:
             max_rev = rev
@@ -391,7 +377,7 @@
         history.append((date, date_url, rev, author, comment))
     html = page.template('history.html', history=history,
                          date_html=hatta.page.date_html, parent=max_rev)
-    response = request.wiki.response(request, title, html, '/history')
+    response = hatta.response.response(request, title, html, '/history')
     return response
 
 @URL('/+history/')
@@ -425,7 +411,7 @@
 
             yield date, date_url, title, author, comment
 
-    page = request.wiki.get_page(request, '')
+    page = hatta.page.get_page(request, '')
     html = page.template('changes.html', changes=_changes_list(),
                          date_html=hatta.page.date_html)
     response = hatta.response.WikiResponse(html, mimetype='text/html')
@@ -438,7 +424,7 @@
     """Show the differences between specified revisions."""
 
     _ = request.wiki.gettext
-    page = request.wiki.get_page(request, title)
+    page = hatta.page.get_page(request, title)
     build = request.adapter.build
     from_url = build(request.wiki.revision, {'title': title, 'rev': from_rev})
     to_url = build(request.wiki.revision, {'title': title, 'rev': to_rev})
@@ -470,7 +456,7 @@
     """Show index of all pages in the request.wiki."""
 
     _ = request.wiki.gettext
-    page = request.wiki.get_page(request, '')
+    page = hatta.page.get_page(request, '')
     html = page.template('list.html',
                          pages=sorted(request.wiki.storage.all_pages()),
                          class_='index',
@@ -500,7 +486,7 @@
     """Show all pages that don't have backlinks."""
 
     _ = request.wiki.gettext
-    page = request.wiki.get_page(request, '')
+    page = hatta.page.get_page(request, '')
     orphaned = [
         title
         for title in request.wiki.index.orphaned_pages()
@@ -526,7 +512,7 @@
                     or title.startswith(':')):
                 yield refs, title
 
-    page = request.wiki.get_page(request, '')
+    page = hatta.page.get_page(request, '')
     html = page.template('wanted.html', pages=_wanted_pages_list())
     response = hatta.response.WikiResponse(html, mimetype='text/html')
     response.set_etag('/+wanted/%d' % request.wiki.storage.repo_revision())
@@ -577,7 +563,7 @@
         yield u'</ol>'
 
     query = request.values.get('q', u'').strip()
-    page = request.wiki.get_page(request, '')
+    page = hatta.page.get_page(request, '')
     if not query:
         url = request.get_url(view=request.wiki.all_pages, external=True)
         return werkzeug.routing.redirect(url, code=303)
@@ -595,8 +581,8 @@
     """Serve the page with backlinks."""
 
     request.wiki.storage.reopen()
-    request.wiki.index.update(wiki)
-    page = request.wiki.get_page(request, title)
+    request.wiki.index.update(request.wiki)
+    page = hatta.page.get_page(request, title)
     html = page.template('backlinks.html',
                          pages=request.wiki.index.page_backlinks(title))
     response = hatta.response.WikiResponse(html, mimetype='text/html')
--- a/hatta/wiki.py	Sat May 18 13:20:40 2013 +0200
+++ b/hatta/wiki.py	Sat May 18 13:46:04 2013 +0200
@@ -3,7 +3,6 @@
 
 import gettext
 import os
-import pkgutil
 import sys
 
 import werkzeug
@@ -120,85 +119,6 @@
             'all': WikiAllConverter,
         })
 
-    def get_page(self, request, title):
-        """Creates a page object based on page's mime type"""
-
-        if title:
-            try:
-                page_class, mime = self.filename_map[title]
-            except KeyError:
-                mime = hatta.page.page_mime(title)
-                major, minor = mime.split('/', 1)
-                try:
-                    page_class = self.mime_map[mime]
-                except KeyError:
-                    try:
-                        plus_pos = minor.find('+')
-                        if plus_pos > 0:
-                            minor_base = minor[plus_pos:]
-                        else:
-                            minor_base = ''
-                        base_mime = '/'.join([major, minor_base])
-                        page_class = self.mime_map[base_mime]
-                    except KeyError:
-                        try:
-                            page_class = self.mime_map[major]
-                        except KeyError:
-                            page_class = self.mime_map['']
-        else:
-            page_class = hatta.page.WikiPageSpecial
-            mime = ''
-        return page_class(self, request, title, mime)
-
-    def response(self, request, title, content, etag='', mime='text/html',
-                 rev=None, size=None):
-        """Create a hatta.request.WikiResponse for a page."""
-
-        response = hatta.response.WikiResponse(content, mimetype=mime)
-        if rev is None:
-            rev, date, author, comment = self.storage.page_meta(title)
-            response.set_etag(u'%s/%s/%d-%s' % (etag,
-                                                werkzeug.url_quote(title),
-                                                rev, date.isoformat()))
-        else:
-            response.set_etag(u'%s/%s/%s' % (etag, werkzeug.url_quote(title),
-                                             rev))
-        if size:
-            response.content_length = size
-        response.make_conditional(request)
-        return response
-
-    def _check_lock(self, title):
-        _ = self.gettext
-        restricted_pages = [
-            'scripts.js',
-            'robots.txt',
-        ]
-        if self.read_only:
-            raise hatta.error.ForbiddenErr(_(u"This site is read-only."))
-        if title in restricted_pages:
-            raise hatta.error.ForbiddenErr(_(u"""Can't edit this page.
-It can only be edited by the site admin directly on the disk."""))
-        if title in self.index.page_links(self.locked_page):
-            raise hatta.error.ForbiddenErr(_(u"This page is locked."))
-
-    def _serve_default(self, request, title, content=None, mime=None):
-        """Some pages have their default content."""
-
-        if title in self.storage:
-            return self.download(request, title)
-        if content is None:
-            content = pkgutil.get_data('hatta', os.path.join('static', title))
-        mime = mime or 'application/octet-stream'
-        response = hatta.response.WikiResponse(
-            content,
-            mimetype=mime,
-        )
-        response.set_etag('/%s/-1' % title)
-        response.make_conditional(request)
-        return response
-
-
     @werkzeug.responder
     def application(self, environ, start):
         """The main application loop."""