gallery.py: Factor out page extraction to CGIGalleryServer.page_from_query
authorW. Trevor King <wking@tremily.us>
Mon, 9 Dec 2013 03:49:32 +0000 (19:49 -0800)
committerW. Trevor King <wking@tremily.us>
Mon, 9 Dec 2013 05:07:04 +0000 (21:07 -0800)
This reduces duplicated code.

posts/gallery/gallery.py

index 9a33baf162725ad9362ac85b52f543198fa85f2b..baacbd892b0a8879764a5f74e153b7228cb7414a 100755 (executable)
@@ -51,6 +51,7 @@ import os.path as _os_path
 import random as _random
 import re as _re
 import subprocess as _subprocess
+import urlparse as _urlparse
 import xml.sax.saxutils as _xml_sax_saxutils
 
 
@@ -238,6 +239,25 @@ class CGIGalleryServer (object):
         except ProcessingComplete:
             pass
 
+    def page_from_query(self, query=None, query_string=None):
+        """Extract the requested page from a query string
+
+        This is a helper method for CGIGalleryServer consumers.
+        Specify either query or query_string, but not both.
+        """
+        if query is None:
+            query = _urlparse.parse_qs(query_string)
+        page = 0
+        if 'pp' in query:
+            pp = query['pp']
+            if isinstance(pp, list):
+                pp = pp[0]
+            try:
+                page = int(pp) - 1
+            except ValueError:
+                pass
+        return page
+
     def relative_url(self, url):
         if url is None:
             return url
@@ -683,41 +703,28 @@ def serve_cgi(server):
     import sys
 
     url=None
-    page=0
     cgitb.enable()
     #cgitb.enable(display=0, logdir="/tmp/")
     data = cgi.FieldStorage()
+    page = server.page_from_query(
+        query={key: data[key].getlist() for key in data.keys()})
     if 'p' in data:
         p = data['p']
         if isinstance(p, list):
             p = p[0]
         url = p.value
-    if 'pp' in data:
-        try:
-            page = int(data['pp'].value) - 1
-        except ValueError:
-            pass
     server.serve(url=url, page=page, stream=sys.stdout)
 
 def serve_scgi(server, host='localhost', port=4000):
     import scgi
     import scgi.scgi_server
-    import urlparse
 
     class GalleryHandler(scgi.scgi_server.SCGIHandler):
         def produce(self, env, bodysize, input, output):
             #LOG.info(HTTP_USER_AGENT REQUEST_METHOD REMOTE_ADDR REQUEST_URI
             url = env.get('DOCUMENT_URI', None)
-            page = 0
-            data = urlparse.parse_qs(env.get('QUERY_STRING', ''))
-            if 'pp' in data:
-                pp = data['pp']
-                if isinstance(pp, list):
-                    pp = pp[0]
-                try:
-                    page = int(pp) - 1
-                except ValueError:
-                    pass
+            page = server.page_from_query(
+                query_string=env.get('QUERY_STRING', ''))
             try:
                 try:
                     url = server.relative_url(url=url)