PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/cgi.py

https://bitbucket.org/glix/python
Python | 1051 lines | 1007 code | 14 blank | 30 comment | 12 complexity | 4c75c28d93f89168aeb2a26182ff71e2 MD5 | raw file
  1. #! /usr/local/bin/python
  2. # NOTE: the above "/usr/local/bin/python" is NOT a mistake. It is
  3. # intentionally NOT "/usr/bin/env python". On many systems
  4. # (e.g. Solaris), /usr/local/bin is not in $PATH as passed to CGI
  5. # scripts, and /usr/local/bin is the default directory where Python is
  6. # installed, so /usr/bin/env would be unable to find python. Granted,
  7. # binary installations by Linux vendors often install Python in
  8. # /usr/bin. So let those vendors patch cgi.py to match their choice
  9. # of installation.
  10. """Support module for CGI (Common Gateway Interface) scripts.
  11. This module defines a number of utilities for use by CGI scripts
  12. written in Python.
  13. """
  14. # XXX Perhaps there should be a slimmed version that doesn't contain
  15. # all those backwards compatible and debugging classes and functions?
  16. # History
  17. # -------
  18. #
  19. # Michael McLay started this module. Steve Majewski changed the
  20. # interface to SvFormContentDict and FormContentDict. The multipart
  21. # parsing was inspired by code submitted by Andreas Paepcke. Guido van
  22. # Rossum rewrote, reformatted and documented the module and is currently
  23. # responsible for its maintenance.
  24. #
  25. __version__ = "2.6"
  26. # Imports
  27. # =======
  28. from operator import attrgetter
  29. import sys
  30. import os
  31. import urllib
  32. import UserDict
  33. import urlparse
  34. from warnings import filterwarnings, catch_warnings, warn
  35. with catch_warnings():
  36. if sys.py3kwarning:
  37. filterwarnings("ignore", ".*mimetools has been removed",
  38. DeprecationWarning)
  39. import mimetools
  40. if sys.py3kwarning:
  41. filterwarnings("ignore", ".*rfc822 has been removed", DeprecationWarning)
  42. import rfc822
  43. try:
  44. from cStringIO import StringIO
  45. except ImportError:
  46. from StringIO import StringIO
  47. __all__ = ["MiniFieldStorage", "FieldStorage", "FormContentDict",
  48. "SvFormContentDict", "InterpFormContentDict", "FormContent",
  49. "parse", "parse_qs", "parse_qsl", "parse_multipart",
  50. "parse_header", "print_exception", "print_environ",
  51. "print_form", "print_directory", "print_arguments",
  52. "print_environ_usage", "escape"]
  53. # Logging support
  54. # ===============
  55. logfile = "" # Filename to log to, if not empty
  56. logfp = None # File object to log to, if not None
  57. def initlog(*allargs):
  58. """Write a log message, if there is a log file.
  59. Even though this function is called initlog(), you should always
  60. use log(); log is a variable that is set either to initlog
  61. (initially), to dolog (once the log file has been opened), or to
  62. nolog (when logging is disabled).
  63. The first argument is a format string; the remaining arguments (if
  64. any) are arguments to the % operator, so e.g.
  65. log("%s: %s", "a", "b")
  66. will write "a: b" to the log file, followed by a newline.
  67. If the global logfp is not None, it should be a file object to
  68. which log data is written.
  69. If the global logfp is None, the global logfile may be a string
  70. giving a filename to open, in append mode. This file should be
  71. world writable!!! If the file can't be opened, logging is
  72. silently disabled (since there is no safe place where we could
  73. send an error message).
  74. """
  75. global logfp, log
  76. if logfile and not logfp:
  77. try:
  78. logfp = open(logfile, "a")
  79. except IOError:
  80. pass
  81. if not logfp:
  82. log = nolog
  83. else:
  84. log = dolog
  85. log(*allargs)
  86. def dolog(fmt, *args):
  87. """Write a log message to the log file. See initlog() for docs."""
  88. logfp.write(fmt%args + "\n")
  89. def nolog(*allargs):
  90. """Dummy function, assigned to log when logging is disabled."""
  91. pass
  92. log = initlog # The current logging function
  93. # Parsing functions
  94. # =================
  95. # Maximum input we will accept when REQUEST_METHOD is POST
  96. # 0 ==> unlimited input
  97. maxlen = 0
  98. def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0):
  99. """Parse a query in the environment or from a file (default stdin)
  100. Arguments, all optional:
  101. fp : file pointer; default: sys.stdin
  102. environ : environment dictionary; default: os.environ
  103. keep_blank_values: flag indicating whether blank values in
  104. URL encoded forms should be treated as blank strings.
  105. A true value indicates that blanks should be retained as
  106. blank strings. The default false value indicates that
  107. blank values are to be ignored and treated as if they were
  108. not included.
  109. strict_parsing: flag indicating what to do with parsing errors.
  110. If false (the default), errors are silently ignored.
  111. If true, errors raise a ValueError exception.
  112. """
  113. if fp is None:
  114. fp = sys.stdin
  115. if not 'REQUEST_METHOD' in environ:
  116. environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone
  117. if environ['REQUEST_METHOD'] == 'POST':
  118. ctype, pdict = parse_header(environ['CONTENT_TYPE'])
  119. if ctype == 'multipart/form-data':
  120. return parse_multipart(fp, pdict)
  121. elif ctype == 'application/x-www-form-urlencoded':
  122. clength = int(environ['CONTENT_LENGTH'])
  123. if maxlen and clength > maxlen:
  124. raise ValueError, 'Maximum content length exceeded'
  125. qs = fp.read(clength)
  126. else:
  127. qs = '' # Unknown content-type
  128. if 'QUERY_STRING' in environ:
  129. if qs: qs = qs + '&'
  130. qs = qs + environ['QUERY_STRING']
  131. elif sys.argv[1:]:
  132. if qs: qs = qs + '&'
  133. qs = qs + sys.argv[1]
  134. environ['QUERY_STRING'] = qs # XXX Shouldn't, really
  135. elif 'QUERY_STRING' in environ:
  136. qs = environ['QUERY_STRING']
  137. else:
  138. if sys.argv[1:]:
  139. qs = sys.argv[1]
  140. else:
  141. qs = ""
  142. environ['QUERY_STRING'] = qs # XXX Shouldn't, really
  143. return parse_qs(qs, keep_blank_values, strict_parsing)
  144. # parse query string function called from urlparse,
  145. # this is done in order to maintain backward compatiblity.
  146. def parse_qs(qs, keep_blank_values=0, strict_parsing=0):
  147. """Parse a query given as a string argument."""
  148. warn("cgi.parse_qs is deprecated, use urlparse.parse_qs \
  149. instead",PendingDeprecationWarning)
  150. return urlparse.parse_qs(qs, keep_blank_values, strict_parsing)
  151. def parse_qsl(qs, keep_blank_values=0, strict_parsing=0):
  152. """Parse a query given as a string argument."""
  153. warn("cgi.parse_qsl is deprecated, use urlparse.parse_qsl instead",
  154. PendingDeprecationWarning)
  155. return urlparse.parse_qsl(qs, keep_blank_values, strict_parsing)
  156. def parse_multipart(fp, pdict):
  157. """Parse multipart input.
  158. Arguments:
  159. fp : input file
  160. pdict: dictionary containing other parameters of content-type header
  161. Returns a dictionary just like parse_qs(): keys are the field names, each
  162. value is a list of values for that field. This is easy to use but not
  163. much good if you are expecting megabytes to be uploaded -- in that case,
  164. use the FieldStorage class instead which is much more flexible. Note
  165. that content-type is the raw, unparsed contents of the content-type
  166. header.
  167. XXX This does not parse nested multipart parts -- use FieldStorage for
  168. that.
  169. XXX This should really be subsumed by FieldStorage altogether -- no
  170. point in having two implementations of the same parsing algorithm.
  171. Also, FieldStorage protects itself better against certain DoS attacks
  172. by limiting the size of the data read in one chunk. The API here
  173. does not support that kind of protection. This also affects parse()
  174. since it can call parse_multipart().
  175. """
  176. boundary = ""
  177. if 'boundary' in pdict:
  178. boundary = pdict['boundary']
  179. if not valid_boundary(boundary):
  180. raise ValueError, ('Invalid boundary in multipart form: %r'
  181. % (boundary,))
  182. nextpart = "--" + boundary
  183. lastpart = "--" + boundary + "--"
  184. partdict = {}
  185. terminator = ""
  186. while terminator != lastpart:
  187. bytes = -1
  188. data = None
  189. if terminator:
  190. # At start of next part. Read headers first.
  191. headers = mimetools.Message(fp)
  192. clength = headers.getheader('content-length')
  193. if clength:
  194. try:
  195. bytes = int(clength)
  196. except ValueError:
  197. pass
  198. if bytes > 0:
  199. if maxlen and bytes > maxlen:
  200. raise ValueError, 'Maximum content length exceeded'
  201. data = fp.read(bytes)
  202. else:
  203. data = ""
  204. # Read lines until end of part.
  205. lines = []
  206. while 1:
  207. line = fp.readline()
  208. if not line:
  209. terminator = lastpart # End outer loop
  210. break
  211. if line[:2] == "--":
  212. terminator = line.strip()
  213. if terminator in (nextpart, lastpart):
  214. break
  215. lines.append(line)
  216. # Done with part.
  217. if data is None:
  218. continue
  219. if bytes < 0:
  220. if lines:
  221. # Strip final line terminator
  222. line = lines[-1]
  223. if line[-2:] == "\r\n":
  224. line = line[:-2]
  225. elif line[-1:] == "\n":
  226. line = line[:-1]
  227. lines[-1] = line
  228. data = "".join(lines)
  229. line = headers['content-disposition']
  230. if not line:
  231. continue
  232. key, params = parse_header(line)
  233. if key != 'form-data':
  234. continue
  235. if 'name' in params:
  236. name = params['name']
  237. else:
  238. continue
  239. if name in partdict:
  240. partdict[name].append(data)
  241. else:
  242. partdict[name] = [data]
  243. return partdict
  244. def _parseparam(s):
  245. while s[:1] == ';':
  246. s = s[1:]
  247. end = s.find(';')
  248. while end > 0 and s.count('"', 0, end) % 2:
  249. end = s.find(';', end + 1)
  250. if end < 0:
  251. end = len(s)
  252. f = s[:end]
  253. yield f.strip()
  254. s = s[end:]
  255. def parse_header(line):
  256. """Parse a Content-type like header.
  257. Return the main content-type and a dictionary of options.
  258. """
  259. parts = _parseparam(';' + line)
  260. key = parts.next()
  261. pdict = {}
  262. for p in parts:
  263. i = p.find('=')
  264. if i >= 0:
  265. name = p[:i].strip().lower()
  266. value = p[i+1:].strip()
  267. if len(value) >= 2 and value[0] == value[-1] == '"':
  268. value = value[1:-1]
  269. value = value.replace('\\\\', '\\').replace('\\"', '"')
  270. pdict[name] = value
  271. return key, pdict
  272. # Classes for field storage
  273. # =========================
  274. class MiniFieldStorage:
  275. """Like FieldStorage, for use when no file uploads are possible."""
  276. # Dummy attributes
  277. filename = None
  278. list = None
  279. type = None
  280. file = None
  281. type_options = {}
  282. disposition = None
  283. disposition_options = {}
  284. headers = {}
  285. def __init__(self, name, value):
  286. """Constructor from field name and value."""
  287. self.name = name
  288. self.value = value
  289. # self.file = StringIO(value)
  290. def __repr__(self):
  291. """Return printable representation."""
  292. return "MiniFieldStorage(%r, %r)" % (self.name, self.value)
  293. class FieldStorage:
  294. """Store a sequence of fields, reading multipart/form-data.
  295. This class provides naming, typing, files stored on disk, and
  296. more. At the top level, it is accessible like a dictionary, whose
  297. keys are the field names. (Note: None can occur as a field name.)
  298. The items are either a Python list (if there's multiple values) or
  299. another FieldStorage or MiniFieldStorage object. If it's a single
  300. object, it has the following attributes:
  301. name: the field name, if specified; otherwise None
  302. filename: the filename, if specified; otherwise None; this is the
  303. client side filename, *not* the file name on which it is
  304. stored (that's a temporary file you don't deal with)
  305. value: the value as a *string*; for file uploads, this
  306. transparently reads the file every time you request the value
  307. file: the file(-like) object from which you can read the data;
  308. None if the data is stored a simple string
  309. type: the content-type, or None if not specified
  310. type_options: dictionary of options specified on the content-type
  311. line
  312. disposition: content-disposition, or None if not specified
  313. disposition_options: dictionary of corresponding options
  314. headers: a dictionary(-like) object (sometimes rfc822.Message or a
  315. subclass thereof) containing *all* headers
  316. The class is subclassable, mostly for the purpose of overriding
  317. the make_file() method, which is called internally to come up with
  318. a file open for reading and writing. This makes it possible to
  319. override the default choice of storing all files in a temporary
  320. directory and unlinking them as soon as they have been opened.
  321. """
  322. def __init__(self, fp=None, headers=None, outerboundary="",
  323. environ=os.environ, keep_blank_values=0, strict_parsing=0):
  324. """Constructor. Read multipart/* until last part.
  325. Arguments, all optional:
  326. fp : file pointer; default: sys.stdin
  327. (not used when the request method is GET)
  328. headers : header dictionary-like object; default:
  329. taken from environ as per CGI spec
  330. outerboundary : terminating multipart boundary
  331. (for internal use only)
  332. environ : environment dictionary; default: os.environ
  333. keep_blank_values: flag indicating whether blank values in
  334. URL encoded forms should be treated as blank strings.
  335. A true value indicates that blanks should be retained as
  336. blank strings. The default false value indicates that
  337. blank values are to be ignored and treated as if they were
  338. not included.
  339. strict_parsing: flag indicating what to do with parsing errors.
  340. If false (the default), errors are silently ignored.
  341. If true, errors raise a ValueError exception.
  342. """
  343. method = 'GET'
  344. self.keep_blank_values = keep_blank_values
  345. self.strict_parsing = strict_parsing
  346. if 'REQUEST_METHOD' in environ:
  347. method = environ['REQUEST_METHOD'].upper()
  348. self.qs_on_post = None
  349. if method == 'GET' or method == 'HEAD':
  350. if 'QUERY_STRING' in environ:
  351. qs = environ['QUERY_STRING']
  352. elif sys.argv[1:]:
  353. qs = sys.argv[1]
  354. else:
  355. qs = ""
  356. fp = StringIO(qs)
  357. if headers is None:
  358. headers = {'content-type':
  359. "application/x-www-form-urlencoded"}
  360. if headers is None:
  361. headers = {}
  362. if method == 'POST':
  363. # Set default content-type for POST to what's traditional
  364. headers['content-type'] = "application/x-www-form-urlencoded"
  365. if 'CONTENT_TYPE' in environ:
  366. headers['content-type'] = environ['CONTENT_TYPE']
  367. if 'QUERY_STRING' in environ:
  368. self.qs_on_post = environ['QUERY_STRING']
  369. if 'CONTENT_LENGTH' in environ:
  370. headers['content-length'] = environ['CONTENT_LENGTH']
  371. self.fp = fp or sys.stdin
  372. self.headers = headers
  373. self.outerboundary = outerboundary
  374. # Process content-disposition header
  375. cdisp, pdict = "", {}
  376. if 'content-disposition' in self.headers:
  377. cdisp, pdict = parse_header(self.headers['content-disposition'])
  378. self.disposition = cdisp
  379. self.disposition_options = pdict
  380. self.name = None
  381. if 'name' in pdict:
  382. self.name = pdict['name']
  383. self.filename = None
  384. if 'filename' in pdict:
  385. self.filename = pdict['filename']
  386. # Process content-type header
  387. #
  388. # Honor any existing content-type header. But if there is no
  389. # content-type header, use some sensible defaults. Assume
  390. # outerboundary is "" at the outer level, but something non-false
  391. # inside a multi-part. The default for an inner part is text/plain,
  392. # but for an outer part it should be urlencoded. This should catch
  393. # bogus clients which erroneously forget to include a content-type
  394. # header.
  395. #
  396. # See below for what we do if there does exist a content-type header,
  397. # but it happens to be something we don't understand.
  398. if 'content-type' in self.headers:
  399. ctype, pdict = parse_header(self.headers['content-type'])
  400. elif self.outerboundary or method != 'POST':
  401. ctype, pdict = "text/plain", {}
  402. else:
  403. ctype, pdict = 'application/x-www-form-urlencoded', {}
  404. self.type = ctype
  405. self.type_options = pdict
  406. self.innerboundary = ""
  407. if 'boundary' in pdict:
  408. self.innerboundary = pdict['boundary']
  409. clen = -1
  410. if 'content-length' in self.headers:
  411. try:
  412. clen = int(self.headers['content-length'])
  413. except ValueError:
  414. pass
  415. if maxlen and clen > maxlen:
  416. raise ValueError, 'Maximum content length exceeded'
  417. self.length = clen
  418. self.list = self.file = None
  419. self.done = 0
  420. if ctype == 'application/x-www-form-urlencoded':
  421. self.read_urlencoded()
  422. elif ctype[:10] == 'multipart/':
  423. self.read_multi(environ, keep_blank_values, strict_parsing)
  424. else:
  425. self.read_single()
  426. def __repr__(self):
  427. """Return a printable representation."""
  428. return "FieldStorage(%r, %r, %r)" % (
  429. self.name, self.filename, self.value)
  430. def __iter__(self):
  431. return iter(self.keys())
  432. def __getattr__(self, name):
  433. if name != 'value':
  434. raise AttributeError, name
  435. if self.file:
  436. self.file.seek(0)
  437. value = self.file.read()
  438. self.file.seek(0)
  439. elif self.list is not None:
  440. value = self.list
  441. else:
  442. value = None
  443. return value
  444. def __getitem__(self, key):
  445. """Dictionary style indexing."""
  446. if self.list is None:
  447. raise TypeError, "not indexable"
  448. found = []
  449. for item in self.list:
  450. if item.name == key: found.append(item)
  451. if not found:
  452. raise KeyError, key
  453. if len(found) == 1:
  454. return found[0]
  455. else:
  456. return found
  457. def getvalue(self, key, default=None):
  458. """Dictionary style get() method, including 'value' lookup."""
  459. if key in self:
  460. value = self[key]
  461. if type(value) is type([]):
  462. return map(attrgetter('value'), value)
  463. else:
  464. return value.value
  465. else:
  466. return default
  467. def getfirst(self, key, default=None):
  468. """ Return the first value received."""
  469. if key in self:
  470. value = self[key]
  471. if type(value) is type([]):
  472. return value[0].value
  473. else:
  474. return value.value
  475. else:
  476. return default
  477. def getlist(self, key):
  478. """ Return list of received values."""
  479. if key in self:
  480. value = self[key]
  481. if type(value) is type([]):
  482. return map(attrgetter('value'), value)
  483. else:
  484. return [value.value]
  485. else:
  486. return []
  487. def keys(self):
  488. """Dictionary style keys() method."""
  489. if self.list is None:
  490. raise TypeError, "not indexable"
  491. return list(set(item.name for item in self.list))
  492. def has_key(self, key):
  493. """Dictionary style has_key() method."""
  494. if self.list is None:
  495. raise TypeError, "not indexable"
  496. return any(item.name == key for item in self.list)
  497. def __contains__(self, key):
  498. """Dictionary style __contains__ method."""
  499. if self.list is None:
  500. raise TypeError, "not indexable"
  501. return any(item.name == key for item in self.list)
  502. def __len__(self):
  503. """Dictionary style len(x) support."""
  504. return len(self.keys())
  505. def __nonzero__(self):
  506. return bool(self.list)
  507. def read_urlencoded(self):
  508. """Internal: read data in query string format."""
  509. qs = self.fp.read(self.length)
  510. if self.qs_on_post:
  511. qs += '&' + self.qs_on_post
  512. self.list = list = []
  513. for key, value in urlparse.parse_qsl(qs, self.keep_blank_values,
  514. self.strict_parsing):
  515. list.append(MiniFieldStorage(key, value))
  516. self.skip_lines()
  517. FieldStorageClass = None
  518. def read_multi(self, environ, keep_blank_values, strict_parsing):
  519. """Internal: read a part that is itself multipart."""
  520. ib = self.innerboundary
  521. if not valid_boundary(ib):
  522. raise ValueError, 'Invalid boundary in multipart form: %r' % (ib,)
  523. self.list = []
  524. if self.qs_on_post:
  525. for key, value in urlparse.parse_qsl(self.qs_on_post,
  526. self.keep_blank_values, self.strict_parsing):
  527. self.list.append(MiniFieldStorage(key, value))
  528. FieldStorageClass = None
  529. klass = self.FieldStorageClass or self.__class__
  530. part = klass(self.fp, {}, ib,
  531. environ, keep_blank_values, strict_parsing)
  532. # Throw first part away
  533. while not part.done:
  534. headers = rfc822.Message(self.fp)
  535. part = klass(self.fp, headers, ib,
  536. environ, keep_blank_values, strict_parsing)
  537. self.list.append(part)
  538. self.skip_lines()
  539. def read_single(self):
  540. """Internal: read an atomic part."""
  541. if self.length >= 0:
  542. self.read_binary()
  543. self.skip_lines()
  544. else:
  545. self.read_lines()
  546. self.file.seek(0)
  547. bufsize = 8*1024 # I/O buffering size for copy to file
  548. def read_binary(self):
  549. """Internal: read binary data."""
  550. self.file = self.make_file('b')
  551. todo = self.length
  552. if todo >= 0:
  553. while todo > 0:
  554. data = self.fp.read(min(todo, self.bufsize))
  555. if not data:
  556. self.done = -1
  557. break
  558. self.file.write(data)
  559. todo = todo - len(data)
  560. def read_lines(self):
  561. """Internal: read lines until EOF or outerboundary."""
  562. self.file = self.__file = StringIO()
  563. if self.outerboundary:
  564. self.read_lines_to_outerboundary()
  565. else:
  566. self.read_lines_to_eof()
  567. def __write(self, line):
  568. if self.__file is not None:
  569. if self.__file.tell() + len(line) > 1000:
  570. self.file = self.make_file('')
  571. self.file.write(self.__file.getvalue())
  572. self.__file = None
  573. self.file.write(line)
  574. def read_lines_to_eof(self):
  575. """Internal: read lines until EOF."""
  576. while 1:
  577. line = self.fp.readline(1<<16)
  578. if not line:
  579. self.done = -1
  580. break
  581. self.__write(line)
  582. def read_lines_to_outerboundary(self):
  583. """Internal: read lines until outerboundary."""
  584. next = "--" + self.outerboundary
  585. last = next + "--"
  586. delim = ""
  587. last_line_lfend = True
  588. while 1:
  589. line = self.fp.readline(1<<16)
  590. if not line:
  591. self.done = -1
  592. break
  593. if line[:2] == "--" and last_line_lfend:
  594. strippedline = line.strip()
  595. if strippedline == next:
  596. break
  597. if strippedline == last:
  598. self.done = 1
  599. break
  600. odelim = delim
  601. if line[-2:] == "\r\n":
  602. delim = "\r\n"
  603. line = line[:-2]
  604. last_line_lfend = True
  605. elif line[-1] == "\n":
  606. delim = "\n"
  607. line = line[:-1]
  608. last_line_lfend = True
  609. else:
  610. delim = ""
  611. last_line_lfend = False
  612. self.__write(odelim + line)
  613. def skip_lines(self):
  614. """Internal: skip lines until outer boundary if defined."""
  615. if not self.outerboundary or self.done:
  616. return
  617. next = "--" + self.outerboundary
  618. last = next + "--"
  619. last_line_lfend = True
  620. while 1:
  621. line = self.fp.readline(1<<16)
  622. if not line:
  623. self.done = -1
  624. break
  625. if line[:2] == "--" and last_line_lfend:
  626. strippedline = line.strip()
  627. if strippedline == next:
  628. break
  629. if strippedline == last:
  630. self.done = 1
  631. break
  632. last_line_lfend = line.endswith('\n')
  633. def make_file(self, binary=None):
  634. """Overridable: return a readable & writable file.
  635. The file will be used as follows:
  636. - data is written to it
  637. - seek(0)
  638. - data is read from it
  639. The 'binary' argument is unused -- the file is always opened
  640. in binary mode.
  641. This version opens a temporary file for reading and writing,
  642. and immediately deletes (unlinks) it. The trick (on Unix!) is
  643. that the file can still be used, but it can't be opened by
  644. another process, and it will automatically be deleted when it
  645. is closed or when the current process terminates.
  646. If you want a more permanent file, you derive a class which
  647. overrides this method. If you want a visible temporary file
  648. that is nevertheless automatically deleted when the script
  649. terminates, try defining a __del__ method in a derived class
  650. which unlinks the temporary files you have created.
  651. """
  652. import tempfile
  653. return tempfile.TemporaryFile("w+b")
  654. # Backwards Compatibility Classes
  655. # ===============================
  656. class FormContentDict(UserDict.UserDict):
  657. """Form content as dictionary with a list of values per field.
  658. form = FormContentDict()
  659. form[key] -> [value, value, ...]
  660. key in form -> Boolean
  661. form.keys() -> [key, key, ...]
  662. form.values() -> [[val, val, ...], [val, val, ...], ...]
  663. form.items() -> [(key, [val, val, ...]), (key, [val, val, ...]), ...]
  664. form.dict == {key: [val, val, ...], ...}
  665. """
  666. def __init__(self, environ=os.environ, keep_blank_values=0, strict_parsing=0):
  667. self.dict = self.data = parse(environ=environ,
  668. keep_blank_values=keep_blank_values,
  669. strict_parsing=strict_parsing)
  670. self.query_string = environ['QUERY_STRING']
  671. class SvFormContentDict(FormContentDict):
  672. """Form content as dictionary expecting a single value per field.
  673. If you only expect a single value for each field, then form[key]
  674. will return that single value. It will raise an IndexError if
  675. that expectation is not true. If you expect a field to have
  676. possible multiple values, than you can use form.getlist(key) to
  677. get all of the values. values() and items() are a compromise:
  678. they return single strings where there is a single value, and
  679. lists of strings otherwise.
  680. """
  681. def __getitem__(self, key):
  682. if len(self.dict[key]) > 1:
  683. raise IndexError, 'expecting a single value'
  684. return self.dict[key][0]
  685. def getlist(self, key):
  686. return self.dict[key]
  687. def values(self):
  688. result = []
  689. for value in self.dict.values():
  690. if len(value) == 1:
  691. result.append(value[0])
  692. else: result.append(value)
  693. return result
  694. def items(self):
  695. result = []
  696. for key, value in self.dict.items():
  697. if len(value) == 1:
  698. result.append((key, value[0]))
  699. else: result.append((key, value))
  700. return result
  701. class InterpFormContentDict(SvFormContentDict):
  702. """This class is present for backwards compatibility only."""
  703. def __getitem__(self, key):
  704. v = SvFormContentDict.__getitem__(self, key)
  705. if v[0] in '0123456789+-.':
  706. try: return int(v)
  707. except ValueError:
  708. try: return float(v)
  709. except ValueError: pass
  710. return v.strip()
  711. def values(self):
  712. result = []
  713. for key in self.keys():
  714. try:
  715. result.append(self[key])
  716. except IndexError:
  717. result.append(self.dict[key])
  718. return result
  719. def items(self):
  720. result = []
  721. for key in self.keys():
  722. try:
  723. result.append((key, self[key]))
  724. except IndexError:
  725. result.append((key, self.dict[key]))
  726. return result
  727. class FormContent(FormContentDict):
  728. """This class is present for backwards compatibility only."""
  729. def values(self, key):
  730. if key in self.dict :return self.dict[key]
  731. else: return None
  732. def indexed_value(self, key, location):
  733. if key in self.dict:
  734. if len(self.dict[key]) > location:
  735. return self.dict[key][location]
  736. else: return None
  737. else: return None
  738. def value(self, key):
  739. if key in self.dict: return self.dict[key][0]
  740. else: return None
  741. def length(self, key):
  742. return len(self.dict[key])
  743. def stripped(self, key):
  744. if key in self.dict: return self.dict[key][0].strip()
  745. else: return None
  746. def pars(self):
  747. return self.dict
  748. # Test/debug code
  749. # ===============
  750. def test(environ=os.environ):
  751. """Robust test CGI script, usable as main program.
  752. Write minimal HTTP headers and dump all information provided to
  753. the script in HTML form.
  754. """
  755. print "Content-type: text/html"
  756. print
  757. sys.stderr = sys.stdout
  758. try:
  759. form = FieldStorage() # Replace with other classes to test those
  760. print_directory()
  761. print_arguments()
  762. print_form(form)
  763. print_environ(environ)
  764. print_environ_usage()
  765. def f():
  766. exec "testing print_exception() -- <I>italics?</I>"
  767. def g(f=f):
  768. f()
  769. print "<H3>What follows is a test, not an actual exception:</H3>"
  770. g()
  771. except:
  772. print_exception()
  773. print "<H1>Second try with a small maxlen...</H1>"
  774. global maxlen
  775. maxlen = 50
  776. try:
  777. form = FieldStorage() # Replace with other classes to test those
  778. print_directory()
  779. print_arguments()
  780. print_form(form)
  781. print_environ(environ)
  782. except:
  783. print_exception()
  784. def print_exception(type=None, value=None, tb=None, limit=None):
  785. if type is None:
  786. type, value, tb = sys.exc_info()
  787. import traceback
  788. print
  789. print "<H3>Traceback (most recent call last):</H3>"
  790. list = traceback.format_tb(tb, limit) + \
  791. traceback.format_exception_only(type, value)
  792. print "<PRE>%s<B>%s</B></PRE>" % (
  793. escape("".join(list[:-1])),
  794. escape(list[-1]),
  795. )
  796. del tb
  797. def print_environ(environ=os.environ):
  798. """Dump the shell environment as HTML."""
  799. keys = environ.keys()
  800. keys.sort()
  801. print
  802. print "<H3>Shell Environment:</H3>"
  803. print "<DL>"
  804. for key in keys:
  805. print "<DT>", escape(key), "<DD>", escape(environ[key])
  806. print "</DL>"
  807. print
  808. def print_form(form):
  809. """Dump the contents of a form as HTML."""
  810. keys = form.keys()
  811. keys.sort()
  812. print
  813. print "<H3>Form Contents:</H3>"
  814. if not keys:
  815. print "<P>No form fields."
  816. print "<DL>"
  817. for key in keys:
  818. print "<DT>" + escape(key) + ":",
  819. value = form[key]
  820. print "<i>" + escape(repr(type(value))) + "</i>"
  821. print "<DD>" + escape(repr(value))
  822. print "</DL>"
  823. print
  824. def print_directory():
  825. """Dump the current directory as HTML."""
  826. print
  827. print "<H3>Current Working Directory:</H3>"
  828. try:
  829. pwd = os.getcwd()
  830. except os.error, msg:
  831. print "os.error:", escape(str(msg))
  832. else:
  833. print escape(pwd)
  834. print
  835. def print_arguments():
  836. print
  837. print "<H3>Command Line Arguments:</H3>"
  838. print
  839. print sys.argv
  840. print
  841. def print_environ_usage():
  842. """Dump a list of environment variables used by CGI as HTML."""
  843. print """
  844. <H3>These environment variables could have been set:</H3>
  845. <UL>
  846. <LI>AUTH_TYPE
  847. <LI>CONTENT_LENGTH
  848. <LI>CONTENT_TYPE
  849. <LI>DATE_GMT
  850. <LI>DATE_LOCAL
  851. <LI>DOCUMENT_NAME
  852. <LI>DOCUMENT_ROOT
  853. <LI>DOCUMENT_URI
  854. <LI>GATEWAY_INTERFACE
  855. <LI>LAST_MODIFIED
  856. <LI>PATH
  857. <LI>PATH_INFO
  858. <LI>PATH_TRANSLATED
  859. <LI>QUERY_STRING
  860. <LI>REMOTE_ADDR
  861. <LI>REMOTE_HOST
  862. <LI>REMOTE_IDENT
  863. <LI>REMOTE_USER
  864. <LI>REQUEST_METHOD
  865. <LI>SCRIPT_NAME
  866. <LI>SERVER_NAME
  867. <LI>SERVER_PORT
  868. <LI>SERVER_PROTOCOL
  869. <LI>SERVER_ROOT
  870. <LI>SERVER_SOFTWARE
  871. </UL>
  872. In addition, HTTP headers sent by the server may be passed in the
  873. environment as well. Here are some common variable names:
  874. <UL>
  875. <LI>HTTP_ACCEPT
  876. <LI>HTTP_CONNECTION
  877. <LI>HTTP_HOST
  878. <LI>HTTP_PRAGMA
  879. <LI>HTTP_REFERER
  880. <LI>HTTP_USER_AGENT
  881. </UL>
  882. """
  883. # Utilities
  884. # =========
  885. def escape(s, quote=None):
  886. '''Replace special characters "&", "<" and ">" to HTML-safe sequences.
  887. If the optional flag quote is true, the quotation mark character (")
  888. is also translated.'''
  889. s = s.replace("&", "&amp;") # Must be done first!
  890. s = s.replace("<", "&lt;")
  891. s = s.replace(">", "&gt;")
  892. if quote:
  893. s = s.replace('"', "&quot;")
  894. return s
  895. def valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"):
  896. import re
  897. return re.match(_vb_pattern, s)
  898. # Invoke mainline
  899. # ===============
  900. # Call test() when this file is run as a script (not imported as a module)
  901. if __name__ == '__main__':
  902. test()