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 # Retain computed state. 41 42 self.state = {} 43 44 def get_args(self): 45 if self.args is None: 46 if self.get_method() != "POST": 47 if not self.query_string: 48 self.query_string = getenv("QUERY_STRING") 49 setenv("QUERY_STRING", "") 50 args = cgi.parse(keep_blank_values=True) 51 52 if not self.charset: 53 self.args = args 54 else: 55 self.args = {} 56 for key, values in args.items(): 57 self.args[key] = [unicode(value, self.charset) for value in values] 58 59 return self.args 60 61 def get_query(self): 62 if not self.query_string: 63 self.query_string = getenv("QUERY_STRING") 64 return urlparse.parse_qs(self.query_string or "", keep_blank_values=True) 65 66 def get_method(self): 67 if self.method is None: 68 self.method = getenv("REQUEST_METHOD") or "GET" 69 return self.method 70 71 def get_path(self): 72 if self.path is None: 73 self.path = getenv("SCRIPT_NAME") or "" 74 return self.path 75 76 def get_path_info(self): 77 if self.path_info is None: 78 self.path_info = getenv("PATH_INFO") or "" 79 return self.path_info 80 81 def get_user(self): 82 if self.user is None: 83 self.user = getenv("REMOTE_USER") or "" 84 return self.user 85 86 def get_output(self): 87 return sys.stdout 88 89 def get_url(self): 90 path = self.get_path() 91 path_info = self.get_path_info() 92 return "%s%s" % (path.rstrip("/"), path_info) 93 94 def new_url(self, path_info): 95 path = self.get_path() 96 return "%s/%s" % (path.rstrip("/"), path_info.lstrip("/")) 97 98 def get_state(self): 99 return self.state 100 101 # vim: tabstop=4 expandtab shiftwidth=4