PageRenderTime 38ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/other/FetchData/ClientForm.py

http://github.com/jbeezley/wrf-fire
Python | 3401 lines | 3209 code | 69 blank | 123 comment | 84 complexity | e39b95cd355883183b9cc33194d1a082 MD5 | raw file
Possible License(s): AGPL-1.0
  1. """HTML form handling for web clients.
  2. ClientForm is a Python module for handling HTML forms on the client
  3. side, useful for parsing HTML forms, filling them in and returning the
  4. completed forms to the server. It has developed from a port of Gisle
  5. Aas' Perl module HTML::Form, from the libwww-perl library, but the
  6. interface is not the same.
  7. The most useful docstring is the one for HTMLForm.
  8. RFC 1866: HTML 2.0
  9. RFC 1867: Form-based File Upload in HTML
  10. RFC 2388: Returning Values from Forms: multipart/form-data
  11. HTML 3.2 Specification, W3C Recommendation 14 January 1997 (for ISINDEX)
  12. HTML 4.01 Specification, W3C Recommendation 24 December 1999
  13. Copyright 2002-2007 John J. Lee <jjl@pobox.com>
  14. Copyright 2005 Gary Poster
  15. Copyright 2005 Zope Corporation
  16. Copyright 1998-2000 Gisle Aas.
  17. This code is free software; you can redistribute it and/or modify it
  18. under the terms of the BSD or ZPL 2.1 licenses (see the file
  19. COPYING.txt included with the distribution).
  20. """
  21. # XXX
  22. # Remove parser testing hack
  23. # safeUrl()-ize action
  24. # Switch to unicode throughout (would be 0.3.x)
  25. # See Wichert Akkerman's 2004-01-22 message to c.l.py.
  26. # Add charset parameter to Content-type headers? How to find value??
  27. # Add some more functional tests
  28. # Especially single and multiple file upload on the internet.
  29. # Does file upload work when name is missing? Sourceforge tracker form
  30. # doesn't like it. Check standards, and test with Apache. Test
  31. # binary upload with Apache.
  32. # mailto submission & enctype text/plain
  33. # I'm not going to fix this unless somebody tells me what real servers
  34. # that want this encoding actually expect: If enctype is
  35. # application/x-www-form-urlencoded and there's a FILE control present.
  36. # Strictly, it should be 'name=data' (see HTML 4.01 spec., section
  37. # 17.13.2), but I send "name=" ATM. What about multiple file upload??
  38. # Would be nice, but I'm not going to do it myself:
  39. # -------------------------------------------------
  40. # Maybe a 0.4.x?
  41. # Replace by_label etc. with moniker / selector concept. Allows, eg.,
  42. # a choice between selection by value / id / label / element
  43. # contents. Or choice between matching labels exactly or by
  44. # substring. Etc.
  45. # Remove deprecated methods.
  46. # ...what else?
  47. # Work on DOMForm.
  48. # XForms? Don't know if there's a need here.
  49. __all__ = ['AmbiguityError', 'CheckboxControl', 'Control',
  50. 'ControlNotFoundError', 'FileControl', 'FormParser', 'HTMLForm',
  51. 'HiddenControl', 'IgnoreControl', 'ImageControl', 'IsindexControl',
  52. 'Item', 'ItemCountError', 'ItemNotFoundError', 'Label',
  53. 'ListControl', 'LocateError', 'Missing', 'ParseError', 'ParseFile',
  54. 'ParseFileEx', 'ParseResponse', 'ParseResponseEx','PasswordControl',
  55. 'RadioControl', 'ScalarControl', 'SelectControl',
  56. 'SubmitButtonControl', 'SubmitControl', 'TextControl',
  57. 'TextareaControl', 'XHTMLCompatibleFormParser']
  58. try: True
  59. except NameError:
  60. True = 1
  61. False = 0
  62. try: bool
  63. except NameError:
  64. def bool(expr):
  65. if expr: return True
  66. else: return False
  67. try:
  68. import logging
  69. import inspect
  70. except ImportError:
  71. def debug(msg, *args, **kwds):
  72. pass
  73. else:
  74. _logger = logging.getLogger("ClientForm")
  75. OPTIMIZATION_HACK = True
  76. def debug(msg, *args, **kwds):
  77. if OPTIMIZATION_HACK:
  78. return
  79. caller_name = inspect.stack()[1][3]
  80. extended_msg = '%%s %s' % msg
  81. extended_args = (caller_name,)+args
  82. debug = _logger.debug(extended_msg, *extended_args, **kwds)
  83. def _show_debug_messages():
  84. global OPTIMIZATION_HACK
  85. OPTIMIZATION_HACK = False
  86. _logger.setLevel(logging.DEBUG)
  87. handler = logging.StreamHandler(sys.stdout)
  88. handler.setLevel(logging.DEBUG)
  89. _logger.addHandler(handler)
  90. import sys, urllib, urllib2, types, mimetools, copy, urlparse, \
  91. htmlentitydefs, re, random
  92. from cStringIO import StringIO
  93. import sgmllib
  94. # monkeypatch to fix http://www.python.org/sf/803422 :-(
  95. sgmllib.charref = re.compile("&#(x?[0-9a-fA-F]+)[^0-9a-fA-F]")
  96. # HTMLParser.HTMLParser is recent, so live without it if it's not available
  97. # (also, sgmllib.SGMLParser is much more tolerant of bad HTML)
  98. try:
  99. import HTMLParser
  100. except ImportError:
  101. HAVE_MODULE_HTMLPARSER = False
  102. else:
  103. HAVE_MODULE_HTMLPARSER = True
  104. try:
  105. import warnings
  106. except ImportError:
  107. def deprecation(message, stack_offset=0):
  108. pass
  109. else:
  110. def deprecation(message, stack_offset=0):
  111. warnings.warn(message, DeprecationWarning, stacklevel=3+stack_offset)
  112. VERSION = "0.2.10"
  113. CHUNK = 1024 # size of chunks fed to parser, in bytes
  114. DEFAULT_ENCODING = "latin-1"
  115. class Missing: pass
  116. _compress_re = re.compile(r"\s+")
  117. def compress_text(text): return _compress_re.sub(" ", text.strip())
  118. def normalize_line_endings(text):
  119. return re.sub(r"(?:(?<!\r)\n)|(?:\r(?!\n))", "\r\n", text)
  120. # This version of urlencode is from my Python 1.5.2 back-port of the
  121. # Python 2.1 CVS maintenance branch of urllib. It will accept a sequence
  122. # of pairs instead of a mapping -- the 2.0 version only accepts a mapping.
  123. def urlencode(query,doseq=False,):
  124. """Encode a sequence of two-element tuples or dictionary into a URL query \
  125. string.
  126. If any values in the query arg are sequences and doseq is true, each
  127. sequence element is converted to a separate parameter.
  128. If the query arg is a sequence of two-element tuples, the order of the
  129. parameters in the output will match the order of parameters in the
  130. input.
  131. """
  132. if hasattr(query,"items"):
  133. # mapping objects
  134. query = query.items()
  135. else:
  136. # it's a bother at times that strings and string-like objects are
  137. # sequences...
  138. try:
  139. # non-sequence items should not work with len()
  140. x = len(query)
  141. # non-empty strings will fail this
  142. if len(query) and type(query[0]) != types.TupleType:
  143. raise TypeError()
  144. # zero-length sequences of all types will get here and succeed,
  145. # but that's a minor nit - since the original implementation
  146. # allowed empty dicts that type of behavior probably should be
  147. # preserved for consistency
  148. except TypeError:
  149. ty,va,tb = sys.exc_info()
  150. raise TypeError("not a valid non-string sequence or mapping "
  151. "object", tb)
  152. l = []
  153. if not doseq:
  154. # preserve old behavior
  155. for k, v in query:
  156. k = urllib.quote_plus(str(k))
  157. v = urllib.quote_plus(str(v))
  158. l.append(k + '=' + v)
  159. else:
  160. for k, v in query:
  161. k = urllib.quote_plus(str(k))
  162. if type(v) == types.StringType:
  163. v = urllib.quote_plus(v)
  164. l.append(k + '=' + v)
  165. elif type(v) == types.UnicodeType:
  166. # is there a reasonable way to convert to ASCII?
  167. # encode generates a string, but "replace" or "ignore"
  168. # lose information and "strict" can raise UnicodeError
  169. v = urllib.quote_plus(v.encode("ASCII","replace"))
  170. l.append(k + '=' + v)
  171. else:
  172. try:
  173. # is this a sufficient test for sequence-ness?
  174. x = len(v)
  175. except TypeError:
  176. # not a sequence
  177. v = urllib.quote_plus(str(v))
  178. l.append(k + '=' + v)
  179. else:
  180. # loop over the sequence
  181. for elt in v:
  182. l.append(k + '=' + urllib.quote_plus(str(elt)))
  183. return '&'.join(l)
  184. def unescape(data, entities, encoding=DEFAULT_ENCODING):
  185. if data is None or "&" not in data:
  186. return data
  187. def replace_entities(match, entities=entities, encoding=encoding):
  188. ent = match.group()
  189. if ent[1] == "#":
  190. return unescape_charref(ent[2:-1], encoding)
  191. repl = entities.get(ent)
  192. if repl is not None:
  193. if type(repl) != type(""):
  194. try:
  195. repl = repl.encode(encoding)
  196. except UnicodeError:
  197. repl = ent
  198. else:
  199. repl = ent
  200. return repl
  201. return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data)
  202. def unescape_charref(data, encoding):
  203. name, base = data, 10
  204. if name.startswith("x"):
  205. name, base= name[1:], 16
  206. uc = unichr(int(name, base))
  207. if encoding is None:
  208. return uc
  209. else:
  210. try:
  211. repl = uc.encode(encoding)
  212. except UnicodeError:
  213. repl = "&#%s;" % data
  214. return repl
  215. def get_entitydefs():
  216. import htmlentitydefs
  217. from codecs import latin_1_decode
  218. entitydefs = {}
  219. try:
  220. htmlentitydefs.name2codepoint
  221. except AttributeError:
  222. entitydefs = {}
  223. for name, char in htmlentitydefs.entitydefs.items():
  224. uc = latin_1_decode(char)[0]
  225. if uc.startswith("&#") and uc.endswith(";"):
  226. uc = unescape_charref(uc[2:-1], None)
  227. entitydefs["&%s;" % name] = uc
  228. else:
  229. for name, codepoint in htmlentitydefs.name2codepoint.items():
  230. entitydefs["&%s;" % name] = unichr(codepoint)
  231. return entitydefs
  232. def issequence(x):
  233. try:
  234. x[0]
  235. except (TypeError, KeyError):
  236. return False
  237. except IndexError:
  238. pass
  239. return True
  240. def isstringlike(x):
  241. try: x+""
  242. except: return False
  243. else: return True
  244. def choose_boundary():
  245. """Return a string usable as a multipart boundary."""
  246. # follow IE and firefox
  247. nonce = "".join([str(random.randint(0, sys.maxint-1)) for i in 0,1,2])
  248. return "-"*27 + nonce
  249. # This cut-n-pasted MimeWriter from standard library is here so can add
  250. # to HTTP headers rather than message body when appropriate. It also uses
  251. # \r\n in place of \n. This is a bit nasty.
  252. class MimeWriter:
  253. """Generic MIME writer.
  254. Methods:
  255. __init__()
  256. addheader()
  257. flushheaders()
  258. startbody()
  259. startmultipartbody()
  260. nextpart()
  261. lastpart()
  262. A MIME writer is much more primitive than a MIME parser. It
  263. doesn't seek around on the output file, and it doesn't use large
  264. amounts of buffer space, so you have to write the parts in the
  265. order they should occur on the output file. It does buffer the
  266. headers you add, allowing you to rearrange their order.
  267. General usage is:
  268. f = <open the output file>
  269. w = MimeWriter(f)
  270. ...call w.addheader(key, value) 0 or more times...
  271. followed by either:
  272. f = w.startbody(content_type)
  273. ...call f.write(data) for body data...
  274. or:
  275. w.startmultipartbody(subtype)
  276. for each part:
  277. subwriter = w.nextpart()
  278. ...use the subwriter's methods to create the subpart...
  279. w.lastpart()
  280. The subwriter is another MimeWriter instance, and should be
  281. treated in the same way as the toplevel MimeWriter. This way,
  282. writing recursive body parts is easy.
  283. Warning: don't forget to call lastpart()!
  284. XXX There should be more state so calls made in the wrong order
  285. are detected.
  286. Some special cases:
  287. - startbody() just returns the file passed to the constructor;
  288. but don't use this knowledge, as it may be changed.
  289. - startmultipartbody() actually returns a file as well;
  290. this can be used to write the initial 'if you can read this your
  291. mailer is not MIME-aware' message.
  292. - If you call flushheaders(), the headers accumulated so far are
  293. written out (and forgotten); this is useful if you don't need a
  294. body part at all, e.g. for a subpart of type message/rfc822
  295. that's (mis)used to store some header-like information.
  296. - Passing a keyword argument 'prefix=<flag>' to addheader(),
  297. start*body() affects where the header is inserted; 0 means
  298. append at the end, 1 means insert at the start; default is
  299. append for addheader(), but insert for start*body(), which use
  300. it to determine where the Content-type header goes.
  301. """
  302. def __init__(self, fp, http_hdrs=None):
  303. self._http_hdrs = http_hdrs
  304. self._fp = fp
  305. self._headers = []
  306. self._boundary = []
  307. self._first_part = True
  308. def addheader(self, key, value, prefix=0,
  309. add_to_http_hdrs=0):
  310. """
  311. prefix is ignored if add_to_http_hdrs is true.
  312. """
  313. lines = value.split("\r\n")
  314. while lines and not lines[-1]: del lines[-1]
  315. while lines and not lines[0]: del lines[0]
  316. if add_to_http_hdrs:
  317. value = "".join(lines)
  318. # 2.2 urllib2 doesn't normalize header case
  319. self._http_hdrs.append((key.capitalize(), value))
  320. else:
  321. for i in range(1, len(lines)):
  322. lines[i] = " " + lines[i].strip()
  323. value = "\r\n".join(lines) + "\r\n"
  324. line = key.title() + ": " + value
  325. if prefix:
  326. self._headers.insert(0, line)
  327. else:
  328. self._headers.append(line)
  329. def flushheaders(self):
  330. self._fp.writelines(self._headers)
  331. self._headers = []
  332. def startbody(self, ctype=None, plist=[], prefix=1,
  333. add_to_http_hdrs=0, content_type=1):
  334. """
  335. prefix is ignored if add_to_http_hdrs is true.
  336. """
  337. if content_type and ctype:
  338. for name, value in plist:
  339. ctype = ctype + ';\r\n %s=%s' % (name, value)
  340. self.addheader("Content-Type", ctype, prefix=prefix,
  341. add_to_http_hdrs=add_to_http_hdrs)
  342. self.flushheaders()
  343. if not add_to_http_hdrs: self._fp.write("\r\n")
  344. self._first_part = True
  345. return self._fp
  346. def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1,
  347. add_to_http_hdrs=0, content_type=1):
  348. boundary = boundary or choose_boundary()
  349. self._boundary.append(boundary)
  350. return self.startbody("multipart/" + subtype,
  351. [("boundary", boundary)] + plist,
  352. prefix=prefix,
  353. add_to_http_hdrs=add_to_http_hdrs,
  354. content_type=content_type)
  355. def nextpart(self):
  356. boundary = self._boundary[-1]
  357. if self._first_part:
  358. self._first_part = False
  359. else:
  360. self._fp.write("\r\n")
  361. self._fp.write("--" + boundary + "\r\n")
  362. return self.__class__(self._fp)
  363. def lastpart(self):
  364. if self._first_part:
  365. self.nextpart()
  366. boundary = self._boundary.pop()
  367. self._fp.write("\r\n--" + boundary + "--\r\n")
  368. class LocateError(ValueError): pass
  369. class AmbiguityError(LocateError): pass
  370. class ControlNotFoundError(LocateError): pass
  371. class ItemNotFoundError(LocateError): pass
  372. class ItemCountError(ValueError): pass
  373. # for backwards compatibility, ParseError derives from exceptions that were
  374. # raised by versions of ClientForm <= 0.2.5
  375. if HAVE_MODULE_HTMLPARSER:
  376. SGMLLIB_PARSEERROR = sgmllib.SGMLParseError
  377. class ParseError(sgmllib.SGMLParseError,
  378. HTMLParser.HTMLParseError,
  379. ):
  380. pass
  381. else:
  382. if hasattr(sgmllib, "SGMLParseError"):
  383. SGMLLIB_PARSEERROR = sgmllib.SGMLParseError
  384. class ParseError(sgmllib.SGMLParseError):
  385. pass
  386. else:
  387. SGMLLIB_PARSEERROR = RuntimeError
  388. class ParseError(RuntimeError):
  389. pass
  390. class _AbstractFormParser:
  391. """forms attribute contains HTMLForm instances on completion."""
  392. # thanks to Moshe Zadka for an example of sgmllib/htmllib usage
  393. def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING):
  394. if entitydefs is None:
  395. entitydefs = get_entitydefs()
  396. self._entitydefs = entitydefs
  397. self._encoding = encoding
  398. self.base = None
  399. self.forms = []
  400. self.labels = []
  401. self._current_label = None
  402. self._current_form = None
  403. self._select = None
  404. self._optgroup = None
  405. self._option = None
  406. self._textarea = None
  407. # forms[0] will contain all controls that are outside of any form
  408. # self._global_form is an alias for self.forms[0]
  409. self._global_form = None
  410. self.start_form([])
  411. self.end_form()
  412. self._current_form = self._global_form = self.forms[0]
  413. def do_base(self, attrs):
  414. debug("%s", attrs)
  415. for key, value in attrs:
  416. if key == "href":
  417. self.base = self.unescape_attr_if_required(value)
  418. def end_body(self):
  419. debug("")
  420. if self._current_label is not None:
  421. self.end_label()
  422. if self._current_form is not self._global_form:
  423. self.end_form()
  424. def start_form(self, attrs):
  425. debug("%s", attrs)
  426. if self._current_form is not self._global_form:
  427. raise ParseError("nested FORMs")
  428. name = None
  429. action = None
  430. enctype = "application/x-www-form-urlencoded"
  431. method = "GET"
  432. d = {}
  433. for key, value in attrs:
  434. if key == "name":
  435. name = self.unescape_attr_if_required(value)
  436. elif key == "action":
  437. action = self.unescape_attr_if_required(value)
  438. elif key == "method":
  439. method = self.unescape_attr_if_required(value.upper())
  440. elif key == "enctype":
  441. enctype = self.unescape_attr_if_required(value.lower())
  442. d[key] = self.unescape_attr_if_required(value)
  443. controls = []
  444. self._current_form = (name, action, method, enctype), d, controls
  445. def end_form(self):
  446. debug("")
  447. if self._current_label is not None:
  448. self.end_label()
  449. if self._current_form is self._global_form:
  450. raise ParseError("end of FORM before start")
  451. self.forms.append(self._current_form)
  452. self._current_form = self._global_form
  453. def start_select(self, attrs):
  454. debug("%s", attrs)
  455. if self._select is not None:
  456. raise ParseError("nested SELECTs")
  457. if self._textarea is not None:
  458. raise ParseError("SELECT inside TEXTAREA")
  459. d = {}
  460. for key, val in attrs:
  461. d[key] = self.unescape_attr_if_required(val)
  462. self._select = d
  463. self._add_label(d)
  464. self._append_select_control({"__select": d})
  465. def end_select(self):
  466. debug("")
  467. if self._select is None:
  468. raise ParseError("end of SELECT before start")
  469. if self._option is not None:
  470. self._end_option()
  471. self._select = None
  472. def start_optgroup(self, attrs):
  473. debug("%s", attrs)
  474. if self._select is None:
  475. raise ParseError("OPTGROUP outside of SELECT")
  476. d = {}
  477. for key, val in attrs:
  478. d[key] = self.unescape_attr_if_required(val)
  479. self._optgroup = d
  480. def end_optgroup(self):
  481. debug("")
  482. if self._optgroup is None:
  483. raise ParseError("end of OPTGROUP before start")
  484. self._optgroup = None
  485. def _start_option(self, attrs):
  486. debug("%s", attrs)
  487. if self._select is None:
  488. raise ParseError("OPTION outside of SELECT")
  489. if self._option is not None:
  490. self._end_option()
  491. d = {}
  492. for key, val in attrs:
  493. d[key] = self.unescape_attr_if_required(val)
  494. self._option = {}
  495. self._option.update(d)
  496. if (self._optgroup and self._optgroup.has_key("disabled") and
  497. not self._option.has_key("disabled")):
  498. self._option["disabled"] = None
  499. def _end_option(self):
  500. debug("")
  501. if self._option is None:
  502. raise ParseError("end of OPTION before start")
  503. contents = self._option.get("contents", "").strip()
  504. self._option["contents"] = contents
  505. if not self._option.has_key("value"):
  506. self._option["value"] = contents
  507. if not self._option.has_key("label"):
  508. self._option["label"] = contents
  509. # stuff dict of SELECT HTML attrs into a special private key
  510. # (gets deleted again later)
  511. self._option["__select"] = self._select
  512. self._append_select_control(self._option)
  513. self._option = None
  514. def _append_select_control(self, attrs):
  515. debug("%s", attrs)
  516. controls = self._current_form[2]
  517. name = self._select.get("name")
  518. controls.append(("select", name, attrs))
  519. def start_textarea(self, attrs):
  520. debug("%s", attrs)
  521. if self._textarea is not None:
  522. raise ParseError("nested TEXTAREAs")
  523. if self._select is not None:
  524. raise ParseError("TEXTAREA inside SELECT")
  525. d = {}
  526. for key, val in attrs:
  527. d[key] = self.unescape_attr_if_required(val)
  528. self._add_label(d)
  529. self._textarea = d
  530. def end_textarea(self):
  531. debug("")
  532. if self._textarea is None:
  533. raise ParseError("end of TEXTAREA before start")
  534. controls = self._current_form[2]
  535. name = self._textarea.get("name")
  536. controls.append(("textarea", name, self._textarea))
  537. self._textarea = None
  538. def start_label(self, attrs):
  539. debug("%s", attrs)
  540. if self._current_label:
  541. self.end_label()
  542. d = {}
  543. for key, val in attrs:
  544. d[key] = self.unescape_attr_if_required(val)
  545. taken = bool(d.get("for")) # empty id is invalid
  546. d["__text"] = ""
  547. d["__taken"] = taken
  548. if taken:
  549. self.labels.append(d)
  550. self._current_label = d
  551. def end_label(self):
  552. debug("")
  553. label = self._current_label
  554. if label is None:
  555. # something is ugly in the HTML, but we're ignoring it
  556. return
  557. self._current_label = None
  558. # if it is staying around, it is True in all cases
  559. del label["__taken"]
  560. def _add_label(self, d):
  561. #debug("%s", d)
  562. if self._current_label is not None:
  563. if not self._current_label["__taken"]:
  564. self._current_label["__taken"] = True
  565. d["__label"] = self._current_label
  566. def handle_data(self, data):
  567. debug("%s", data)
  568. if self._option is not None:
  569. # self._option is a dictionary of the OPTION element's HTML
  570. # attributes, but it has two special keys, one of which is the
  571. # special "contents" key contains text between OPTION tags (the
  572. # other is the "__select" key: see the end_option method)
  573. map = self._option
  574. key = "contents"
  575. elif self._textarea is not None:
  576. map = self._textarea
  577. key = "value"
  578. data = normalize_line_endings(data)
  579. # not if within option or textarea
  580. elif self._current_label is not None:
  581. map = self._current_label
  582. key = "__text"
  583. else:
  584. return
  585. if data and not map.has_key(key):
  586. # according to
  587. # http://www.w3.org/TR/html4/appendix/notes.html#h-B.3.1 line break
  588. # immediately after start tags or immediately before end tags must
  589. # be ignored, but real browsers only ignore a line break after a
  590. # start tag, so we'll do that.
  591. if data[0:2] == "\r\n":
  592. data = data[2:]
  593. elif data[0:1] in ["\n", "\r"]:
  594. data = data[1:]
  595. map[key] = data
  596. else:
  597. map[key] = map[key] + data
  598. def do_button(self, attrs):
  599. debug("%s", attrs)
  600. d = {}
  601. d["type"] = "submit" # default
  602. for key, val in attrs:
  603. d[key] = self.unescape_attr_if_required(val)
  604. controls = self._current_form[2]
  605. type = d["type"]
  606. name = d.get("name")
  607. # we don't want to lose information, so use a type string that
  608. # doesn't clash with INPUT TYPE={SUBMIT,RESET,BUTTON}
  609. # e.g. type for BUTTON/RESET is "resetbutton"
  610. # (type for INPUT/RESET is "reset")
  611. type = type+"button"
  612. self._add_label(d)
  613. controls.append((type, name, d))
  614. def do_input(self, attrs):
  615. debug("%s", attrs)
  616. d = {}
  617. d["type"] = "text" # default
  618. for key, val in attrs:
  619. d[key] = self.unescape_attr_if_required(val)
  620. controls = self._current_form[2]
  621. type = d["type"]
  622. name = d.get("name")
  623. self._add_label(d)
  624. controls.append((type, name, d))
  625. def do_isindex(self, attrs):
  626. debug("%s", attrs)
  627. d = {}
  628. for key, val in attrs:
  629. d[key] = self.unescape_attr_if_required(val)
  630. controls = self._current_form[2]
  631. self._add_label(d)
  632. # isindex doesn't have type or name HTML attributes
  633. controls.append(("isindex", None, d))
  634. def handle_entityref(self, name):
  635. #debug("%s", name)
  636. self.handle_data(unescape(
  637. '&%s;' % name, self._entitydefs, self._encoding))
  638. def handle_charref(self, name):
  639. #debug("%s", name)
  640. self.handle_data(unescape_charref(name, self._encoding))
  641. def unescape_attr(self, name):
  642. #debug("%s", name)
  643. return unescape(name, self._entitydefs, self._encoding)
  644. def unescape_attrs(self, attrs):
  645. #debug("%s", attrs)
  646. escaped_attrs = {}
  647. for key, val in attrs.items():
  648. try:
  649. val.items
  650. except AttributeError:
  651. escaped_attrs[key] = self.unescape_attr(val)
  652. else:
  653. # e.g. "__select" -- yuck!
  654. escaped_attrs[key] = self.unescape_attrs(val)
  655. return escaped_attrs
  656. def unknown_entityref(self, ref): self.handle_data("&%s;" % ref)
  657. def unknown_charref(self, ref): self.handle_data("&#%s;" % ref)
  658. if not HAVE_MODULE_HTMLPARSER:
  659. class XHTMLCompatibleFormParser:
  660. def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING):
  661. raise ValueError("HTMLParser could not be imported")
  662. else:
  663. class XHTMLCompatibleFormParser(_AbstractFormParser, HTMLParser.HTMLParser):
  664. """Good for XHTML, bad for tolerance of incorrect HTML."""
  665. # thanks to Michael Howitz for this!
  666. def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING):
  667. HTMLParser.HTMLParser.__init__(self)
  668. _AbstractFormParser.__init__(self, entitydefs, encoding)
  669. def feed(self, data):
  670. try:
  671. HTMLParser.HTMLParser.feed(self, data)
  672. except HTMLParser.HTMLParseError, exc:
  673. raise ParseError(exc)
  674. def start_option(self, attrs):
  675. _AbstractFormParser._start_option(self, attrs)
  676. def end_option(self):
  677. _AbstractFormParser._end_option(self)
  678. def handle_starttag(self, tag, attrs):
  679. try:
  680. method = getattr(self, "start_" + tag)
  681. except AttributeError:
  682. try:
  683. method = getattr(self, "do_" + tag)
  684. except AttributeError:
  685. pass # unknown tag
  686. else:
  687. method(attrs)
  688. else:
  689. method(attrs)
  690. def handle_endtag(self, tag):
  691. try:
  692. method = getattr(self, "end_" + tag)
  693. except AttributeError:
  694. pass # unknown tag
  695. else:
  696. method()
  697. def unescape(self, name):
  698. # Use the entitydefs passed into constructor, not
  699. # HTMLParser.HTMLParser's entitydefs.
  700. return self.unescape_attr(name)
  701. def unescape_attr_if_required(self, name):
  702. return name # HTMLParser.HTMLParser already did it
  703. def unescape_attrs_if_required(self, attrs):
  704. return attrs # ditto
  705. def close(self):
  706. HTMLParser.HTMLParser.close(self)
  707. self.end_body()
  708. class _AbstractSgmllibParser(_AbstractFormParser):
  709. def do_option(self, attrs):
  710. _AbstractFormParser._start_option(self, attrs)
  711. if sys.version_info[:2] >= (2,5):
  712. # we override this attr to decode hex charrefs
  713. entity_or_charref = re.compile(
  714. '&(?:([a-zA-Z][-.a-zA-Z0-9]*)|#(x?[0-9a-fA-F]+))(;?)')
  715. def convert_entityref(self, name):
  716. return unescape("&%s;" % name, self._entitydefs, self._encoding)
  717. def convert_charref(self, name):
  718. return unescape_charref("%s" % name, self._encoding)
  719. def unescape_attr_if_required(self, name):
  720. return name # sgmllib already did it
  721. def unescape_attrs_if_required(self, attrs):
  722. return attrs # ditto
  723. else:
  724. def unescape_attr_if_required(self, name):
  725. return self.unescape_attr(name)
  726. def unescape_attrs_if_required(self, attrs):
  727. return self.unescape_attrs(attrs)
  728. class FormParser(_AbstractSgmllibParser, sgmllib.SGMLParser):
  729. """Good for tolerance of incorrect HTML, bad for XHTML."""
  730. def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING):
  731. sgmllib.SGMLParser.__init__(self)
  732. _AbstractFormParser.__init__(self, entitydefs, encoding)
  733. def feed(self, data):
  734. try:
  735. sgmllib.SGMLParser.feed(self, data)
  736. except SGMLLIB_PARSEERROR, exc:
  737. raise ParseError(exc)
  738. def close(self):
  739. sgmllib.SGMLParser.close(self)
  740. self.end_body()
  741. # sigh, must support mechanize by allowing dynamic creation of classes based on
  742. # its bundled copy of BeautifulSoup (which was necessary because of dependency
  743. # problems)
  744. def _create_bs_classes(bs,
  745. icbinbs,
  746. ):
  747. class _AbstractBSFormParser(_AbstractSgmllibParser):
  748. bs_base_class = None
  749. def __init__(self, entitydefs=None, encoding=DEFAULT_ENCODING):
  750. _AbstractFormParser.__init__(self, entitydefs, encoding)
  751. self.bs_base_class.__init__(self)
  752. def handle_data(self, data):
  753. _AbstractFormParser.handle_data(self, data)
  754. self.bs_base_class.handle_data(self, data)
  755. def feed(self, data):
  756. try:
  757. self.bs_base_class.feed(self, data)
  758. except SGMLLIB_PARSEERROR, exc:
  759. raise ParseError(exc)
  760. def close(self):
  761. self.bs_base_class.close(self)
  762. self.end_body()
  763. class RobustFormParser(_AbstractBSFormParser, bs):
  764. """Tries to be highly tolerant of incorrect HTML."""
  765. pass
  766. RobustFormParser.bs_base_class = bs
  767. class NestingRobustFormParser(_AbstractBSFormParser, icbinbs):
  768. """Tries to be highly tolerant of incorrect HTML.
  769. Different from RobustFormParser in that it more often guesses nesting
  770. above missing end tags (see BeautifulSoup docs).
  771. """
  772. pass
  773. NestingRobustFormParser.bs_base_class = icbinbs
  774. return RobustFormParser, NestingRobustFormParser
  775. try:
  776. if sys.version_info[:2] < (2, 2):
  777. raise ImportError # BeautifulSoup uses generators
  778. import BeautifulSoup
  779. except ImportError:
  780. pass
  781. else:
  782. RobustFormParser, NestingRobustFormParser = _create_bs_classes(
  783. BeautifulSoup.BeautifulSoup, BeautifulSoup.ICantBelieveItsBeautifulSoup
  784. )
  785. __all__ += ['RobustFormParser', 'NestingRobustFormParser']
  786. #FormParser = XHTMLCompatibleFormParser # testing hack
  787. #FormParser = RobustFormParser # testing hack
  788. def ParseResponseEx(response,
  789. select_default=False,
  790. form_parser_class=FormParser,
  791. request_class=urllib2.Request,
  792. entitydefs=None,
  793. encoding=DEFAULT_ENCODING,
  794. # private
  795. _urljoin=urlparse.urljoin,
  796. _urlparse=urlparse.urlparse,
  797. _urlunparse=urlparse.urlunparse,
  798. ):
  799. """Identical to ParseResponse, except that:
  800. 1. The returned list contains an extra item. The first form in the list
  801. contains all controls not contained in any FORM element.
  802. 2. The arguments ignore_errors and backwards_compat have been removed.
  803. 3. Backwards-compatibility mode (backwards_compat=True) is not available.
  804. """
  805. return _ParseFileEx(response, response.geturl(),
  806. select_default,
  807. False,
  808. form_parser_class,
  809. request_class,
  810. entitydefs,
  811. False,
  812. encoding,
  813. _urljoin=_urljoin,
  814. _urlparse=_urlparse,
  815. _urlunparse=_urlunparse,
  816. )
  817. def ParseFileEx(file, base_uri,
  818. select_default=False,
  819. form_parser_class=FormParser,
  820. request_class=urllib2.Request,
  821. entitydefs=None,
  822. encoding=DEFAULT_ENCODING,
  823. # private
  824. _urljoin=urlparse.urljoin,
  825. _urlparse=urlparse.urlparse,
  826. _urlunparse=urlparse.urlunparse,
  827. ):
  828. """Identical to ParseFile, except that:
  829. 1. The returned list contains an extra item. The first form in the list
  830. contains all controls not contained in any FORM element.
  831. 2. The arguments ignore_errors and backwards_compat have been removed.
  832. 3. Backwards-compatibility mode (backwards_compat=True) is not available.
  833. """
  834. return _ParseFileEx(file, base_uri,
  835. select_default,
  836. False,
  837. form_parser_class,
  838. request_class,
  839. entitydefs,
  840. False,
  841. encoding,
  842. _urljoin=_urljoin,
  843. _urlparse=_urlparse,
  844. _urlunparse=_urlunparse,
  845. )
  846. def ParseResponse(response, *args, **kwds):
  847. """Parse HTTP response and return a list of HTMLForm instances.
  848. The return value of urllib2.urlopen can be conveniently passed to this
  849. function as the response parameter.
  850. ClientForm.ParseError is raised on parse errors.
  851. response: file-like object (supporting read() method) with a method
  852. geturl(), returning the URI of the HTTP response
  853. select_default: for multiple-selection SELECT controls and RADIO controls,
  854. pick the first item as the default if none are selected in the HTML
  855. form_parser_class: class to instantiate and use to pass
  856. request_class: class to return from .click() method (default is
  857. urllib2.Request)
  858. entitydefs: mapping like {"&amp;": "&", ...} containing HTML entity
  859. definitions (a sensible default is used)
  860. encoding: character encoding used for encoding numeric character references
  861. when matching link text. ClientForm does not attempt to find the encoding
  862. in a META HTTP-EQUIV attribute in the document itself (mechanize, for
  863. example, does do that and will pass the correct value to ClientForm using
  864. this parameter).
  865. backwards_compat: boolean that determines whether the returned HTMLForm
  866. objects are backwards-compatible with old code. If backwards_compat is
  867. true:
  868. - ClientForm 0.1 code will continue to work as before.
  869. - Label searches that do not specify a nr (number or count) will always
  870. get the first match, even if other controls match. If
  871. backwards_compat is False, label searches that have ambiguous results
  872. will raise an AmbiguityError.
  873. - Item label matching is done by strict string comparison rather than
  874. substring matching.
  875. - De-selecting individual list items is allowed even if the Item is
  876. disabled.
  877. The backwards_compat argument will be deprecated in a future release.
  878. Pass a true value for select_default if you want the behaviour specified by
  879. RFC 1866 (the HTML 2.0 standard), which is to select the first item in a
  880. RADIO or multiple-selection SELECT control if none were selected in the
  881. HTML. Most browsers (including Microsoft Internet Explorer (IE) and
  882. Netscape Navigator) instead leave all items unselected in these cases. The
  883. W3C HTML 4.0 standard leaves this behaviour undefined in the case of
  884. multiple-selection SELECT controls, but insists that at least one RADIO
  885. button should be checked at all times, in contradiction to browser
  886. behaviour.
  887. There is a choice of parsers. ClientForm.XHTMLCompatibleFormParser (uses
  888. HTMLParser.HTMLParser) works best for XHTML, ClientForm.FormParser (uses
  889. sgmllib.SGMLParser) (the default) works better for ordinary grubby HTML.
  890. Note that HTMLParser is only available in Python 2.2 and later. You can
  891. pass your own class in here as a hack to work around bad HTML, but at your
  892. own risk: there is no well-defined interface.
  893. """
  894. return _ParseFileEx(response, response.geturl(), *args, **kwds)[1:]
  895. def ParseFile(file, base_uri, *args, **kwds):
  896. """Parse HTML and return a list of HTMLForm instances.
  897. ClientForm.ParseError is raised on parse errors.
  898. file: file-like object (supporting read() method) containing HTML with zero
  899. or more forms to be parsed
  900. base_uri: the URI of the document (note that the base URI used to submit
  901. the form will be that given in the BASE element if present, not that of
  902. the document)
  903. For the other arguments and further details, see ParseResponse.__doc__.
  904. """
  905. return _ParseFileEx(file, base_uri, *args, **kwds)[1:]
  906. def _ParseFileEx(file, base_uri,
  907. select_default=False,
  908. ignore_errors=False,
  909. form_parser_class=FormParser,
  910. request_class=urllib2.Request,
  911. entitydefs=None,
  912. backwards_compat=True,
  913. encoding=DEFAULT_ENCODING,
  914. _urljoin=urlparse.urljoin,
  915. _urlparse=urlparse.urlparse,
  916. _urlunparse=urlparse.urlunparse,
  917. ):
  918. if backwards_compat:
  919. deprecation("operating in backwards-compatibility mode", 1)
  920. fp = form_parser_class(entitydefs, encoding)
  921. while 1:
  922. data = file.read(CHUNK)
  923. try:
  924. fp.feed(data)
  925. except ParseError, e:
  926. e.base_uri = base_uri
  927. raise
  928. if len(data) != CHUNK: break
  929. fp.close()
  930. if fp.base is not None:
  931. # HTML BASE element takes precedence over document URI
  932. base_uri = fp.base
  933. labels = [] # Label(label) for label in fp.labels]
  934. id_to_labels = {}
  935. for l in fp.labels:
  936. label = Label(l)
  937. labels.append(label)
  938. for_id = l["for"]
  939. coll = id_to_labels.get(for_id)
  940. if coll is None:
  941. id_to_labels[for_id] = [label]
  942. else:
  943. coll.append(label)
  944. forms = []
  945. for (name, action, method, enctype), attrs, controls in fp.forms:
  946. if action is None:
  947. action = base_uri
  948. else:
  949. action = _urljoin(base_uri, action)
  950. # would be nice to make HTMLForm class (form builder) pluggable
  951. form = HTMLForm(
  952. action, method, enctype, name, attrs, request_class,
  953. forms, labels, id_to_labels, backwards_compat)
  954. form._urlparse = _urlparse
  955. form._urlunparse = _urlunparse
  956. for ii in range(len(controls)):
  957. type, name, attrs = controls[ii]
  958. # index=ii*10 allows ImageControl to return multiple ordered pairs
  959. form.new_control(
  960. type, name, attrs, select_default=select_default, index=ii*10)
  961. forms.append(form)
  962. for form in forms:
  963. form.fixup()
  964. return forms
  965. class Label:
  966. def __init__(self, attrs):
  967. self.id = attrs.get("for")
  968. self._text = attrs.get("__text").strip()
  969. self._ctext = compress_text(self._text)
  970. self.attrs = attrs
  971. self._backwards_compat = False # maintained by HTMLForm
  972. def __getattr__(self, name):
  973. if name == "text":
  974. if self._backwards_compat:
  975. return self._text
  976. else:
  977. return self._ctext
  978. return getattr(Label, name)
  979. def __setattr__(self, name, value):
  980. if name == "text":
  981. # don't see any need for this, so make it read-only
  982. raise AttributeError("text attribute is read-only")
  983. self.__dict__[name] = value
  984. def __str__(self):
  985. return "<Label(id=%r, text=%r)>" % (self.id, self.text)
  986. def _get_label(attrs):
  987. text = attrs.get("__label")
  988. if text is not None:
  989. return Label(text)
  990. else:
  991. return None
  992. class Control:
  993. """An HTML form control.
  994. An HTMLForm contains a sequence of Controls. The Controls in an HTMLForm
  995. are accessed using the HTMLForm.find_control method or the
  996. HTMLForm.controls attribute.
  997. Control instances are usually constructed using the ParseFile /
  998. ParseResponse functions. If you use those functions, you can ignore the
  999. rest of this paragraph. A Control is only properly initialised after the
  1000. fixup method has been called. In fact, this is only strictly necessary for
  1001. ListControl instances. This is necessary because ListControls are built up
  1002. from ListControls each containing only a single item, and their initial
  1003. value(s) can only be known after the sequence is complete.
  1004. The types and values that are acceptable for assignment to the value
  1005. attribute are defined by subclasses.
  1006. If the disabled attribute is true, this represents the state typically
  1007. represented by browsers by 'greying out' a control. If the disabled
  1008. attribute is true, the Control will raise AttributeError if an attempt is
  1009. made to change its value. In addition, the control will not be considered
  1010. 'successful' as defined by the W3C HTML 4 standard -- ie. it will
  1011. contribute no data to the return value of the HTMLForm.click* methods. To
  1012. enable a control, set the disabled attribute to a false value.
  1013. If the readonly attribute is true, the Control will raise AttributeError if
  1014. an attempt is made to change its value. To make a control writable, set
  1015. the readonly attribute to a false value.
  1016. All controls have the disabled and readonly attributes, not only those that
  1017. may have the HTML attributes of the same names.
  1018. On assignment to the value attribute, the following exceptions are raised:
  1019. TypeError, AttributeError (if the value attribute should not be assigned
  1020. to, because the control is disabled, for example) and ValueError.
  1021. If the name or value attributes are None, or the value is an empty list, or
  1022. if the control is disabled, the control is not successful.
  1023. Public attributes:
  1024. type: string describing type of control (see the keys of the
  1025. HTMLForm.type2class dictionary for the allowable values) (readonly)
  1026. name: name of control (readonly)
  1027. value: current value of control (subclasses may allow a single value, a
  1028. sequence of values, or either)
  1029. disabled: disabled state
  1030. readonly: readonly state
  1031. id: value of id HTML attribute
  1032. """
  1033. def __init__(self, type, name, attrs, index=None):
  1034. """
  1035. type: string describing type of control (see the keys of the
  1036. HTMLForm.type2class dictionary for the allowable values)
  1037. name: control name
  1038. attrs: HTML attributes of control's HTML element
  1039. """
  1040. raise NotImplementedError()
  1041. def add_to_form(self, form):
  1042. self._form = form
  1043. form.controls.append(self)
  1044. def fixup(self):
  1045. pass
  1046. def is_of_kind(self, kind):
  1047. raise NotImplementedError()
  1048. def clear(self):
  1049. raise NotImplementedError()
  1050. def __getattr__(self, name): raise NotImplementedError()
  1051. def __setattr__(self, name, value): raise NotImplementedError()
  1052. def pairs(self):
  1053. """Return list of (key, value) pairs suitable for passing to urlencode.
  1054. """
  1055. return [(k, v) for (i, k, v) in self._totally_ordered_pairs()]
  1056. def _totally_ordered_pairs(self):
  1057. """Return list of (key, value, index) tuples.
  1058. Like pairs, but allows preserving correct ordering even where several
  1059. controls are involved.
  1060. """
  1061. raise NotImplementedError()
  1062. def _write_mime_data(self, mw, name, value):
  1063. """Write data for a subitem of this control to a MimeWriter."""
  1064. # called by HTMLForm
  1065. mw2 = mw.nextpart()
  1066. mw2.addheader("Content-Disposition",
  1067. 'form-data; name="%s"' % name, 1)
  1068. f = mw2.startbody(prefix=0)
  1069. f.write(value)
  1070. def __str__(self):
  1071. raise NotImplementedError()
  1072. def get_labels(self):
  1073. """Return all labels (Label instances) for this control.
  1074. If the control was surrounded by a <label> tag, that will be the first
  1075. label; all other labels, connected by 'for' and 'id', are in the order
  1076. that appear in the HTML.
  1077. """
  1078. res = []
  1079. if self._label:
  1080. res.append(self._label)
  1081. if self.id:
  1082. res.extend(self._form._id_to_labels.get(self.id, ()))
  1083. return res
  1084. #---------------------------------------------------
  1085. class ScalarControl(Control):
  1086. """Control whose value is not restricted to one of a prescribed set.
  1087. Some ScalarControls don't accept any value attribute. Otherwise, takes a
  1088. single value, which must be string-like.
  1089. Additional read-only public attribute:
  1090. attrs: dictionary mapping the names of original HTML attributes of the
  1091. control to their values
  1092. """
  1093. def __init__(self, type, name, attrs, index=None):
  1094. self._index = index
  1095. self._label = _get_label(attrs)
  1096. self.__dict__["type"] = type.lower()
  1097. self.__dict__["name"] = name
  1098. self._value = attrs.get("value")
  1099. self.disabled = attrs.has_key("disabled")
  1100. self.readonly = attrs.has_key("readonly")
  1101. self.id = attrs.get("id")
  1102. self.attrs = attrs.copy()
  1103. self._clicked = False
  1104. self._urlparse = urlparse.urlparse
  1105. self._urlunparse = urlparse.urlunparse
  1106. def __getattr__(self, name):
  1107. if name == "value":
  1108. return self.__dict__["_value"]
  1109. else:
  1110. raise AttributeError("%s instance has no attribute '%s'" %
  1111. (self.__class__.__name__, name))
  1112. def __setattr__(self, name, value):
  1113. if name == "value":
  1114. if not isstringlike(value):
  1115. raise TypeError("must assign a string")
  1116. elif self.readonly:
  1117. raise AttributeError("control '%s' is readonly" % self.name)
  1118. elif self.disabled:
  1119. raise AttributeError("control '%s' is disabled" % self.name)
  1120. self.__dict__["_value"] = value
  1121. elif name in ("name", "type"):
  1122. raise AttributeError("%s attribute is readonly" % name)
  1123. else:
  1124. self.__dict__[name] = value
  1125. def _totally_ordered_pairs(self):
  1126. name = self.name
  1127. value = self.value
  1128. if name is None or value is None or self.disabled:
  1129. return []
  1130. return [(self._index, name, value)]
  1131. def clear(self):
  1132. if self.readonly:
  1133. raise AttributeError("control '%s' is readonly" % self.name)
  1134. self.__dict__["_value"] = None
  1135. def __str__(self):
  1136. name = self.name
  1137. value = self.value
  1138. if name is None: name = "<None>"
  1139. if value is None: value = "<None>"
  1140. infos = []
  1141. if self.disabled: infos.append("disabled")
  1142. if self.readonly: infos.append("readonly")
  1143. info = ", ".join(infos)
  1144. if info: info = " (%s)" % info
  1145. return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info)
  1146. #---------------------------------------------------
  1147. class TextControl(ScalarControl):
  1148. """Textual input control.
  1149. Covers:
  1150. INPUT/TEXT
  1151. INPUT/PASSWORD
  1152. INPUT/HIDDEN
  1153. TEXTAREA
  1154. """
  1155. def __init__(self, type, name, attrs, index=None):
  1156. ScalarControl.__init__(self, type, name, attrs, index)
  1157. if self.type == "hidden": self.readonly = True
  1158. if self._value is None:
  1159. self._value = ""
  1160. def is_of_kind(self, kind): return kind == "text"
  1161. #---------------------------------------------------
  1162. class FileControl(ScalarControl):
  1163. """File upload with INPUT TYPE=FILE.
  1164. The value attribute of a FileControl is always None. Use add_file instead.
  1165. Additional public method: add_file
  1166. """
  1167. def __init__(self, type, name, attrs, index=None):
  1168. ScalarControl.__init__(self, type, name, attrs, index)
  1169. self._value = None
  1170. self._upload_data = []
  1171. def is_of_kind(self, kind): return kind == "file"
  1172. def clear(self):
  1173. if self.readonly:
  1174. raise AttributeError("control '%s' is readonly" % self.name)
  1175. self._upload_data = []
  1176. def __setattr__(self, name, value):
  1177. if name in ("value", "name", "type"):
  1178. raise AttributeError("%s attribute is readonly" % name)
  1179. else:
  1180. self.__dict__[name] = value
  1181. def add_file(self, file_object, content_type=None, filename=None):
  1182. if not hasattr(file_object, "read"):
  1183. raise TypeError("file-like object must have read method")
  1184. if content_type is not None and not isstringlike(content_type):
  1185. raise TypeError("content type must be None or string-like")
  1186. if filename is not None and not isstringlike(filename):
  1187. raise TypeError("filename must be None or string-like")
  1188. if content_type is None:
  1189. content_type = "application/octet-stream"
  1190. self._upload_data.append((file_object, content_type, filename))
  1191. def _totally_ordered_pairs(self):
  1192. # XXX should it be successful even if unnamed?
  1193. if self.name is None or self.disabled:
  1194. return []
  1195. return [(self._index, self.name, "")]
  1196. def _write_mime_data(self, mw, _name, _value):
  1197. # called by HTMLForm
  1198. # assert _name == self.name and _value == ''
  1199. if len(self._upload_data) < 2:
  1200. if len(self._upload_data) == 0:
  1201. file_object = StringIO()
  1202. content_type = "application/octet-stream"
  1203. filename = ""
  1204. else:
  1205. file_object, content_type, filename = self._upload_data[0]
  1206. if filename is None:
  1207. filename = ""
  1208. mw2 = mw.nextpart()
  1209. fn_part = '; filename="%s"' % filename
  1210. disp = 'form-data; name="%s"%s' % (self.name, fn_part)
  1211. mw2.addheader("Content-Disposition", disp, prefix=1)
  1212. fh = mw2.startbody(content_type, prefix=0)
  1213. fh.write(file_object.read())
  1214. else:
  1215. # multiple files
  1216. mw2 = mw.nextpart()
  1217. disp = 'form-data; name="%s"' % self.name
  1218. mw2.addheader("Content-Disposition", disp, prefix=1)
  1219. fh = mw2.startmultipartbody("mixed", prefix=0)
  1220. for file_object, content_type, filename in self._upload_data:
  1221. mw3 = mw2.nextpart()
  1222. if filename is None:
  1223. filename = ""
  1224. fn_part = '; filename="%s"' % filename
  1225. disp = "file%s" % fn_part
  1226. mw3.addheader("Content-Disposition", disp, prefix=1)
  1227. fh2 = mw3.startbody(content_type, prefix=0)
  1228. fh2.write(file_object.read())
  1229. mw2.lastpart()
  1230. def __str__(self):
  1231. name = self.name
  1232. if name is None: name = "<None>"
  1233. if not self._upload_data:
  1234. value = "<No files added>"
  1235. else:
  1236. value = []
  1237. for file, ctype, filename in self._upload_data:
  1238. if filename is None:
  1239. value.append("<Unnamed file>")
  1240. else:
  1241. value.append(filename)
  1242. value = ", ".join(value)
  1243. info = []
  1244. if self.disabled: info.append("disabled")
  1245. if self.readonly: info.append("readonly")
  1246. info = ", ".join(info)
  1247. if info: info = " (%s)" % info
  1248. return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info)
  1249. #---------------------------------------------------
  1250. class IsindexControl(ScalarControl):
  1251. """ISINDEX control.
  1252. ISINDEX is the odd-one-out of HTML form controls. In fact, it isn't really
  1253. part of regular HTML forms at all, and predates it. You're only allowed
  1254. one ISINDEX per HTML document. ISINDEX and regular form submission are
  1255. mutually exclusive -- either submit a form, or the ISINDEX.
  1256. Having said this, since ISINDEX controls may appear in forms (which is
  1257. probably bad HTML), ParseFile / ParseResponse will include them in the
  1258. HTMLForm instances it returns. You can set the ISINDEX's value, as with
  1259. any other control (but note that ISINDEX controls have no name, so you'll
  1260. need to use the type argument of set_value!). When you submit the form,
  1261. the ISINDEX will not be successful (ie., no data will get returned to the
  1262. server as a result of its presence), unless you click on the ISINDEX
  1263. control, in which case the ISINDEX gets submitted instead of the form:
  1264. form.set_value("my isindex value", type="isindex")
  1265. urllib2.urlopen(form.click(type="isindex"))
  1266. ISINDEX elements outside of FORMs are ignored. If you want to submit one
  1267. by hand, do it like so:
  1268. url = urlparse.urljoin(page_uri, "?"+urllib.quote_plus("my isindex value"))
  1269. result = urllib2.urlopen(url)
  1270. """
  1271. def __init__(self, type, name, attrs, index=None):
  1272. ScalarControl.__init__(self, type, name, attrs, index)
  1273. if self._value is None:
  1274. self._value = ""
  1275. def is_of_kind(self, kind): return kind in ["text", "clickable"]
  1276. def _totally_ordered_pairs(self):
  1277. return []
  1278. def _click(self, form, coord, return_type, request_class=urllib2.Request):
  1279. # Relative URL for ISINDEX submission: instead of "foo=bar+baz",
  1280. # want "bar+baz".
  1281. # This doesn't seem to be specified in HTML 4.01 spec. (ISINDEX is
  1282. # deprecated in 4.01, but it should still say how to submit it).
  1283. # Submission of ISINDEX is explained in the HTML 3.2 spec, though.
  1284. parts = self._urlparse(form.action)
  1285. rest, (query, frag) = parts[:-2], parts[-2:]
  1286. parts = rest + (urllib.quote_plus(self.value), None)
  1287. url = self._urlunparse(parts)
  1288. req_data = url, None, []
  1289. if return_type == "pairs":
  1290. return []
  1291. elif return_type == "request_data":
  1292. return req_data
  1293. else:
  1294. return request_class(url)
  1295. def __str__(self):
  1296. value = self.value
  1297. if value is None: value = "<None>"
  1298. infos = []
  1299. if self.disabled: infos.append("disabled")
  1300. if self.readonly: infos.append("readonly")
  1301. info = ", ".join(infos)
  1302. if info: info = " (%s)" % info
  1303. return "<%s(%s)%s>" % (self.__class__.__name__, value, info)
  1304. #---------------------------------------------------
  1305. class IgnoreControl(ScalarControl):
  1306. """Control that we're not interested in.
  1307. Covers:
  1308. INPUT/RESET
  1309. BUTTON/RESET
  1310. INPUT/BUTTON
  1311. BUTTON/BUTTON
  1312. These controls are always unsuccessful, in the terminology of HTML 4 (ie.
  1313. they never require any information to be returned to the server).
  1314. BUTTON/BUTTON is used to generate events for script embedded in HTML.
  1315. The value attribute of IgnoreControl is always None.
  1316. """
  1317. def __init__(self, type, name, attrs, index=None):
  1318. ScalarControl.__init__(self, type, name, attrs, index)
  1319. self._value = None
  1320. def is_of_kind(self, kind): return False
  1321. def __setattr__(self, name, value):
  1322. if name == "value":
  1323. raise AttributeError(
  1324. "control '%s' is ignored, hence read-only" % self.name)
  1325. elif name in ("name", "type"):
  1326. raise AttributeError("%s attribute is readonly" % name)
  1327. else:
  1328. self.__dict__[name] = value
  1329. #---------------------------------------------------
  1330. # ListControls
  1331. # helpers and subsidiary classes
  1332. class Item:
  1333. def __init__(self, control, attrs, index=None):
  1334. label = _get_label(attrs)
  1335. self.__dict__.update({
  1336. "name": attrs["value"],
  1337. "_labels": label and [label] or [],
  1338. "attrs": attrs,
  1339. "_control": control,
  1340. "disabled": attrs.has_key("disabled"),
  1341. "_selected": False,
  1342. "id": attrs.get("id"),
  1343. "_index": index,
  1344. })
  1345. control.items.append(self)
  1346. def get_labels(self):
  1347. """Return all labels (Label instances) for this item.
  1348. For items that represent radio buttons or checkboxes, if the item was
  1349. surrounded by a <label> tag, that will be the first label; all other
  1350. labels, connected by 'for' and 'id', are in the order that appear in
  1351. the HTML.
  1352. For items that represent select options, if the option had a label
  1353. attribute, that will be the first label. If the option has contents
  1354. (text within the option tags) and it is not the same as the label
  1355. attribute (if any), that will be a label. There is nothing in the
  1356. spec to my knowledge that makes an option with an id unable to be the
  1357. target of a label's for attribute, so those are included, if any, for
  1358. the sake of consistency and completeness.
  1359. """
  1360. res = []
  1361. res.extend(self._labels)
  1362. if self.id:
  1363. res.extend(self._control._form._id_to_labels.get(self.id, ()))
  1364. return res
  1365. def __getattr__(self, name):
  1366. if name=="selected":
  1367. return self._selected
  1368. raise AttributeError(name)
  1369. def __setattr__(self, name, value):
  1370. if name == "selected":
  1371. self._control._set_selected_state(self, value)
  1372. elif name == "disabled":
  1373. self.__dict__["disabled"] = bool(value)
  1374. else:
  1375. raise AttributeError(name)
  1376. def __str__(self):
  1377. res = self.name
  1378. if self.selected:
  1379. res = "*" + res
  1380. if self.disabled:
  1381. res = "(%s)" % res
  1382. return res
  1383. def __repr__(self):
  1384. # XXX appending the attrs without distinguishing them from name and id
  1385. # is silly
  1386. attrs = [("name", self.name), ("id", self.id)]+self.attrs.items()
  1387. return "<%s %s>" % (
  1388. self.__class__.__name__,
  1389. " ".join(["%s=%r" % (k, v) for k, v in attrs])
  1390. )
  1391. def disambiguate(items, nr, **kwds):
  1392. msgs = []
  1393. for key, value in kwds.items():
  1394. msgs.append("%s=%r" % (key, value))
  1395. msg = " ".join(msgs)
  1396. if not items:
  1397. raise ItemNotFoundError(msg)
  1398. if nr is None:
  1399. if len(items) > 1:
  1400. raise AmbiguityError(msg)
  1401. nr = 0
  1402. if len(items) <= nr:
  1403. raise ItemNotFoundError(msg)
  1404. return items[nr]
  1405. class ListControl(Control):
  1406. """Control representing a sequence of items.
  1407. The value attribute of a ListControl represents the successful list items
  1408. in the control. The successful list items are those that are selected and
  1409. not disabled.
  1410. ListControl implements both list controls that take a length-1 value
  1411. (single-selection) and those that take length >1 values
  1412. (multiple-selection).
  1413. ListControls accept sequence values only. Some controls only accept
  1414. sequences of length 0 or 1 (RADIO, and single-selection SELECT).
  1415. In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes
  1416. and multiple-selection SELECTs (those having the "multiple" HTML attribute)
  1417. accept sequences of any length.
  1418. Note the following mistake:
  1419. control.value = some_value
  1420. assert control.value == some_value # not necessarily true
  1421. The reason for this is that the value attribute always gives the list items
  1422. in the order they were listed in the HTML.
  1423. ListControl items can also be referred to by their labels instead of names.
  1424. Use the label argument to .get(), and the .set_value_by_label(),
  1425. .get_value_by_label() methods.
  1426. Note that, rather confusingly, though SELECT controls are represented in
  1427. HTML by SELECT elements (which contain OPTION elements, representing
  1428. individual list items), CHECKBOXes and RADIOs are not represented by *any*
  1429. element. Instead, those controls are represented by a collection of INPUT
  1430. elements. For example, this is a SELECT control, named "control1":
  1431. <select name="control1">
  1432. <option>foo</option>
  1433. <option value="1">bar</option>
  1434. </select>
  1435. and this is a CHECKBOX control, named "control2":
  1436. <input type="checkbox" name="control2" value="foo" id="cbe1">
  1437. <input type="checkbox" name="control2" value="bar" id="cbe2">
  1438. The id attribute of a CHECKBOX or RADIO ListControl is always that of its
  1439. first element (for example, "cbe1" above).
  1440. Additional read-only public attribute: multiple.
  1441. """
  1442. # ListControls are built up by the parser from their component items by
  1443. # creating one ListControl per item, consolidating them into a single
  1444. # master ListControl held by the HTMLForm:
  1445. # -User calls form.new_control(...)
  1446. # -Form creates Control, and calls control.add_to_form(self).
  1447. # -Control looks for a Control with the same name and type in the form,
  1448. # and if it finds one, merges itself with that control by calling
  1449. # control.merge_control(self). The first Control added to the form, of
  1450. # a particular name and type, is the only one that survives in the
  1451. # form.
  1452. # -Form calls control.fixup for all its controls. ListControls in the
  1453. # form know they can now safely pick their default values.
  1454. # To create a ListControl without an HTMLForm, use:
  1455. # control.merge_control(new_control)
  1456. # (actually, it's much easier just to use ParseFile)
  1457. _label = None
  1458. def __init__(self, type, name, attrs={}, select_default=False,
  1459. called_as_base_class=False, index=None):
  1460. """
  1461. select_default: for RADIO and multiple-selection SELECT controls, pick
  1462. the first item as the default if no 'selected' HTML attribute is
  1463. present
  1464. """
  1465. if not called_as_base_class:
  1466. raise NotImplementedError()
  1467. self.__dict__["type"] = type.lower()
  1468. self.__dict__["name"] = name
  1469. self._value = attrs.get("value")
  1470. self.disabled = False
  1471. self.readonly = False
  1472. self.id = attrs.get("id")
  1473. self._closed = False
  1474. # As Controls are merged in with .merge_control(), self.attrs will
  1475. # refer to each Control in turn -- always the most recently merged
  1476. # control. Each merged-in Control instance corresponds to a single
  1477. # list item: see ListControl.__doc__.
  1478. self.items = []
  1479. self._form = None
  1480. self._select_default = select_default
  1481. self._clicked = False
  1482. def clear(self):
  1483. self.value = []
  1484. def is_of_kind(self, kind):
  1485. if kind == "list":
  1486. return True
  1487. elif kind == "multilist":
  1488. return bool(self.multiple)
  1489. elif kind == "singlelist":
  1490. return not self.multiple
  1491. else:
  1492. return False
  1493. def get_items(self, name=None, label=None, id=None,
  1494. exclude_disabled=False):
  1495. """Return matching items by name or label.
  1496. For argument docs, see the docstring for .get()
  1497. """
  1498. if name is not None and not isstringlike(name):
  1499. raise TypeError("item name must be string-like")
  1500. if label is not None and not isstringlike(label):
  1501. raise TypeError("item label must be string-like")
  1502. if id is not None and not isstringlike(id):
  1503. raise TypeError("item id must be string-like")
  1504. items = [] # order is important
  1505. compat = self._form.backwards_compat
  1506. for o in self.items:
  1507. if exclude_disabled and o.disabled:
  1508. continue
  1509. if name is not None and o.name != name:
  1510. continue
  1511. if label is not None:
  1512. for l in o.get_labels():
  1513. if ((compat and l.text == label) or
  1514. (not compat and l.text.find(label) > -1)):
  1515. break
  1516. else:
  1517. continue
  1518. if id is not None and o.id != id:
  1519. continue
  1520. items.append(o)
  1521. return items
  1522. def get(self, name=None, label=None, id=None, nr=None,
  1523. exclude_disabled=False):
  1524. """Return item by name or label, disambiguating if necessary with nr.
  1525. All arguments must be passed by name, with the exception of 'name',
  1526. which may be used as a positional argument.
  1527. If name is specified, then the item must have the indicated name.
  1528. If label is specified, then the item must have a label whose
  1529. whitespace-compressed, stripped, text substring-matches the indicated
  1530. label string (eg. label="please choose" will match
  1531. " Do please choose an item ").
  1532. If id is specified, then the item must have the indicated id.
  1533. nr is an optional 0-based index of the items matching the query.
  1534. If nr is the default None value and more than item is found, raises
  1535. AmbiguityError (unless the HTMLForm instance's backwards_compat
  1536. attribute is true).
  1537. If no item is found, or if items are found but nr is specified and not
  1538. found, raises ItemNotFoundError.
  1539. Optionally excludes disabled items.
  1540. """
  1541. if nr is None and self._form.backwards_compat:
  1542. nr = 0 # :-/
  1543. items = self.get_items(name, label, id, exclude_disabled)
  1544. return disambiguate(items, nr, name=name, label=label, id=id)
  1545. def _get(self, name, by_label=False, nr=None, exclude_disabled=False):
  1546. # strictly for use by deprecated methods
  1547. if by_label:
  1548. name, label = None, name
  1549. else:
  1550. name, label = name, None
  1551. return self.get(name, label, nr, exclude_disabled)
  1552. def toggle(self, name, by_label=False, nr=None):
  1553. """Deprecated: given a name or label and optional disambiguating index
  1554. nr, toggle the matching item's selection.
  1555. Selecting items follows the behavior described in the docstring of the
  1556. 'get' method.
  1557. if the item is disabled, or this control is disabled or readonly,
  1558. raise AttributeError.
  1559. """
  1560. deprecation(
  1561. "item = control.get(...); item.selected = not item.selected")
  1562. o = self._get(name, by_label, nr)
  1563. self._set_selected_state(o, not o.selected)
  1564. def set(self, selected, name, by_label=False, nr=None):
  1565. """Deprecated: given a name or label and optional disambiguating index
  1566. nr, set the matching item's selection to the bool value of selected.
  1567. Selecting items follows the behavior described in the docstring of the
  1568. 'get' method.
  1569. if the item is disabled, or this control is disabled or readonly,
  1570. raise AttributeError.
  1571. """
  1572. deprecation(
  1573. "control.get(...).selected = <boolean>")
  1574. self._set_selected_state(self._get(name, by_label, nr), selected)
  1575. def _set_selected_state(self, item, action):
  1576. # action:
  1577. # bool False: off
  1578. # bool True: on
  1579. if self.disabled:
  1580. raise AttributeError("control '%s' is disabled" % self.name)
  1581. if self.readonly:
  1582. raise AttributeError("control '%s' is readonly" % self.name)
  1583. action == bool(action)
  1584. compat = self._form.backwards_compat
  1585. if not compat and item.disabled:
  1586. raise AttributeError("item is disabled")
  1587. else:
  1588. if compat and item.disabled and action:
  1589. raise AttributeError("item is disabled")
  1590. if self.multiple:
  1591. item.__dict__["_selected"] = action
  1592. else:
  1593. if not action:
  1594. item.__dict__["_selected"] = False
  1595. else:
  1596. for o in self.items:
  1597. o.__dict__["_selected"] = False
  1598. item.__dict__["_selected"] = True
  1599. def toggle_single(self, by_label=None):
  1600. """Deprecated: toggle the selection of the single item in this control.
  1601. Raises ItemCountError if the control does not contain only one item.
  1602. by_label argument is ignored, and included only for backwards
  1603. compatibility.
  1604. """
  1605. deprecation(
  1606. "control.items[0].selected = not control.items[0].selected")
  1607. if len(self.items) != 1:
  1608. raise ItemCountError(
  1609. "'%s' is not a single-item control" % self.name)
  1610. item = self.items[0]
  1611. self._set_selected_state(item, not item.selected)
  1612. def set_single(self, selected, by_label=None):
  1613. """Deprecated: set the selection of the single item in this control.
  1614. Raises ItemCountError if the control does not contain only one item.
  1615. by_label argument is ignored, and included only for backwards
  1616. compatibility.
  1617. """
  1618. deprecation(
  1619. "control.items[0].selected = <boolean>")
  1620. if len(self.items) != 1:
  1621. raise ItemCountError(
  1622. "'%s' is not a single-item control" % self.name)
  1623. self._set_selected_state(self.items[0], selected)
  1624. def get_item_disabled(self, name, by_label=False, nr=None):
  1625. """Get disabled state of named list item in a ListControl."""
  1626. deprecation(
  1627. "control.get(...).disabled")
  1628. return self._get(name, by_label, nr).disabled
  1629. def set_item_disabled(self, disabled, name, by_label=False, nr=None):
  1630. """Set disabled state of named list item in a ListControl.
  1631. disabled: boolean disabled state
  1632. """
  1633. deprecation(
  1634. "control.get(...).disabled = <boolean>")
  1635. self._get(name, by_label, nr).disabled = disabled
  1636. def set_all_items_disabled(self, disabled):
  1637. """Set disabled state of all list items in a ListControl.
  1638. disabled: boolean disabled state
  1639. """
  1640. for o in self.items:
  1641. o.disabled = disabled
  1642. def get_item_attrs(self, name, by_label=False, nr=None):
  1643. """Return dictionary of HTML attributes for a single ListControl item.
  1644. The HTML element types that describe list items are: OPTION for SELECT
  1645. controls, INPUT for the rest. These elements have HTML attributes that
  1646. you may occasionally want to know about -- for example, the "alt" HTML
  1647. attribute gives a text string describing the item (graphical browsers
  1648. usually display this as a tooltip).
  1649. The returned dictionary maps HTML attribute names to values. The names
  1650. and values are taken from the original HTML.
  1651. """
  1652. deprecation(
  1653. "control.get(...).attrs")
  1654. return self._get(name, by_label, nr).attrs
  1655. def close_control(self):
  1656. self._closed = True
  1657. def add_to_form(self, form):
  1658. assert self._form is None or form == self._form, (
  1659. "can't add control to more than one form")
  1660. self._form = form
  1661. if self.name is None:
  1662. # always count nameless elements as separate controls
  1663. Control.add_to_form(self, form)
  1664. else:
  1665. for ii in range(len(form.controls)-1, -1, -1):
  1666. control = form.controls[ii]
  1667. if control.name == self.name and control.type == self.type:
  1668. if control._closed:
  1669. Control.add_to_form(self, form)
  1670. else:
  1671. control.merge_control(self)
  1672. break
  1673. else:
  1674. Control.add_to_form(self, form)
  1675. def merge_control(self, control):
  1676. assert bool(control.multiple) == bool(self.multiple)
  1677. # usually, isinstance(control, self.__class__)
  1678. self.items.extend(control.items)
  1679. def fixup(self):
  1680. """
  1681. ListControls are built up from component list items (which are also
  1682. ListControls) during parsing. This method should be called after all
  1683. items have been added. See ListControl.__doc__ for the reason this is
  1684. required.
  1685. """
  1686. # Need to set default selection where no item was indicated as being
  1687. # selected by the HTML:
  1688. # CHECKBOX:
  1689. # Nothing should be selected.
  1690. # SELECT/single, SELECT/multiple and RADIO:
  1691. # RFC 1866 (HTML 2.0): says first item should be selected.
  1692. # W3C HTML 4.01 Specification: says that client behaviour is
  1693. # undefined in this case. For RADIO, exactly one must be selected,
  1694. # though which one is undefined.
  1695. # Both Netscape and Microsoft Internet Explorer (IE) choose first
  1696. # item for SELECT/single. However, both IE5 and Mozilla (both 1.0
  1697. # and Firebird 0.6) leave all items unselected for RADIO and
  1698. # SELECT/multiple.
  1699. # Since both Netscape and IE all choose the first item for
  1700. # SELECT/single, we do the same. OTOH, both Netscape and IE
  1701. # leave SELECT/multiple with nothing selected, in violation of RFC 1866
  1702. # (but not in violation of the W3C HTML 4 standard); the same is true
  1703. # of RADIO (which *is* in violation of the HTML 4 standard). We follow
  1704. # RFC 1866 if the _select_default attribute is set, and Netscape and IE
  1705. # otherwise. RFC 1866 and HTML 4 are always violated insofar as you
  1706. # can deselect all items in a RadioControl.
  1707. for o in self.items:
  1708. # set items' controls to self, now that we've merged
  1709. o.__dict__["_control"] = self
  1710. def __getattr__(self, name):
  1711. if name == "value":
  1712. compat = self._form.backwards_compat
  1713. if self.name is None:
  1714. return []
  1715. return [o.name for o in self.items if o.selected and
  1716. (not o.disabled or compat)]
  1717. else:
  1718. raise AttributeError("%s instance has no attribute '%s'" %
  1719. (self.__class__.__name__, name))
  1720. def __setattr__(self, name, value):
  1721. if name == "value":
  1722. if self.disabled:
  1723. raise AttributeError("control '%s' is disabled" % self.name)
  1724. if self.readonly:
  1725. raise AttributeError("control '%s' is readonly" % self.name)
  1726. self._set_value(value)
  1727. elif name in ("name", "type", "multiple"):
  1728. raise AttributeError("%s attribute is readonly" % name)
  1729. else:
  1730. self.__dict__[name] = value
  1731. def _set_value(self, value):
  1732. if value is None or isstringlike(value):
  1733. raise TypeError("ListControl, must set a sequence")
  1734. if not value:
  1735. compat = self._form.backwards_compat
  1736. for o in self.items:
  1737. if not o.disabled or compat:
  1738. o.selected = False
  1739. elif self.multiple:
  1740. self._multiple_set_value(value)
  1741. elif len(value) > 1:
  1742. raise ItemCountError(
  1743. "single selection list, must set sequence of "
  1744. "length 0 or 1")
  1745. else:
  1746. self._single_set_value(value)
  1747. def _get_items(self, name, target=1):
  1748. all_items = self.get_items(name)
  1749. items = [o for o in all_items if not o.disabled]
  1750. if len(items) < target:
  1751. if len(all_items) < target:
  1752. raise ItemNotFoundError(
  1753. "insufficient items with name %r" % name)
  1754. else:
  1755. raise AttributeError(
  1756. "insufficient non-disabled items with name %s" % name)
  1757. on = []
  1758. off = []
  1759. for o in items:
  1760. if o.selected:
  1761. on.append(o)
  1762. else:
  1763. off.append(o)
  1764. return on, off
  1765. def _single_set_value(self, value):
  1766. assert len(value) == 1
  1767. on, off = self._get_items(value[0])
  1768. assert len(on) <= 1
  1769. if not on:
  1770. off[0].selected = True
  1771. def _multiple_set_value(self, value):
  1772. compat = self._form.backwards_compat
  1773. turn_on = [] # transactional-ish
  1774. turn_off = [item for item in self.items if
  1775. item.selected and (not item.disabled or compat)]
  1776. names = {}
  1777. for nn in value:
  1778. if nn in names.keys():
  1779. names[nn] += 1
  1780. else:
  1781. names[nn] = 1
  1782. for name, count in names.items():
  1783. on, off = self._get_items(name, count)
  1784. for i in range(count):
  1785. if on:
  1786. item = on[0]
  1787. del on[0]
  1788. del turn_off[turn_off.index(item)]
  1789. else:
  1790. item = off[0]
  1791. del off[0]
  1792. turn_on.append(item)
  1793. for item in turn_off:
  1794. item.selected = False
  1795. for item in turn_on:
  1796. item.selected = True
  1797. def set_value_by_label(self, value):
  1798. """Set the value of control by item labels.
  1799. value is expected to be an iterable of strings that are substrings of
  1800. the item labels that should be selected. Before substring matching is
  1801. performed, the original label text is whitespace-compressed
  1802. (consecutive whitespace characters are converted to a single space
  1803. character) and leading and trailing whitespace is stripped. Ambiguous
  1804. labels are accepted without complaint if the form's backwards_compat is
  1805. True; otherwise, it will not complain as long as all ambiguous labels
  1806. share the same item name (e.g. OPTION value).
  1807. """
  1808. if isstringlike(value):
  1809. raise TypeError(value)
  1810. if not self.multiple and len(value) > 1:
  1811. raise ItemCountError(
  1812. "single selection list, must set sequence of "
  1813. "length 0 or 1")
  1814. items = []
  1815. for nn in value:
  1816. found = self.get_items(label=nn)
  1817. if len(found) > 1:
  1818. if not self._form.backwards_compat:
  1819. # ambiguous labels are fine as long as item names (e.g.
  1820. # OPTION values) are same
  1821. opt_name = found[0].name
  1822. if [o for o in found[1:] if o.name != opt_name]:
  1823. raise AmbiguityError(nn)
  1824. else:
  1825. # OK, we'll guess :-( Assume first available item.
  1826. found = found[:1]
  1827. for o in found:
  1828. # For the multiple-item case, we could try to be smarter,
  1829. # saving them up and trying to resolve, but that's too much.
  1830. if self._form.backwards_compat or o not in items:
  1831. items.append(o)
  1832. break
  1833. else: # all of them are used
  1834. raise ItemNotFoundError(nn)
  1835. # now we have all the items that should be on
  1836. # let's just turn everything off and then back on.
  1837. self.value = []
  1838. for o in items:
  1839. o.selected = True
  1840. def get_value_by_label(self):
  1841. """Return the value of the control as given by normalized labels."""
  1842. res = []
  1843. compat = self._form.backwards_compat
  1844. for o in self.items:
  1845. if (not o.disabled or compat) and o.selected:
  1846. for l in o.get_labels():
  1847. if l.text:
  1848. res.append(l.text)
  1849. break
  1850. else:
  1851. res.append(None)
  1852. return res
  1853. def possible_items(self, by_label=False):
  1854. """Deprecated: return the names or labels of all possible items.
  1855. Includes disabled items, which may be misleading for some use cases.
  1856. """
  1857. deprecation(
  1858. "[item.name for item in self.items]")
  1859. if by_label:
  1860. res = []
  1861. for o in self.items:
  1862. for l in o.get_labels():
  1863. if l.text:
  1864. res.append(l.text)
  1865. break
  1866. else:
  1867. res.append(None)
  1868. return res
  1869. return [o.name for o in self.items]
  1870. def _totally_ordered_pairs(self):
  1871. if self.disabled or self.name is None:
  1872. return []
  1873. else:
  1874. return [(o._index, self.name, o.name) for o in self.items
  1875. if o.selected and not o.disabled]
  1876. def __str__(self):
  1877. name = self.name
  1878. if name is None: name = "<None>"
  1879. display = [str(o) for o in self.items]
  1880. infos = []
  1881. if self.disabled: infos.append("disabled")
  1882. if self.readonly: infos.append("readonly")
  1883. info = ", ".join(infos)
  1884. if info: info = " (%s)" % info
  1885. return "<%s(%s=[%s])%s>" % (self.__class__.__name__,
  1886. name, ", ".join(display), info)
  1887. class RadioControl(ListControl):
  1888. """
  1889. Covers:
  1890. INPUT/RADIO
  1891. """
  1892. def __init__(self, type, name, attrs, select_default=False, index=None):
  1893. attrs.setdefault("value", "on")
  1894. ListControl.__init__(self, type, name, attrs, select_default,
  1895. called_as_base_class=True, index=index)
  1896. self.__dict__["multiple"] = False
  1897. o = Item(self, attrs, index)
  1898. o.__dict__["_selected"] = attrs.has_key("checked")
  1899. def fixup(self):
  1900. ListControl.fixup(self)
  1901. found = [o for o in self.items if o.selected and not o.disabled]
  1902. if not found:
  1903. if self._select_default:
  1904. for o in self.items:
  1905. if not o.disabled:
  1906. o.selected = True
  1907. break
  1908. else:
  1909. # Ensure only one item selected. Choose the last one,
  1910. # following IE and Firefox.
  1911. for o in found[:-1]:
  1912. o.selected = False
  1913. def get_labels(self):
  1914. return []
  1915. class CheckboxControl(ListControl):
  1916. """
  1917. Covers:
  1918. INPUT/CHECKBOX
  1919. """
  1920. def __init__(self, type, name, attrs, select_default=False, index=None):
  1921. attrs.setdefault("value", "on")
  1922. ListControl.__init__(self, type, name, attrs, select_default,
  1923. called_as_base_class=True, index=index)
  1924. self.__dict__["multiple"] = True
  1925. o = Item(self, attrs, index)
  1926. o.__dict__["_selected"] = attrs.has_key("checked")
  1927. def get_labels(self):
  1928. return []
  1929. class SelectControl(ListControl):
  1930. """
  1931. Covers:
  1932. SELECT (and OPTION)
  1933. OPTION 'values', in HTML parlance, are Item 'names' in ClientForm parlance.
  1934. SELECT control values and labels are subject to some messy defaulting
  1935. rules. For example, if the HTML representation of the control is:
  1936. <SELECT name=year>
  1937. <OPTION value=0 label="2002">current year</OPTION>
  1938. <OPTION value=1>2001</OPTION>
  1939. <OPTION>2000</OPTION>
  1940. </SELECT>
  1941. The items, in order, have labels "2002", "2001" and "2000", whereas their
  1942. names (the OPTION values) are "0", "1" and "2000" respectively. Note that
  1943. the value of the last OPTION in this example defaults to its contents, as
  1944. specified by RFC 1866, as do the labels of the second and third OPTIONs.
  1945. The OPTION labels are sometimes more meaningful than the OPTION values,
  1946. which can make for more maintainable code.
  1947. Additional read-only public attribute: attrs
  1948. The attrs attribute is a dictionary of the original HTML attributes of the
  1949. SELECT element. Other ListControls do not have this attribute, because in
  1950. other cases the control as a whole does not correspond to any single HTML
  1951. element. control.get(...).attrs may be used as usual to get at the HTML
  1952. attributes of the HTML elements corresponding to individual list items (for
  1953. SELECT controls, these are OPTION elements).
  1954. Another special case is that the Item.attrs dictionaries have a special key
  1955. "contents" which does not correspond to any real HTML attribute, but rather
  1956. contains the contents of the OPTION element:
  1957. <OPTION>this bit</OPTION>
  1958. """
  1959. # HTML attributes here are treated slightly differently from other list
  1960. # controls:
  1961. # -The SELECT HTML attributes dictionary is stuffed into the OPTION
  1962. # HTML attributes dictionary under the "__select" key.
  1963. # -The content of each OPTION element is stored under the special
  1964. # "contents" key of the dictionary.
  1965. # After all this, the dictionary is passed to the SelectControl constructor
  1966. # as the attrs argument, as usual. However:
  1967. # -The first SelectControl constructed when building up a SELECT control
  1968. # has a constructor attrs argument containing only the __select key -- so
  1969. # this SelectControl represents an empty SELECT control.
  1970. # -Subsequent SelectControls have both OPTION HTML-attribute in attrs and
  1971. # the __select dictionary containing the SELECT HTML-attributes.
  1972. def __init__(self, type, name, attrs, select_default=False, index=None):
  1973. # fish out the SELECT HTML attributes from the OPTION HTML attributes
  1974. # dictionary
  1975. self.attrs = attrs["__select"].copy()
  1976. self.__dict__["_label"] = _get_label(self.attrs)
  1977. self.__dict__["id"] = self.attrs.get("id")
  1978. self.__dict__["multiple"] = self.attrs.has_key("multiple")
  1979. # the majority of the contents, label, and value dance already happened
  1980. contents = attrs.get("contents")
  1981. attrs = attrs.copy()
  1982. del attrs["__select"]
  1983. ListControl.__init__(self, type, name, self.attrs, select_default,
  1984. called_as_base_class=True, index=index)
  1985. self.disabled = self.attrs.has_key("disabled")
  1986. self.readonly = self.attrs.has_key("readonly")
  1987. if attrs.has_key("value"):
  1988. # otherwise it is a marker 'select started' token
  1989. o = Item(self, attrs, index)
  1990. o.__dict__["_selected"] = attrs.has_key("selected")
  1991. # add 'label' label and contents label, if different. If both are
  1992. # provided, the 'label' label is used for display in HTML
  1993. # 4.0-compliant browsers (and any lower spec? not sure) while the
  1994. # contents are used for display in older or less-compliant
  1995. # browsers. We make label objects for both, if the values are
  1996. # different.
  1997. label = attrs.get("label")
  1998. if label:
  1999. o._labels.append(Label({"__text": label}))
  2000. if contents and contents != label:
  2001. o._labels.append(Label({"__text": contents}))
  2002. elif contents:
  2003. o._labels.append(Label({"__text": contents}))
  2004. def fixup(self):
  2005. ListControl.fixup(self)
  2006. # Firefox doesn't exclude disabled items from those considered here
  2007. # (i.e. from 'found', for both branches of the if below). Note that
  2008. # IE6 doesn't support the disabled attribute on OPTIONs at all.
  2009. found = [o for o in self.items if o.selected]
  2010. if not found:
  2011. if not self.multiple or self._select_default:
  2012. for o in self.items:
  2013. if not o.disabled:
  2014. was_disabled = self.disabled
  2015. self.disabled = False
  2016. try:
  2017. o.selected = True
  2018. finally:
  2019. o.disabled = was_disabled
  2020. break
  2021. elif not self.multiple:
  2022. # Ensure only one item selected. Choose the last one,
  2023. # following IE and Firefox.
  2024. for o in found[:-1]:
  2025. o.selected = False
  2026. #---------------------------------------------------
  2027. class SubmitControl(ScalarControl):
  2028. """
  2029. Covers:
  2030. INPUT/SUBMIT
  2031. BUTTON/SUBMIT
  2032. """
  2033. def __init__(self, type, name, attrs, index=None):
  2034. ScalarControl.__init__(self, type, name, attrs, index)
  2035. # IE5 defaults SUBMIT value to "Submit Query"; Firebird 0.6 leaves it
  2036. # blank, Konqueror 3.1 defaults to "Submit". HTML spec. doesn't seem
  2037. # to define this.
  2038. if self.value is None: self.value = ""
  2039. self.readonly = True
  2040. def get_labels(self):
  2041. res = []
  2042. if self.value:
  2043. res.append(Label({"__text": self.value}))
  2044. res.extend(ScalarControl.get_labels(self))
  2045. return res
  2046. def is_of_kind(self, kind): return kind == "clickable"
  2047. def _click(self, form, coord, return_type, request_class=urllib2.Request):
  2048. self._clicked = coord
  2049. r = form._switch_click(return_type, request_class)
  2050. self._clicked = False
  2051. return r
  2052. def _totally_ordered_pairs(self):
  2053. if not self._clicked:
  2054. return []
  2055. return ScalarControl._totally_ordered_pairs(self)
  2056. #---------------------------------------------------
  2057. class ImageControl(SubmitControl):
  2058. """
  2059. Covers:
  2060. INPUT/IMAGE
  2061. Coordinates are specified using one of the HTMLForm.click* methods.
  2062. """
  2063. def __init__(self, type, name, attrs, index=None):
  2064. SubmitControl.__init__(self, type, name, attrs, index)
  2065. self.readonly = False
  2066. def _totally_ordered_pairs(self):
  2067. clicked = self._clicked
  2068. if self.disabled or not clicked:
  2069. return []
  2070. name = self.name
  2071. if name is None: return []
  2072. pairs = [
  2073. (self._index, "%s.x" % name, str(clicked[0])),
  2074. (self._index+1, "%s.y" % name, str(clicked[1])),
  2075. ]
  2076. value = self._value
  2077. if value:
  2078. pairs.append((self._index+2, name, value))
  2079. return pairs
  2080. get_labels = ScalarControl.get_labels
  2081. # aliases, just to make str(control) and str(form) clearer
  2082. class PasswordControl(TextControl): pass
  2083. class HiddenControl(TextControl): pass
  2084. class TextareaControl(TextControl): pass
  2085. class SubmitButtonControl(SubmitControl): pass
  2086. def is_listcontrol(control): return control.is_of_kind("list")
  2087. class HTMLForm:
  2088. """Represents a single HTML <form> ... </form> element.
  2089. A form consists of a sequence of controls that usually have names, and
  2090. which can take on various values. The values of the various types of
  2091. controls represent variously: text, zero-or-one-of-many or many-of-many
  2092. choices, and files to be uploaded. Some controls can be clicked on to
  2093. submit the form, and clickable controls' values sometimes include the
  2094. coordinates of the click.
  2095. Forms can be filled in with data to be returned to the server, and then
  2096. submitted, using the click method to generate a request object suitable for
  2097. passing to urllib2.urlopen (or the click_request_data or click_pairs
  2098. methods if you're not using urllib2).
  2099. import ClientForm
  2100. forms = ClientForm.ParseFile(html, base_uri)
  2101. form = forms[0]
  2102. form["query"] = "Python"
  2103. form.find_control("nr_results").get("lots").selected = True
  2104. response = urllib2.urlopen(form.click())
  2105. Usually, HTMLForm instances are not created directly. Instead, the
  2106. ParseFile or ParseResponse factory functions are used. If you do construct
  2107. HTMLForm objects yourself, however, note that an HTMLForm instance is only
  2108. properly initialised after the fixup method has been called (ParseFile and
  2109. ParseResponse do this for you). See ListControl.__doc__ for the reason
  2110. this is required.
  2111. Indexing a form (form["control_name"]) returns the named Control's value
  2112. attribute. Assignment to a form index (form["control_name"] = something)
  2113. is equivalent to assignment to the named Control's value attribute. If you
  2114. need to be more specific than just supplying the control's name, use the
  2115. set_value and get_value methods.
  2116. ListControl values are lists of item names (specifically, the names of the
  2117. items that are selected and not disabled, and hence are "successful" -- ie.
  2118. cause data to be returned to the server). The list item's name is the
  2119. value of the corresponding HTML element's"value" attribute.
  2120. Example:
  2121. <INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT>
  2122. <INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT>
  2123. defines a CHECKBOX control with name "cheeses" which has two items, named
  2124. "leicester" and "cheddar".
  2125. Another example:
  2126. <SELECT name="more_cheeses">
  2127. <OPTION>1</OPTION>
  2128. <OPTION value="2" label="CHEDDAR">cheddar</OPTION>
  2129. </SELECT>
  2130. defines a SELECT control with name "more_cheeses" which has two items,
  2131. named "1" and "2" (because the OPTION element's value HTML attribute
  2132. defaults to the element contents -- see SelectControl.__doc__ for more on
  2133. these defaulting rules).
  2134. To select, deselect or otherwise manipulate individual list items, use the
  2135. HTMLForm.find_control() and ListControl.get() methods. To set the whole
  2136. value, do as for any other control: use indexing or the set_/get_value
  2137. methods.
  2138. Example:
  2139. # select *only* the item named "cheddar"
  2140. form["cheeses"] = ["cheddar"]
  2141. # select "cheddar", leave other items unaffected
  2142. form.find_control("cheeses").get("cheddar").selected = True
  2143. Some controls (RADIO and SELECT without the multiple attribute) can only
  2144. have zero or one items selected at a time. Some controls (CHECKBOX and
  2145. SELECT with the multiple attribute) can have multiple items selected at a
  2146. time. To set the whole value of a ListControl, assign a sequence to a form
  2147. index:
  2148. form["cheeses"] = ["cheddar", "leicester"]
  2149. If the ListControl is not multiple-selection, the assigned list must be of
  2150. length one.
  2151. To check if a control has an item, if an item is selected, or if an item is
  2152. successful (selected and not disabled), respectively:
  2153. "cheddar" in [item.name for item in form.find_control("cheeses").items]
  2154. "cheddar" in [item.name for item in form.find_control("cheeses").items and
  2155. item.selected]
  2156. "cheddar" in form["cheeses"] # (or "cheddar" in form.get_value("cheeses"))
  2157. Note that some list items may be disabled (see below).
  2158. Note the following mistake:
  2159. form[control_name] = control_value
  2160. assert form[control_name] == control_value # not necessarily true
  2161. The reason for this is that form[control_name] always gives the list items
  2162. in the order they were listed in the HTML.
  2163. List items (hence list values, too) can be referred to in terms of list
  2164. item labels rather than list item names using the appropriate label
  2165. arguments. Note that each item may have several labels.
  2166. The question of default values of OPTION contents, labels and values is
  2167. somewhat complicated: see SelectControl.__doc__ and
  2168. ListControl.get_item_attrs.__doc__ if you think you need to know.
  2169. Controls can be disabled or readonly. In either case, the control's value
  2170. cannot be changed until you clear those flags (see example below).
  2171. Disabled is the state typically represented by browsers by 'greying out' a
  2172. control. Disabled controls are not 'successful' -- they don't cause data
  2173. to get returned to the server. Readonly controls usually appear in
  2174. browsers as read-only text boxes. Readonly controls are successful. List
  2175. items can also be disabled. Attempts to select or deselect disabled items
  2176. fail with AttributeError.
  2177. If a lot of controls are readonly, it can be useful to do this:
  2178. form.set_all_readonly(False)
  2179. To clear a control's value attribute, so that it is not successful (until a
  2180. value is subsequently set):
  2181. form.clear("cheeses")
  2182. More examples:
  2183. control = form.find_control("cheeses")
  2184. control.disabled = False
  2185. control.readonly = False
  2186. control.get("gruyere").disabled = True
  2187. control.items[0].selected = True
  2188. See the various Control classes for further documentation. Many methods
  2189. take name, type, kind, id, label and nr arguments to specify the control to
  2190. be operated on: see HTMLForm.find_control.__doc__.
  2191. ControlNotFoundError (subclass of ValueError) is raised if the specified
  2192. control can't be found. This includes occasions where a non-ListControl
  2193. is found, but the method (set, for example) requires a ListControl.
  2194. ItemNotFoundError (subclass of ValueError) is raised if a list item can't
  2195. be found. ItemCountError (subclass of ValueError) is raised if an attempt
  2196. is made to select more than one item and the control doesn't allow that, or
  2197. set/get_single are called and the control contains more than one item.
  2198. AttributeError is raised if a control or item is readonly or disabled and
  2199. an attempt is made to alter its value.
  2200. Security note: Remember that any passwords you store in HTMLForm instances
  2201. will be saved to disk in the clear if you pickle them (directly or
  2202. indirectly). The simplest solution to this is to avoid pickling HTMLForm
  2203. objects. You could also pickle before filling in any password, or just set
  2204. the password to "" before pickling.
  2205. Public attributes:
  2206. action: full (absolute URI) form action
  2207. method: "GET" or "POST"
  2208. enctype: form transfer encoding MIME type
  2209. name: name of form (None if no name was specified)
  2210. attrs: dictionary mapping original HTML form attributes to their values
  2211. controls: list of Control instances; do not alter this list
  2212. (instead, call form.new_control to make a Control and add it to the
  2213. form, or control.add_to_form if you already have a Control instance)
  2214. Methods for form filling:
  2215. -------------------------
  2216. Most of the these methods have very similar arguments. See
  2217. HTMLForm.find_control.__doc__ for details of the name, type, kind, label
  2218. and nr arguments.
  2219. def find_control(self,
  2220. name=None, type=None, kind=None, id=None, predicate=None,
  2221. nr=None, label=None)
  2222. get_value(name=None, type=None, kind=None, id=None, nr=None,
  2223. by_label=False, # by_label is deprecated
  2224. label=None)
  2225. set_value(value,
  2226. name=None, type=None, kind=None, id=None, nr=None,
  2227. by_label=False, # by_label is deprecated
  2228. label=None)
  2229. clear_all()
  2230. clear(name=None, type=None, kind=None, id=None, nr=None, label=None)
  2231. set_all_readonly(readonly)
  2232. Method applying only to FileControls:
  2233. add_file(file_object,
  2234. content_type="application/octet-stream", filename=None,
  2235. name=None, id=None, nr=None, label=None)
  2236. Methods applying only to clickable controls:
  2237. click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None)
  2238. click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1),
  2239. label=None)
  2240. click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1), label=None)
  2241. """
  2242. type2class = {
  2243. "text": TextControl,
  2244. "password": PasswordControl,
  2245. "hidden": HiddenControl,
  2246. "textarea": TextareaControl,
  2247. "isindex": IsindexControl,
  2248. "file": FileControl,
  2249. "button": IgnoreControl,
  2250. "buttonbutton": IgnoreControl,
  2251. "reset": IgnoreControl,
  2252. "resetbutton": IgnoreControl,
  2253. "submit": SubmitControl,
  2254. "submitbutton": SubmitButtonControl,
  2255. "image": ImageControl,
  2256. "radio": RadioControl,
  2257. "checkbox": CheckboxControl,
  2258. "select": SelectControl,
  2259. }
  2260. #---------------------------------------------------
  2261. # Initialisation. Use ParseResponse / ParseFile instead.
  2262. def __init__(self, action, method="GET",
  2263. enctype="application/x-www-form-urlencoded",
  2264. name=None, attrs=None,
  2265. request_class=urllib2.Request,
  2266. forms=None, labels=None, id_to_labels=None,
  2267. backwards_compat=True):
  2268. """
  2269. In the usual case, use ParseResponse (or ParseFile) to create new
  2270. HTMLForm objects.
  2271. action: full (absolute URI) form action
  2272. method: "GET" or "POST"
  2273. enctype: form transfer encoding MIME type
  2274. name: name of form
  2275. attrs: dictionary mapping original HTML form attributes to their values
  2276. """
  2277. self.action = action
  2278. self.method = method
  2279. self.enctype = enctype
  2280. self.name = name
  2281. if attrs is not None:
  2282. self.attrs = attrs.copy()
  2283. else:
  2284. self.attrs = {}
  2285. self.controls = []
  2286. self._request_class = request_class
  2287. # these attributes are used by zope.testbrowser
  2288. self._forms = forms # this is a semi-public API!
  2289. self._labels = labels # this is a semi-public API!
  2290. self._id_to_labels = id_to_labels # this is a semi-public API!
  2291. self.backwards_compat = backwards_compat # note __setattr__
  2292. self._urlunparse = urlparse.urlunparse
  2293. self._urlparse = urlparse.urlparse
  2294. def __getattr__(self, name):
  2295. if name == "backwards_compat":
  2296. return self._backwards_compat
  2297. return getattr(HTMLForm, name)
  2298. def __setattr__(self, name, value):
  2299. # yuck
  2300. if name == "backwards_compat":
  2301. name = "_backwards_compat"
  2302. value = bool(value)
  2303. for cc in self.controls:
  2304. try:
  2305. items = cc.items
  2306. except AttributeError:
  2307. continue
  2308. else:
  2309. for ii in items:
  2310. for ll in ii.get_labels():
  2311. ll._backwards_compat = value
  2312. self.__dict__[name] = value
  2313. def new_control(self, type, name, attrs,
  2314. ignore_unknown=False, select_default=False, index=None):
  2315. """Adds a new control to the form.
  2316. This is usually called by ParseFile and ParseResponse. Don't call it
  2317. youself unless you're building your own Control instances.
  2318. Note that controls representing lists of items are built up from
  2319. controls holding only a single list item. See ListControl.__doc__ for
  2320. further information.
  2321. type: type of control (see Control.__doc__ for a list)
  2322. attrs: HTML attributes of control
  2323. ignore_unknown: if true, use a dummy Control instance for controls of
  2324. unknown type; otherwise, use a TextControl
  2325. select_default: for RADIO and multiple-selection SELECT controls, pick
  2326. the first item as the default if no 'selected' HTML attribute is
  2327. present (this defaulting happens when the HTMLForm.fixup method is
  2328. called)
  2329. index: index of corresponding element in HTML (see
  2330. MoreFormTests.test_interspersed_controls for motivation)
  2331. """
  2332. type = type.lower()
  2333. klass = self.type2class.get(type)
  2334. if klass is None:
  2335. if ignore_unknown:
  2336. klass = IgnoreControl
  2337. else:
  2338. klass = TextControl
  2339. a = attrs.copy()
  2340. if issubclass(klass, ListControl):
  2341. control = klass(type, name, a, select_default, index)
  2342. else:
  2343. control = klass(type, name, a, index)
  2344. if type == "select" and len(attrs) == 1:
  2345. for ii in range(len(self.controls)-1, -1, -1):
  2346. ctl = self.controls[ii]
  2347. if ctl.type == "select":
  2348. ctl.close_control()
  2349. break
  2350. control.add_to_form(self)
  2351. control._urlparse = self._urlparse
  2352. control._urlunparse = self._urlunparse
  2353. def fixup(self):
  2354. """Normalise form after all controls have been added.
  2355. This is usually called by ParseFile and ParseResponse. Don't call it
  2356. youself unless you're building your own Control instances.
  2357. This method should only be called once, after all controls have been
  2358. added to the form.
  2359. """
  2360. for control in self.controls:
  2361. control.fixup()
  2362. self.backwards_compat = self._backwards_compat
  2363. #---------------------------------------------------
  2364. def __str__(self):
  2365. header = "%s%s %s %s" % (
  2366. (self.name and self.name+" " or ""),
  2367. self.method, self.action, self.enctype)
  2368. rep = [header]
  2369. for control in self.controls:
  2370. rep.append(" %s" % str(control))
  2371. return "<%s>" % "\n".join(rep)
  2372. #---------------------------------------------------
  2373. # Form-filling methods.
  2374. def __getitem__(self, name):
  2375. return self.find_control(name).value
  2376. def __contains__(self, name):
  2377. return bool(self.find_control(name))
  2378. def __setitem__(self, name, value):
  2379. control = self.find_control(name)
  2380. try:
  2381. control.value = value
  2382. except AttributeError, e:
  2383. raise ValueError(str(e))
  2384. def get_value(self,
  2385. name=None, type=None, kind=None, id=None, nr=None,
  2386. by_label=False, # by_label is deprecated
  2387. label=None):
  2388. """Return value of control.
  2389. If only name and value arguments are supplied, equivalent to
  2390. form[name]
  2391. """
  2392. if by_label:
  2393. deprecation("form.get_value_by_label(...)")
  2394. c = self.find_control(name, type, kind, id, label=label, nr=nr)
  2395. if by_label:
  2396. try:
  2397. meth = c.get_value_by_label
  2398. except AttributeError:
  2399. raise NotImplementedError(
  2400. "control '%s' does not yet support by_label" % c.name)
  2401. else:
  2402. return meth()
  2403. else:
  2404. return c.value
  2405. def set_value(self, value,
  2406. name=None, type=None, kind=None, id=None, nr=None,
  2407. by_label=False, # by_label is deprecated
  2408. label=None):
  2409. """Set value of control.
  2410. If only name and value arguments are supplied, equivalent to
  2411. form[name] = value
  2412. """
  2413. if by_label:
  2414. deprecation("form.get_value_by_label(...)")
  2415. c = self.find_control(name, type, kind, id, label=label, nr=nr)
  2416. if by_label:
  2417. try:
  2418. meth = c.set_value_by_label
  2419. except AttributeError:
  2420. raise NotImplementedError(
  2421. "control '%s' does not yet support by_label" % c.name)
  2422. else:
  2423. meth(value)
  2424. else:
  2425. c.value = value
  2426. def get_value_by_label(
  2427. self, name=None, type=None, kind=None, id=None, label=None, nr=None):
  2428. """
  2429. All arguments should be passed by name.
  2430. """
  2431. c = self.find_control(name, type, kind, id, label=label, nr=nr)
  2432. return c.get_value_by_label()
  2433. def set_value_by_label(
  2434. self, value,
  2435. name=None, type=None, kind=None, id=None, label=None, nr=None):
  2436. """
  2437. All arguments should be passed by name.
  2438. """
  2439. c = self.find_control(name, type, kind, id, label=label, nr=nr)
  2440. c.set_value_by_label(value)
  2441. def set_all_readonly(self, readonly):
  2442. for control in self.controls:
  2443. control.readonly = bool(readonly)
  2444. def clear_all(self):
  2445. """Clear the value attributes of all controls in the form.
  2446. See HTMLForm.clear.__doc__.
  2447. """
  2448. for control in self.controls:
  2449. control.clear()
  2450. def clear(self,
  2451. name=None, type=None, kind=None, id=None, nr=None, label=None):
  2452. """Clear the value attribute of a control.
  2453. As a result, the affected control will not be successful until a value
  2454. is subsequently set. AttributeError is raised on readonly controls.
  2455. """
  2456. c = self.find_control(name, type, kind, id, label=label, nr=nr)
  2457. c.clear()
  2458. #---------------------------------------------------
  2459. # Form-filling methods applying only to ListControls.
  2460. def possible_items(self, # deprecated
  2461. name=None, type=None, kind=None, id=None,
  2462. nr=None, by_label=False, label=None):
  2463. """Return a list of all values that the specified control can take."""
  2464. c = self._find_list_control(name, type, kind, id, label, nr)
  2465. return c.possible_items(by_label)
  2466. def set(self, selected, item_name, # deprecated
  2467. name=None, type=None, kind=None, id=None, nr=None,
  2468. by_label=False, label=None):
  2469. """Select / deselect named list item.
  2470. selected: boolean selected state
  2471. """
  2472. self._find_list_control(name, type, kind, id, label, nr).set(
  2473. selected, item_name, by_label)
  2474. def toggle(self, item_name, # deprecated
  2475. name=None, type=None, kind=None, id=None, nr=None,
  2476. by_label=False, label=None):
  2477. """Toggle selected state of named list item."""
  2478. self._find_list_control(name, type, kind, id, label, nr).toggle(
  2479. item_name, by_label)
  2480. def set_single(self, selected, # deprecated
  2481. name=None, type=None, kind=None, id=None,
  2482. nr=None, by_label=None, label=None):
  2483. """Select / deselect list item in a control having only one item.
  2484. If the control has multiple list items, ItemCountError is raised.
  2485. This is just a convenience method, so you don't need to know the item's
  2486. name -- the item name in these single-item controls is usually
  2487. something meaningless like "1" or "on".
  2488. For example, if a checkbox has a single item named "on", the following
  2489. two calls are equivalent:
  2490. control.toggle("on")
  2491. control.toggle_single()
  2492. """ # by_label ignored and deprecated
  2493. self._find_list_control(
  2494. name, type, kind, id, label, nr).set_single(selected)
  2495. def toggle_single(self, name=None, type=None, kind=None, id=None,
  2496. nr=None, by_label=None, label=None): # deprecated
  2497. """Toggle selected state of list item in control having only one item.
  2498. The rest is as for HTMLForm.set_single.__doc__.
  2499. """ # by_label ignored and deprecated
  2500. self._find_list_control(name, type, kind, id, label, nr).toggle_single()
  2501. #---------------------------------------------------
  2502. # Form-filling method applying only to FileControls.
  2503. def add_file(self, file_object, content_type=None, filename=None,
  2504. name=None, id=None, nr=None, label=None):
  2505. """Add a file to be uploaded.
  2506. file_object: file-like object (with read method) from which to read
  2507. data to upload
  2508. content_type: MIME content type of data to upload
  2509. filename: filename to pass to server
  2510. If filename is None, no filename is sent to the server.
  2511. If content_type is None, the content type is guessed based on the
  2512. filename and the data from read from the file object.
  2513. XXX
  2514. At the moment, guessed content type is always application/octet-stream.
  2515. Use sndhdr, imghdr modules. Should also try to guess HTML, XML, and
  2516. plain text.
  2517. Note the following useful HTML attributes of file upload controls (see
  2518. HTML 4.01 spec, section 17):
  2519. accept: comma-separated list of content types that the server will
  2520. handle correctly; you can use this to filter out non-conforming files
  2521. size: XXX IIRC, this is indicative of whether form wants multiple or
  2522. single files
  2523. maxlength: XXX hint of max content length in bytes?
  2524. """
  2525. self.find_control(name, "file", id=id, label=label, nr=nr).add_file(
  2526. file_object, content_type, filename)
  2527. #---------------------------------------------------
  2528. # Form submission methods, applying only to clickable controls.
  2529. def click(self, name=None, type=None, id=None, nr=0, coord=(1,1),
  2530. request_class=urllib2.Request,
  2531. label=None):
  2532. """Return request that would result from clicking on a control.
  2533. The request object is a urllib2.Request instance, which you can pass to
  2534. urllib2.urlopen (or ClientCookie.urlopen).
  2535. Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and
  2536. IMAGEs) can be clicked.
  2537. Will click on the first clickable control, subject to the name, type
  2538. and nr arguments (as for find_control). If no name, type, id or number
  2539. is specified and there are no clickable controls, a request will be
  2540. returned for the form in its current, un-clicked, state.
  2541. IndexError is raised if any of name, type, id or nr is specified but no
  2542. matching control is found. ValueError is raised if the HTMLForm has an
  2543. enctype attribute that is not recognised.
  2544. You can optionally specify a coordinate to click at, which only makes a
  2545. difference if you clicked on an image.
  2546. """
  2547. return self._click(name, type, id, label, nr, coord, "request",
  2548. self._request_class)
  2549. def click_request_data(self,
  2550. name=None, type=None, id=None,
  2551. nr=0, coord=(1,1),
  2552. request_class=urllib2.Request,
  2553. label=None):
  2554. """As for click method, but return a tuple (url, data, headers).
  2555. You can use this data to send a request to the server. This is useful
  2556. if you're using httplib or urllib rather than urllib2. Otherwise, use
  2557. the click method.
  2558. # Untested. Have to subclass to add headers, I think -- so use urllib2
  2559. # instead!
  2560. import urllib
  2561. url, data, hdrs = form.click_request_data()
  2562. r = urllib.urlopen(url, data)
  2563. # Untested. I don't know of any reason to use httplib -- you can get
  2564. # just as much control with urllib2.
  2565. import httplib, urlparse
  2566. url, data, hdrs = form.click_request_data()
  2567. tup = urlparse(url)
  2568. host, path = tup[1], urlparse.urlunparse((None, None)+tup[2:])
  2569. conn = httplib.HTTPConnection(host)
  2570. if data:
  2571. httplib.request("POST", path, data, hdrs)
  2572. else:
  2573. httplib.request("GET", path, headers=hdrs)
  2574. r = conn.getresponse()
  2575. """
  2576. return self._click(name, type, id, label, nr, coord, "request_data",
  2577. self._request_class)
  2578. def click_pairs(self, name=None, type=None, id=None,
  2579. nr=0, coord=(1,1),
  2580. label=None):
  2581. """As for click_request_data, but returns a list of (key, value) pairs.
  2582. You can use this list as an argument to ClientForm.urlencode. This is
  2583. usually only useful if you're using httplib or urllib rather than
  2584. urllib2 or ClientCookie. It may also be useful if you want to manually
  2585. tweak the keys and/or values, but this should not be necessary.
  2586. Otherwise, use the click method.
  2587. Note that this method is only useful for forms of MIME type
  2588. x-www-form-urlencoded. In particular, it does not return the
  2589. information required for file upload. If you need file upload and are
  2590. not using urllib2, use click_request_data.
  2591. Also note that Python 2.0's urllib.urlencode is slightly broken: it
  2592. only accepts a mapping, not a sequence of pairs, as an argument. This
  2593. messes up any ordering in the argument. Use ClientForm.urlencode
  2594. instead.
  2595. """
  2596. return self._click(name, type, id, label, nr, coord, "pairs",
  2597. self._request_class)
  2598. #---------------------------------------------------
  2599. def find_control(self,
  2600. name=None, type=None, kind=None, id=None,
  2601. predicate=None, nr=None,
  2602. label=None):
  2603. """Locate and return some specific control within the form.
  2604. At least one of the name, type, kind, predicate and nr arguments must
  2605. be supplied. If no matching control is found, ControlNotFoundError is
  2606. raised.
  2607. If name is specified, then the control must have the indicated name.
  2608. If type is specified then the control must have the specified type (in
  2609. addition to the types possible for <input> HTML tags: "text",
  2610. "password", "hidden", "submit", "image", "button", "radio", "checkbox",
  2611. "file" we also have "reset", "buttonbutton", "submitbutton",
  2612. "resetbutton", "textarea", "select" and "isindex").
  2613. If kind is specified, then the control must fall into the specified
  2614. group, each of which satisfies a particular interface. The types are
  2615. "text", "list", "multilist", "singlelist", "clickable" and "file".
  2616. If id is specified, then the control must have the indicated id.
  2617. If predicate is specified, then the control must match that function.
  2618. The predicate function is passed the control as its single argument,
  2619. and should return a boolean value indicating whether the control
  2620. matched.
  2621. nr, if supplied, is the sequence number of the control (where 0 is the
  2622. first). Note that control 0 is the first control matching all the
  2623. other arguments (if supplied); it is not necessarily the first control
  2624. in the form. If no nr is supplied, AmbiguityError is raised if
  2625. multiple controls match the other arguments (unless the
  2626. .backwards-compat attribute is true).
  2627. If label is specified, then the control must have this label. Note
  2628. that radio controls and checkboxes never have labels: their items do.
  2629. """
  2630. if ((name is None) and (type is None) and (kind is None) and
  2631. (id is None) and (label is None) and (predicate is None) and
  2632. (nr is None)):
  2633. raise ValueError(
  2634. "at least one argument must be supplied to specify control")
  2635. return self._find_control(name, type, kind, id, label, predicate, nr)
  2636. #---------------------------------------------------
  2637. # Private methods.
  2638. def _find_list_control(self,
  2639. name=None, type=None, kind=None, id=None,
  2640. label=None, nr=None):
  2641. if ((name is None) and (type is None) and (kind is None) and
  2642. (id is None) and (label is None) and (nr is None)):
  2643. raise ValueError(
  2644. "at least one argument must be supplied to specify control")
  2645. return self._find_control(name, type, kind, id, label,
  2646. is_listcontrol, nr)
  2647. def _find_control(self, name, type, kind, id, label, predicate, nr):
  2648. if ((name is not None) and (name is not Missing) and
  2649. not isstringlike(name)):
  2650. raise TypeError("control name must be string-like")
  2651. if (type is not None) and not isstringlike(type):
  2652. raise TypeError("control type must be string-like")
  2653. if (kind is not None) and not isstringlike(kind):
  2654. raise TypeError("control kind must be string-like")
  2655. if (id is not None) and not isstringlike(id):
  2656. raise TypeError("control id must be string-like")
  2657. if (label is not None) and not isstringlike(label):
  2658. raise TypeError("control label must be string-like")
  2659. if (predicate is not None) and not callable(predicate):
  2660. raise TypeError("control predicate must be callable")
  2661. if (nr is not None) and nr < 0:
  2662. raise ValueError("control number must be a positive integer")
  2663. orig_nr = nr
  2664. found = None
  2665. ambiguous = False
  2666. if nr is None and self.backwards_compat:
  2667. nr = 0
  2668. for control in self.controls:
  2669. if ((name is not None and name != control.name) and
  2670. (name is not Missing or control.name is not None)):
  2671. continue
  2672. if type is not None and type != control.type:
  2673. continue
  2674. if kind is not None and not control.is_of_kind(kind):
  2675. continue
  2676. if id is not None and id != control.id:
  2677. continue
  2678. if predicate and not predicate(control):
  2679. continue
  2680. if label:
  2681. for l in control.get_labels():
  2682. if l.text.find(label) > -1:
  2683. break
  2684. else:
  2685. continue
  2686. if nr is not None:
  2687. if nr == 0:
  2688. return control # early exit: unambiguous due to nr
  2689. nr -= 1
  2690. continue
  2691. if found:
  2692. ambiguous = True
  2693. break
  2694. found = control
  2695. if found and not ambiguous:
  2696. return found
  2697. description = []
  2698. if name is not None: description.append("name %s" % repr(name))
  2699. if type is not None: description.append("type '%s'" % type)
  2700. if kind is not None: description.append("kind '%s'" % kind)
  2701. if id is not None: description.append("id '%s'" % id)
  2702. if label is not None: description.append("label '%s'" % label)
  2703. if predicate is not None:
  2704. description.append("predicate %s" % predicate)
  2705. if orig_nr: description.append("nr %d" % orig_nr)
  2706. description = ", ".join(description)
  2707. if ambiguous:
  2708. raise AmbiguityError("more than one control matching "+description)
  2709. elif not found:
  2710. raise ControlNotFoundError("no control matching "+description)
  2711. assert False
  2712. def _click(self, name, type, id, label, nr, coord, return_type,
  2713. request_class=urllib2.Request):
  2714. try:
  2715. control = self._find_control(
  2716. name, type, "clickable", id, label, None, nr)
  2717. except ControlNotFoundError:
  2718. if ((name is not None) or (type is not None) or (id is not None) or
  2719. (nr != 0)):
  2720. raise
  2721. # no clickable controls, but no control was explicitly requested,
  2722. # so return state without clicking any control
  2723. return self._switch_click(return_type, request_class)
  2724. else:
  2725. return control._click(self, coord, return_type, request_class)
  2726. def _pairs(self):
  2727. """Return sequence of (key, value) pairs suitable for urlencoding."""
  2728. return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()]
  2729. def _pairs_and_controls(self):
  2730. """Return sequence of (index, key, value, control_index)
  2731. of totally ordered pairs suitable for urlencoding.
  2732. control_index is the index of the control in self.controls
  2733. """
  2734. pairs = []
  2735. for control_index in range(len(self.controls)):
  2736. control = self.controls[control_index]
  2737. for ii, key, val in control._totally_ordered_pairs():
  2738. pairs.append((ii, key, val, control_index))
  2739. # stable sort by ONLY first item in tuple
  2740. pairs.sort()
  2741. return pairs
  2742. def _request_data(self):
  2743. """Return a tuple (url, data, headers)."""
  2744. method = self.method.upper()
  2745. #scheme, netloc, path, parameters, query, frag = urlparse.urlparse(self.action)
  2746. parts = self._urlparse(self.action)
  2747. rest, (query, frag) = parts[:-2], parts[-2:]
  2748. if method == "GET":
  2749. if self.enctype != "application/x-www-form-urlencoded":
  2750. raise ValueError(
  2751. "unknown GET form encoding type '%s'" % self.enctype)
  2752. parts = rest + (urlencode(self._pairs()), None)
  2753. uri = self._urlunparse(parts)
  2754. return uri, None, []
  2755. elif method == "POST":
  2756. parts = rest + (query, None)
  2757. uri = self._urlunparse(parts)
  2758. if self.enctype == "application/x-www-form-urlencoded":
  2759. return (uri, urlencode(self._pairs()),
  2760. [("Content-Type", self.enctype)])
  2761. elif self.enctype == "multipart/form-data":
  2762. data = StringIO()
  2763. http_hdrs = []
  2764. mw = MimeWriter(data, http_hdrs)
  2765. f = mw.startmultipartbody("form-data", add_to_http_hdrs=True,
  2766. prefix=0)
  2767. for ii, k, v, control_index in self._pairs_and_controls():
  2768. self.controls[control_index]._write_mime_data(mw, k, v)
  2769. mw.lastpart()
  2770. return uri, data.getvalue(), http_hdrs
  2771. else:
  2772. raise ValueError(
  2773. "unknown POST form encoding type '%s'" % self.enctype)
  2774. else:
  2775. raise ValueError("Unknown method '%s'" % method)
  2776. def _switch_click(self, return_type, request_class=urllib2.Request):
  2777. # This is called by HTMLForm and clickable Controls to hide switching
  2778. # on return_type.
  2779. if return_type == "pairs":
  2780. return self._pairs()
  2781. elif return_type == "request_data":
  2782. return self._request_data()
  2783. else:
  2784. req_data = self._request_data()
  2785. req = request_class(req_data[0], req_data[1])
  2786. for key, val in req_data[2]:
  2787. add_hdr = req.add_header
  2788. if key.lower() == "content-type":
  2789. try:
  2790. add_hdr = req.add_unredirected_header
  2791. except AttributeError:
  2792. # pre-2.4 and not using ClientCookie
  2793. pass
  2794. add_hdr(key, val)
  2795. return req