PageRenderTime 69ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full file

  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

Large files files are truncated, but you can click here to view the full file