1 #!/usr/bin/env python 2 3 """ 4 Web interface utilities. 5 6 Copyright (C) 2014, 2015, 2017 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 import cgi, os, sys, urlparse 23 24 getenv = os.environ.get 25 setenv = os.environ.__setitem__ 26 27 class CGIEnvironment: 28 29 "A CGI-compatible environment." 30 31 def __init__(self, charset=None): 32 self.charset = charset 33 self.args = None 34 self.method = None 35 self.path = None 36 self.path_info = None 37 self.user = None 38 self.query_string = None 39 40 def get_args(self): 41 if self.args is None: 42 if self.get_method() != "POST": 43 if not self.query_string: 44 self.query_string = getenv("QUERY_STRING") 45 setenv("QUERY_STRING", "") 46 args = cgi.parse(keep_blank_values=True) 47 48 if not self.charset: 49 self.args = args 50 else: 51 self.args = {} 52 for key, values in args.items(): 53 self.args[key] = [unicode(value, self.charset) for value in values] 54 55 return self.args 56 57 def get_query(self): 58 if not self.query_string: 59 self.query_string = getenv("QUERY_STRING") 60 return urlparse.parse_qs(self.query_string or "", keep_blank_values=True) 61 62 def get_method(self): 63 if self.method is None: 64 self.method = getenv("REQUEST_METHOD") or "GET" 65 return self.method 66 67 def get_path(self): 68 if self.path is None: 69 self.path = getenv("SCRIPT_NAME") or "" 70 return self.path 71 72 def get_path_info(self): 73 if self.path_info is None: 74 self.path_info = getenv("PATH_INFO") or "" 75 return self.path_info 76 77 def get_user(self): 78 if self.user is None: 79 self.user = getenv("REMOTE_USER") or "" 80 return self.user 81 82 def get_output(self): 83 return sys.stdout 84 85 def get_url(self): 86 path = self.get_path() 87 path_info = self.get_path_info() 88 return "%s%s" % (path.rstrip("/"), path_info) 89 90 def new_url(self, path_info): 91 path = self.get_path() 92 return "%s/%s" % (path.rstrip("/"), path_info.lstrip("/")) 93 94 # vim: tabstop=4 expandtab shiftwidth=4