From 746e3cd0180152bc3d2b7d9157485a1a8aa57f74 Mon Sep 17 00:00:00 2001 From: "W. Trevor King" Date: Sun, 8 Dec 2013 19:49:32 -0800 Subject: [PATCH] gallery.py: Factor out page extraction to CGIGalleryServer.page_from_query This reduces duplicated code. --- posts/gallery/gallery.py | 41 +++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/posts/gallery/gallery.py b/posts/gallery/gallery.py index 9a33baf..baacbd8 100755 --- a/posts/gallery/gallery.py +++ b/posts/gallery/gallery.py @@ -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) -- 2.26.2