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