📄 cgi.py
字号:
if not line: self.done = -1 break if line[:2] == "--": strippedline = line.strip() if strippedline == next: break if strippedline == last: self.done = 1 break odelim = delim if line[-2:] == "\r\n": delim = "\r\n" line = line[:-2] elif line[-1] == "\n": delim = "\n" line = line[:-1] else: delim = "" self.__write(odelim + line) def skip_lines(self): """Internal: skip lines until outer boundary if defined.""" if not self.outerboundary or self.done: return next = "--" + self.outerboundary last = next + "--" while 1: line = self.fp.readline() if not line: self.done = -1 break if line[:2] == "--": strippedline = line.strip() if strippedline == next: break if strippedline == last: self.done = 1 break def make_file(self, binary=None): """Overridable: return a readable & writable file. The file will be used as follows: - data is written to it - seek(0) - data is read from it The 'binary' argument is unused -- the file is always opened in binary mode. This version opens a temporary file for reading and writing, and immediately deletes (unlinks) it. The trick (on Unix!) is that the file can still be used, but it can't be opened by another process, and it will automatically be deleted when it is closed or when the current process terminates. If you want a more permanent file, you derive a class which overrides this method. If you want a visible temporary file that is nevertheless automatically deleted when the script terminates, try defining a __del__ method in a derived class which unlinks the temporary files you have created. """ import tempfile return tempfile.TemporaryFile("w+b")# Backwards Compatibility Classes# ===============================class FormContentDict(UserDict.UserDict): """Form content as dictionary with a list of values per field. form = FormContentDict() form[key] -> [value, value, ...] form.has_key(key) -> Boolean form.keys() -> [key, key, ...] form.values() -> [[val, val, ...], [val, val, ...], ...] form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...] form.dict == {key: [val, val, ...], ...} """ def __init__(self, environ=os.environ): self.dict = self.data = parse(environ=environ) self.query_string = environ['QUERY_STRING']class SvFormContentDict(FormContentDict): """Form content as dictionary expecting a single value per field. If you only expect a single value for each field, then form[key] will return that single value. It will raise an IndexError if that expectation is not true. If you expect a field to have possible multiple values, than you can use form.getlist(key) to get all of the values. values() and items() are a compromise: they return single strings where there is a single value, and lists of strings otherwise. """ def __getitem__(self, key): if len(self.dict[key]) > 1: raise IndexError, 'expecting a single value' return self.dict[key][0] def getlist(self, key): return self.dict[key] def values(self): result = [] for value in self.dict.values(): if len(value) == 1: result.append(value[0]) else: result.append(value) return result def items(self): result = [] for key, value in self.dict.items(): if len(value) == 1: result.append((key, value[0])) else: result.append((key, value)) return resultclass InterpFormContentDict(SvFormContentDict): """This class is present for backwards compatibility only.""" def __getitem__(self, key): v = SvFormContentDict.__getitem__(self, key) if v[0] in '0123456789+-.': try: return int(v) except ValueError: try: return float(v) except ValueError: pass return v.strip() def values(self): result = [] for key in self.keys(): try: result.append(self[key]) except IndexError: result.append(self.dict[key]) return result def items(self): result = [] for key in self.keys(): try: result.append((key, self[key])) except IndexError: result.append((key, self.dict[key])) return resultclass FormContent(FormContentDict): """This class is present for backwards compatibility only.""" def values(self, key): if self.dict.has_key(key) :return self.dict[key] else: return None def indexed_value(self, key, location): if self.dict.has_key(key): if len(self.dict[key]) > location: return self.dict[key][location] else: return None else: return None def value(self, key): if self.dict.has_key(key): return self.dict[key][0] else: return None def length(self, key): return len(self.dict[key]) def stripped(self, key): if self.dict.has_key(key): return self.dict[key][0].strip() else: return None def pars(self): return self.dict# Test/debug code# ===============def test(environ=os.environ): """Robust test CGI script, usable as main program. Write minimal HTTP headers and dump all information provided to the script in HTML form. """ import traceback print "Content-type: text/html" print sys.stderr = sys.stdout try: form = FieldStorage() # Replace with other classes to test those print_directory() print_arguments() print_form(form) print_environ(environ) print_environ_usage() def f(): exec "testing print_exception() -- <I>italics?</I>" def g(f=f): f() print "<H3>What follows is a test, not an actual exception:</H3>" g() except: print_exception() print "<H1>Second try with a small maxlen...</H1>" global maxlen maxlen = 50 try: form = FieldStorage() # Replace with other classes to test those print_directory() print_arguments() print_form(form) print_environ(environ) except: print_exception()def print_exception(type=None, value=None, tb=None, limit=None): if type is None: type, value, tb = sys.exc_info() import traceback print print "<H3>Traceback (most recent call last):</H3>" list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(type, value) print "<PRE>%s<B>%s</B></PRE>" % ( escape("".join(list[:-1])), escape(list[-1]), ) del tbdef print_environ(environ=os.environ): """Dump the shell environment as HTML.""" keys = environ.keys() keys.sort() print print "<H3>Shell Environment:</H3>" print "<DL>" for key in keys: print "<DT>", escape(key), "<DD>", escape(environ[key]) print "</DL>" printdef print_form(form): """Dump the contents of a form as HTML.""" keys = form.keys() keys.sort() print print "<H3>Form Contents:</H3>" if not keys: print "<P>No form fields." print "<DL>" for key in keys: print "<DT>" + escape(key) + ":", value = form[key] print "<i>" + escape(`type(value)`) + "</i>" print "<DD>" + escape(`value`) print "</DL>" printdef print_directory(): """Dump the current directory as HTML.""" print print "<H3>Current Working Directory:</H3>" try: pwd = os.getcwd() except os.error, msg: print "os.error:", escape(str(msg)) else: print escape(pwd) printdef print_arguments(): print print "<H3>Command Line Arguments:</H3>" print print sys.argv printdef print_environ_usage(): """Dump a list of environment variables used by CGI as HTML.""" print """<H3>These environment variables could have been set:</H3><UL><LI>AUTH_TYPE<LI>CONTENT_LENGTH<LI>CONTENT_TYPE<LI>DATE_GMT<LI>DATE_LOCAL<LI>DOCUMENT_NAME<LI>DOCUMENT_ROOT<LI>DOCUMENT_URI<LI>GATEWAY_INTERFACE<LI>LAST_MODIFIED<LI>PATH<LI>PATH_INFO<LI>PATH_TRANSLATED<LI>QUERY_STRING<LI>REMOTE_ADDR<LI>REMOTE_HOST<LI>REMOTE_IDENT<LI>REMOTE_USER<LI>REQUEST_METHOD<LI>SCRIPT_NAME<LI>SERVER_NAME<LI>SERVER_PORT<LI>SERVER_PROTOCOL<LI>SERVER_ROOT<LI>SERVER_SOFTWARE</UL>In addition, HTTP headers sent by the server may be passed in theenvironment as well. Here are some common variable names:<UL><LI>HTTP_ACCEPT<LI>HTTP_CONNECTION<LI>HTTP_HOST<LI>HTTP_PRAGMA<LI>HTTP_REFERER<LI>HTTP_USER_AGENT</UL>"""# Utilities# =========def escape(s, quote=None): """Replace special characters '&', '<' and '>' by SGML entities.""" s = s.replace("&", "&") # Must be done first! s = s.replace("<", "<") s = s.replace(">", ">") if quote: s = s.replace('"', """) return sdef valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"): import re return re.match(_vb_pattern, s)# Invoke mainline# ===============# Call test() when this file is run as a script (not imported as a module)if __name__ == '__main__': test()
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -