Luke Plant avatar Luke Plant committed f06a8e0

Cleaned up JSON views and added 'separate_presentation' view

Comments (0)

Files changed (2)

semanticeditor/urls.py

 from django.conf.urls.defaults import patterns, url
-from semanticeditor.views import extract_headings_view, retrieve_styles
+from semanticeditor.views import extract_headings_view, retrieve_styles, separate_presentation
 
 urlpatterns = patterns('',
     url(r'extract_headings/', extract_headings_view),
-    url(r'retrieve_styles/', retrieve_styles)
+    url(r'retrieve_styles/', retrieve_styles),
+    url(r'separate_presentation/', separate_presentation),
 )

semanticeditor/views.py

 from django.utils import simplejson
 from django.core.mail import mail_admins
 from django.utils.translation import ugettext as _
-from semanticeditor.utils import extract_headings, InvalidHtml, IncorrectHeadings, NEWROW, NEWCOL, PresentationClass
+from semanticeditor.utils import extract_headings, extract_presentation, AllUserErrors, NEWROW, NEWCOL, PresentationClass
 from semanticeditor.models import CssClass
 import sys
 
     def wrap(request, *a, **kw):
         response = None
         try:
-            response = dict(func(request, *a, **kw))
-            if 'result' not in response:
-                response['result'] = 'ok'
+            response = func(request, *a, **kw)
         except KeyboardInterrupt:
             # Allow keyboard interrupts through for debugging.
             raise
                 msg = e.message
             else:
                 msg = _('Internal error')+': '+str(e)
-            response = {'result': 'error',
-                        'message': msg}
+            response = error(msg)
 
         json = simplejson.dumps(response)
         return HttpResponse(json, mimetype='application/json')
     return wrap
 
-def failure(msg):
+def error(msg):
+    """
+    Standard error result - for internal errors
+    """
     return dict(result='error', message=msg)
 
+def failure(msg):
+    """
+    Standard failure result
+    """
+    return dict(result='usererror', message=msg)
+
 def success(value):
+    """
+    Standard success result
+    """
     return dict(result='ok', value=value)
 
+
+# Anything that depends on values the user may have entered and might
+# contain 'errors' should use this, normally passing in AllUserErrors
+# as 'exceptions'.
+def graceful_errors(exceptions, callback):
+    """
+    Retrieve a value from a callback, handling the exceptions that
+    are passed in, and returning in standard formats
+    """
+    try:
+        val = callback()
+    except exceptions, e:
+        return failure(e.args[0])
+    return success(val)
+
 @json_view
 def extract_headings_view(request):
     data = request.POST.get('html')
     if data is None:
         return failure("No HTML sent for parsing")
 
-    try:
-        headings = extract_headings(data)
-    except (InvalidHtml, IncorrectHeadings), e:
-        return failure(e.args[0])
-
-    return success(headings)
-
+    return graceful_errors(AllUserErrors, lambda: extract_headings(data))
 
 def PI_to_dict(pi):
     """
                                  description=c.description)
                for c in CssClass.objects.all().order_by('verbose_name')]
     return success(map(PI_to_dict,retval))
+
+@json_view
+def separate_presentation(request):
+    """
+    Returns a JSON object:
+     { presentation: <dictionary of presentation info from html>
+       html: <input html stripped of presentation>
+     }
+    """
+    data = request.POST.get('html')
+    if data is None:
+        return failure("No HTML sent for parsing")
+
+    def _ret():
+        pres, html = extract_presentation(data)
+        # Rewrite pres so that we can serialise it
+        pres2 = {}
+        for k, v in pres.items():
+            pres2[k] = list(v)
+        return dict(presentation=pres2,
+                    html=html)
+
+    return graceful_errors(AllUserErrors, _ret)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.