1 #!/usr/bin/env python 2 3 """ 4 Web interface utilities. 5 6 Copyright (C) 2014, 2015 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 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 39 def get_args(self): 40 if self.args is None: 41 if self.get_method() != "POST": 42 setenv("QUERY_STRING", "") 43 args = cgi.parse(keep_blank_values=True) 44 45 if not self.charset: 46 self.args = args 47 else: 48 self.args = {} 49 for key, values in args.items(): 50 self.args[key] = [unicode(value, self.charset) for value in values] 51 52 return self.args 53 54 def get_method(self): 55 if self.method is None: 56 self.method = getenv("REQUEST_METHOD") or "GET" 57 return self.method 58 59 def get_path(self): 60 if self.path is None: 61 self.path = getenv("SCRIPT_NAME") or "" 62 return self.path 63 64 def get_path_info(self): 65 if self.path_info is None: 66 self.path_info = getenv("PATH_INFO") or "" 67 return self.path_info 68 69 def get_user(self): 70 if self.user is None: 71 self.user = getenv("REMOTE_USER") or "" 72 return self.user 73 74 def get_output(self): 75 return sys.stdout 76 77 def get_url(self): 78 path = self.get_path() 79 path_info = self.get_path_info() 80 return "%s%s" % (path.rstrip("/"), path_info) 81 82 def new_url(self, path_info): 83 path = self.get_path() 84 return "%s/%s" % (path.rstrip("/"), path_info.lstrip("/")) 85 86 # vim: tabstop=4 expandtab shiftwidth=4