1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/imipweb/env.py Wed Mar 25 17:57:42 2015 +0100
1.3 @@ -0,0 +1,86 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Web interface utilities.
1.8 +
1.9 +Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +import cgi, os, sys
1.26 +
1.27 +getenv = os.environ.get
1.28 +setenv = os.environ.__setitem__
1.29 +
1.30 +class CGIEnvironment:
1.31 +
1.32 + "A CGI-compatible environment."
1.33 +
1.34 + def __init__(self, charset=None):
1.35 + self.charset = charset
1.36 + self.args = None
1.37 + self.method = None
1.38 + self.path = None
1.39 + self.path_info = None
1.40 + self.user = None
1.41 +
1.42 + def get_args(self):
1.43 + if self.args is None:
1.44 + if self.get_method() != "POST":
1.45 + setenv("QUERY_STRING", "")
1.46 + args = cgi.parse(keep_blank_values=True)
1.47 +
1.48 + if not self.charset:
1.49 + self.args = args
1.50 + else:
1.51 + self.args = {}
1.52 + for key, values in args.items():
1.53 + self.args[key] = [unicode(value, self.charset) for value in values]
1.54 +
1.55 + return self.args
1.56 +
1.57 + def get_method(self):
1.58 + if self.method is None:
1.59 + self.method = getenv("REQUEST_METHOD") or "GET"
1.60 + return self.method
1.61 +
1.62 + def get_path(self):
1.63 + if self.path is None:
1.64 + self.path = getenv("SCRIPT_NAME") or ""
1.65 + return self.path
1.66 +
1.67 + def get_path_info(self):
1.68 + if self.path_info is None:
1.69 + self.path_info = getenv("PATH_INFO") or ""
1.70 + return self.path_info
1.71 +
1.72 + def get_user(self):
1.73 + if self.user is None:
1.74 + self.user = getenv("REMOTE_USER") or ""
1.75 + return self.user
1.76 +
1.77 + def get_output(self):
1.78 + return sys.stdout
1.79 +
1.80 + def get_url(self):
1.81 + path = self.get_path()
1.82 + path_info = self.get_path_info()
1.83 + return "%s%s" % (path.rstrip("/"), path_info)
1.84 +
1.85 + def new_url(self, path_info):
1.86 + path = self.get_path()
1.87 + return "%s/%s" % (path.rstrip("/"), path_info.lstrip("/"))
1.88 +
1.89 +# vim: tabstop=4 expandtab shiftwidth=4