You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

httplib.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. """HTTP/1.1 client library
  2. <intro stuff goes here>
  3. <other stuff, too>
  4. HTTPConnection go through a number of "states", which defines when a client
  5. may legally make another request or fetch the response for a particular
  6. request. This diagram details these state transitions:
  7. (null)
  8. |
  9. | HTTPConnection()
  10. v
  11. Idle
  12. |
  13. | putrequest()
  14. v
  15. Request-started
  16. |
  17. | ( putheader() )* endheaders()
  18. v
  19. Request-sent
  20. |
  21. | response = getresponse()
  22. v
  23. Unread-response [Response-headers-read]
  24. |\____________________
  25. | |
  26. | response.read() | putrequest()
  27. v v
  28. Idle Req-started-unread-response
  29. ______/|
  30. / |
  31. response.read() | | ( putheader() )* endheaders()
  32. v v
  33. Request-started Req-sent-unread-response
  34. |
  35. | response.read()
  36. v
  37. Request-sent
  38. This diagram presents the following rules:
  39. -- a second request may not be started until {response-headers-read}
  40. -- a response [object] cannot be retrieved until {request-sent}
  41. -- there is no differentiation between an unread response body and a
  42. partially read response body
  43. Note: this enforcement is applied by the HTTPConnection class. The
  44. HTTPResponse class does not enforce this state machine, which
  45. implies sophisticated clients may accelerate the request/response
  46. pipeline. Caution should be taken, though: accelerating the states
  47. beyond the above pattern may imply knowledge of the server's
  48. connection-close behavior for certain requests. For example, it
  49. is impossible to tell whether the server will close the connection
  50. UNTIL the response headers have been read; this means that further
  51. requests cannot be placed into the pipeline until it is known that
  52. the server will NOT be closing the connection.
  53. Logical State __state __response
  54. ------------- ------- ----------
  55. Idle _CS_IDLE None
  56. Request-started _CS_REQ_STARTED None
  57. Request-sent _CS_REQ_SENT None
  58. Unread-response _CS_IDLE <response_class>
  59. Req-started-unread-response _CS_REQ_STARTED <response_class>
  60. Req-sent-unread-response _CS_REQ_SENT <response_class>
  61. """
  62. import socket
  63. import mimetools
  64. try:
  65. from cStringIO import StringIO
  66. except ImportError:
  67. from StringIO import StringIO
  68. __all__ = ["HTTP", "HTTPResponse", "HTTPConnection", "HTTPSConnection",
  69. "HTTPException", "NotConnected", "UnknownProtocol",
  70. "UnknownTransferEncoding", "IllegalKeywordArgument",
  71. "UnimplementedFileMode", "IncompleteRead",
  72. "ImproperConnectionState", "CannotSendRequest", "CannotSendHeader",
  73. "ResponseNotReady", "BadStatusLine", "error"]
  74. HTTP_PORT = 80
  75. HTTPS_PORT = 443
  76. _UNKNOWN = 'UNKNOWN'
  77. # connection states
  78. _CS_IDLE = 'Idle'
  79. _CS_REQ_STARTED = 'Request-started'
  80. _CS_REQ_SENT = 'Request-sent'
  81. class HTTPResponse:
  82. def __init__(self, sock, debuglevel=0):
  83. self.fp = sock.makefile('rb', 0)
  84. self.debuglevel = debuglevel
  85. self.msg = None
  86. # from the Status-Line of the response
  87. self.version = _UNKNOWN # HTTP-Version
  88. self.status = _UNKNOWN # Status-Code
  89. self.reason = _UNKNOWN # Reason-Phrase
  90. self.chunked = _UNKNOWN # is "chunked" being used?
  91. self.chunk_left = _UNKNOWN # bytes left to read in current chunk
  92. self.length = _UNKNOWN # number of bytes left in response
  93. self.will_close = _UNKNOWN # conn will close at end of response
  94. def begin(self):
  95. if self.msg is not None:
  96. # we've already started reading the response
  97. return
  98. line = self.fp.readline()
  99. if self.debuglevel > 0:
  100. print "reply:", repr(line)
  101. try:
  102. [version, status, reason] = line.split(None, 2)
  103. except ValueError:
  104. try:
  105. [version, status] = line.split(None, 1)
  106. reason = ""
  107. except ValueError:
  108. version = "HTTP/0.9"
  109. status = "200"
  110. reason = ""
  111. if version[:5] != 'HTTP/':
  112. self.close()
  113. raise BadStatusLine(line)
  114. # The status code is a three-digit number
  115. try:
  116. self.status = status = int(status)
  117. if status < 100 or status > 999:
  118. raise BadStatusLine(line)
  119. except ValueError:
  120. raise BadStatusLine(line)
  121. self.reason = reason.strip()
  122. if version == 'HTTP/1.0':
  123. self.version = 10
  124. elif version.startswith('HTTP/1.'):
  125. self.version = 11 # use HTTP/1.1 code for HTTP/1.x where x>=1
  126. elif version == 'HTTP/0.9':
  127. self.version = 9
  128. else:
  129. raise UnknownProtocol(version)
  130. if self.version == 9:
  131. self.msg = mimetools.Message(StringIO())
  132. return
  133. self.msg = mimetools.Message(self.fp, 0)
  134. if self.debuglevel > 0:
  135. for hdr in self.msg.headers:
  136. print "header:", hdr,
  137. # don't let the msg keep an fp
  138. self.msg.fp = None
  139. # are we using the chunked-style of transfer encoding?
  140. tr_enc = self.msg.getheader('transfer-encoding')
  141. if tr_enc:
  142. if tr_enc.lower() != 'chunked':
  143. raise UnknownTransferEncoding()
  144. self.chunked = 1
  145. self.chunk_left = None
  146. else:
  147. self.chunked = 0
  148. # will the connection close at the end of the response?
  149. conn = self.msg.getheader('connection')
  150. if conn:
  151. conn = conn.lower()
  152. # a "Connection: close" will always close the connection. if we
  153. # don't see that and this is not HTTP/1.1, then the connection will
  154. # close unless we see a Keep-Alive header.
  155. self.will_close = conn.find('close') != -1 or \
  156. ( self.version != 11 and \
  157. not self.msg.getheader('keep-alive') )
  158. else:
  159. # for HTTP/1.1, the connection will always remain open
  160. # otherwise, it will remain open IFF we see a Keep-Alive header
  161. self.will_close = self.version != 11 and \
  162. not self.msg.getheader('keep-alive')
  163. # do we have a Content-Length?
  164. # NOTE: RFC 2616, S4.4, #3 says we ignore this if tr_enc is "chunked"
  165. length = self.msg.getheader('content-length')
  166. if length and not self.chunked:
  167. try:
  168. self.length = int(length)
  169. except ValueError:
  170. self.length = None
  171. else:
  172. self.length = None
  173. # does the body have a fixed length? (of zero)
  174. if (status == 204 or # No Content
  175. status == 304 or # Not Modified
  176. 100 <= status < 200): # 1xx codes
  177. self.length = 0
  178. # if the connection remains open, and we aren't using chunked, and
  179. # a content-length was not provided, then assume that the connection
  180. # WILL close.
  181. if not self.will_close and \
  182. not self.chunked and \
  183. self.length is None:
  184. self.will_close = 1
  185. def close(self):
  186. if self.fp:
  187. self.fp.close()
  188. self.fp = None
  189. def isclosed(self):
  190. # NOTE: it is possible that we will not ever call self.close(). This
  191. # case occurs when will_close is TRUE, length is None, and we
  192. # read up to the last byte, but NOT past it.
  193. #
  194. # IMPLIES: if will_close is FALSE, then self.close() will ALWAYS be
  195. # called, meaning self.isclosed() is meaningful.
  196. return self.fp is None
  197. def read(self, amt=None):
  198. if self.fp is None:
  199. return ''
  200. if self.chunked:
  201. chunk_left = self.chunk_left
  202. value = ''
  203. while 1:
  204. if chunk_left is None:
  205. line = self.fp.readline()
  206. i = line.find(';')
  207. if i >= 0:
  208. line = line[:i] # strip chunk-extensions
  209. chunk_left = int(line, 16)
  210. if chunk_left == 0:
  211. break
  212. if amt is None:
  213. value = value + self._safe_read(chunk_left)
  214. elif amt < chunk_left:
  215. value = value + self._safe_read(amt)
  216. self.chunk_left = chunk_left - amt
  217. return value
  218. elif amt == chunk_left:
  219. value = value + self._safe_read(amt)
  220. self._safe_read(2) # toss the CRLF at the end of the chunk
  221. self.chunk_left = None
  222. return value
  223. else:
  224. value = value + self._safe_read(chunk_left)
  225. amt = amt - chunk_left
  226. # we read the whole chunk, get another
  227. self._safe_read(2) # toss the CRLF at the end of the chunk
  228. chunk_left = None
  229. # read and discard trailer up to the CRLF terminator
  230. ### note: we shouldn't have any trailers!
  231. while 1:
  232. line = self.fp.readline()
  233. if line == '\r\n':
  234. break
  235. # we read everything; close the "file"
  236. self.close()
  237. return value
  238. elif amt is None:
  239. # unbounded read
  240. if self.will_close:
  241. s = self.fp.read()
  242. else:
  243. s = self._safe_read(self.length)
  244. self.close() # we read everything
  245. return s
  246. if self.length is not None:
  247. if amt > self.length:
  248. # clip the read to the "end of response"
  249. amt = self.length
  250. self.length = self.length - amt
  251. # we do not use _safe_read() here because this may be a .will_close
  252. # connection, and the user is reading more bytes than will be provided
  253. # (for example, reading in 1k chunks)
  254. s = self.fp.read(amt)
  255. return s
  256. def _safe_read(self, amt):
  257. """Read the number of bytes requested, compensating for partial reads.
  258. Normally, we have a blocking socket, but a read() can be interrupted
  259. by a signal (resulting in a partial read).
  260. Note that we cannot distinguish between EOF and an interrupt when zero
  261. bytes have been read. IncompleteRead() will be raised in this
  262. situation.
  263. This function should be used when <amt> bytes "should" be present for
  264. reading. If the bytes are truly not available (due to EOF), then the
  265. IncompleteRead exception can be used to detect the problem.
  266. """
  267. s = ''
  268. while amt > 0:
  269. chunk = self.fp.read(amt)
  270. if not chunk:
  271. raise IncompleteRead(s)
  272. s = s + chunk
  273. amt = amt - len(chunk)
  274. return s
  275. def getheader(self, name, default=None):
  276. if self.msg is None:
  277. raise ResponseNotReady()
  278. return self.msg.getheader(name, default)
  279. class HTTPConnection:
  280. _http_vsn = 11
  281. _http_vsn_str = 'HTTP/1.1'
  282. response_class = HTTPResponse
  283. default_port = HTTP_PORT
  284. auto_open = 1
  285. debuglevel = 0
  286. def __init__(self, host, port=None):
  287. self.sock = None
  288. self.__response = None
  289. self.__state = _CS_IDLE
  290. self._set_hostport(host, port)
  291. def _set_hostport(self, host, port):
  292. if port is None:
  293. i = host.find(':')
  294. if i >= 0:
  295. port = int(host[i+1:])
  296. host = host[:i]
  297. else:
  298. port = self.default_port
  299. self.host = host
  300. self.port = port
  301. def set_debuglevel(self, level):
  302. self.debuglevel = level
  303. def connect(self):
  304. """Connect to the host and port specified in __init__."""
  305. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  306. if self.debuglevel > 0:
  307. print "connect: (%s, %s)" % (self.host, self.port)
  308. self.sock.connect((self.host, self.port))
  309. def close(self):
  310. """Close the connection to the HTTP server."""
  311. if self.sock:
  312. self.sock.close() # close it manually... there may be other refs
  313. self.sock = None
  314. if self.__response:
  315. self.__response.close()
  316. self.__response = None
  317. self.__state = _CS_IDLE
  318. def send(self, str):
  319. """Send `str' to the server."""
  320. if self.sock is None:
  321. if self.auto_open:
  322. self.connect()
  323. else:
  324. raise NotConnected()
  325. # send the data to the server. if we get a broken pipe, then close
  326. # the socket. we want to reconnect when somebody tries to send again.
  327. #
  328. # NOTE: we DO propagate the error, though, because we cannot simply
  329. # ignore the error... the caller will know if they can retry.
  330. if self.debuglevel > 0:
  331. print "send:", repr(str)
  332. try:
  333. self.sock.send(str)
  334. except socket.error, v:
  335. if v[0] == 32: # Broken pipe
  336. self.close()
  337. raise
  338. def putrequest(self, method, url):
  339. """Send a request to the server.
  340. `method' specifies an HTTP request method, e.g. 'GET'.
  341. `url' specifies the object being requested, e.g. '/index.html'.
  342. """
  343. # check if a prior response has been completed
  344. if self.__response and self.__response.isclosed():
  345. self.__response = None
  346. #
  347. # in certain cases, we cannot issue another request on this connection.
  348. # this occurs when:
  349. # 1) we are in the process of sending a request. (_CS_REQ_STARTED)
  350. # 2) a response to a previous request has signalled that it is going
  351. # to close the connection upon completion.
  352. # 3) the headers for the previous response have not been read, thus
  353. # we cannot determine whether point (2) is true. (_CS_REQ_SENT)
  354. #
  355. # if there is no prior response, then we can request at will.
  356. #
  357. # if point (2) is true, then we will have passed the socket to the
  358. # response (effectively meaning, "there is no prior response"), and
  359. # will open a new one when a new request is made.
  360. #
  361. # Note: if a prior response exists, then we *can* start a new request.
  362. # We are not allowed to begin fetching the response to this new
  363. # request, however, until that prior response is complete.
  364. #
  365. if self.__state == _CS_IDLE:
  366. self.__state = _CS_REQ_STARTED
  367. else:
  368. raise CannotSendRequest()
  369. if not url:
  370. url = '/'
  371. str = '%s %s %s\r\n' % (method, url, self._http_vsn_str)
  372. try:
  373. self.send(str)
  374. except socket.error, v:
  375. # trap 'Broken pipe' if we're allowed to automatically reconnect
  376. if v[0] != 32 or not self.auto_open:
  377. raise
  378. # try one more time (the socket was closed; this will reopen)
  379. self.send(str)
  380. if self._http_vsn == 11:
  381. # Issue some standard headers for better HTTP/1.1 compliance
  382. # this header is issued *only* for HTTP/1.1 connections. more
  383. # specifically, this means it is only issued when the client uses
  384. # the new HTTPConnection() class. backwards-compat clients will
  385. # be using HTTP/1.0 and those clients may be issuing this header
  386. # themselves. we should NOT issue it twice; some web servers (such
  387. # as Apache) barf when they see two Host: headers
  388. # if we need a non-standard port,include it in the header
  389. if self.port == HTTP_PORT:
  390. self.putheader('Host', self.host)
  391. else:
  392. self.putheader('Host', "%s:%s" % (self.host, self.port))
  393. # note: we are assuming that clients will not attempt to set these
  394. # headers since *this* library must deal with the
  395. # consequences. this also means that when the supporting
  396. # libraries are updated to recognize other forms, then this
  397. # code should be changed (removed or updated).
  398. # we only want a Content-Encoding of "identity" since we don't
  399. # support encodings such as x-gzip or x-deflate.
  400. self.putheader('Accept-Encoding', 'identity')
  401. # we can accept "chunked" Transfer-Encodings, but no others
  402. # NOTE: no TE header implies *only* "chunked"
  403. #self.putheader('TE', 'chunked')
  404. # if TE is supplied in the header, then it must appear in a
  405. # Connection header.
  406. #self.putheader('Connection', 'TE')
  407. else:
  408. # For HTTP/1.0, the server will assume "not chunked"
  409. pass
  410. def putheader(self, header, value):
  411. """Send a request header line to the server.
  412. For example: h.putheader('Accept', 'text/html')
  413. """
  414. if self.__state != _CS_REQ_STARTED:
  415. raise CannotSendHeader()
  416. str = '%s: %s\r\n' % (header, value)
  417. self.send(str)
  418. def endheaders(self):
  419. """Indicate that the last header line has been sent to the server."""
  420. if self.__state == _CS_REQ_STARTED:
  421. self.__state = _CS_REQ_SENT
  422. else:
  423. raise CannotSendHeader()
  424. self.send('\r\n')
  425. def request(self, method, url, body=None, headers={}):
  426. """Send a complete request to the server."""
  427. try:
  428. self._send_request(method, url, body, headers)
  429. except socket.error, v:
  430. # trap 'Broken pipe' if we're allowed to automatically reconnect
  431. if v[0] != 32 or not self.auto_open:
  432. raise
  433. # try one more time
  434. self._send_request(method, url, body, headers)
  435. def _send_request(self, method, url, body, headers):
  436. self.putrequest(method, url)
  437. if body:
  438. self.putheader('Content-Length', str(len(body)))
  439. for hdr, value in headers.items():
  440. self.putheader(hdr, value)
  441. self.endheaders()
  442. if body:
  443. self.send(body)
  444. def getresponse(self):
  445. "Get the response from the server."
  446. # check if a prior response has been completed
  447. if self.__response and self.__response.isclosed():
  448. self.__response = None
  449. #
  450. # if a prior response exists, then it must be completed (otherwise, we
  451. # cannot read this response's header to determine the connection-close
  452. # behavior)
  453. #
  454. # note: if a prior response existed, but was connection-close, then the
  455. # socket and response were made independent of this HTTPConnection
  456. # object since a new request requires that we open a whole new
  457. # connection
  458. #
  459. # this means the prior response had one of two states:
  460. # 1) will_close: this connection was reset and the prior socket and
  461. # response operate independently
  462. # 2) persistent: the response was retained and we await its
  463. # isclosed() status to become true.
  464. #
  465. if self.__state != _CS_REQ_SENT or self.__response:
  466. raise ResponseNotReady()
  467. if self.debuglevel > 0:
  468. response = self.response_class(self.sock, self.debuglevel)
  469. else:
  470. response = self.response_class(self.sock)
  471. response.begin()
  472. self.__state = _CS_IDLE
  473. if response.will_close:
  474. # this effectively passes the connection to the response
  475. self.close()
  476. else:
  477. # remember this, so we can tell when it is complete
  478. self.__response = response
  479. return response
  480. class FakeSocket:
  481. def __init__(self, sock, ssl):
  482. self.__sock = sock
  483. self.__ssl = ssl
  484. def makefile(self, mode, bufsize=None):
  485. """Return a readable file-like object with data from socket.
  486. This method offers only partial support for the makefile
  487. interface of a real socket. It only supports modes 'r' and
  488. 'rb' and the bufsize argument is ignored.
  489. The returned object contains *all* of the file data
  490. """
  491. if mode != 'r' and mode != 'rb':
  492. raise UnimplementedFileMode()
  493. msgbuf = []
  494. while 1:
  495. try:
  496. buf = self.__ssl.read()
  497. except socket.sslerror, msg:
  498. break
  499. if buf == '':
  500. break
  501. msgbuf.append(buf)
  502. return StringIO("".join(msgbuf))
  503. def send(self, stuff, flags = 0):
  504. return self.__ssl.write(stuff)
  505. def recv(self, len = 1024, flags = 0):
  506. return self.__ssl.read(len)
  507. def __getattr__(self, attr):
  508. return getattr(self.__sock, attr)
  509. class HTTPSConnection(HTTPConnection):
  510. "This class allows communication via SSL."
  511. default_port = HTTPS_PORT
  512. def __init__(self, host, port=None, **x509):
  513. keys = x509.keys()
  514. try:
  515. keys.remove('key_file')
  516. except ValueError:
  517. pass
  518. try:
  519. keys.remove('cert_file')
  520. except ValueError:
  521. pass
  522. if keys:
  523. raise IllegalKeywordArgument()
  524. HTTPConnection.__init__(self, host, port)
  525. self.key_file = x509.get('key_file')
  526. self.cert_file = x509.get('cert_file')
  527. def connect(self):
  528. "Connect to a host on a given (SSL) port."
  529. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  530. sock.connect((self.host, self.port))
  531. realsock = sock
  532. if hasattr(sock, "_sock"):
  533. realsock = sock._sock
  534. ssl = socket.ssl(realsock, self.key_file, self.cert_file)
  535. self.sock = FakeSocket(sock, ssl)
  536. class HTTP:
  537. "Compatibility class with httplib.py from 1.5."
  538. _http_vsn = 10
  539. _http_vsn_str = 'HTTP/1.0'
  540. debuglevel = 0
  541. _connection_class = HTTPConnection
  542. def __init__(self, host='', port=None, **x509):
  543. "Provide a default host, since the superclass requires one."
  544. # some joker passed 0 explicitly, meaning default port
  545. if port == 0:
  546. port = None
  547. # Note that we may pass an empty string as the host; this will throw
  548. # an error when we attempt to connect. Presumably, the client code
  549. # will call connect before then, with a proper host.
  550. self._conn = self._connection_class(host, port)
  551. # set up delegation to flesh out interface
  552. self.send = self._conn.send
  553. self.putrequest = self._conn.putrequest
  554. self.endheaders = self._conn.endheaders
  555. self._conn._http_vsn = self._http_vsn
  556. self._conn._http_vsn_str = self._http_vsn_str
  557. # we never actually use these for anything, but we keep them here for
  558. # compatibility with post-1.5.2 CVS.
  559. self.key_file = x509.get('key_file')
  560. self.cert_file = x509.get('cert_file')
  561. self.file = None
  562. def connect(self, host=None, port=None):
  563. "Accept arguments to set the host/port, since the superclass doesn't."
  564. if host is not None:
  565. self._conn._set_hostport(host, port)
  566. self._conn.connect()
  567. def set_debuglevel(self, debuglevel):
  568. self._conn.set_debuglevel(debuglevel)
  569. def getfile(self):
  570. "Provide a getfile, since the superclass' does not use this concept."
  571. return self.file
  572. def putheader(self, header, *values):
  573. "The superclass allows only one value argument."
  574. self._conn.putheader(header, '\r\n\t'.join(values))
  575. def getreply(self):
  576. """Compat definition since superclass does not define it.
  577. Returns a tuple consisting of:
  578. - server status code (e.g. '200' if all goes well)
  579. - server "reason" corresponding to status code
  580. - any RFC822 headers in the response from the server
  581. """
  582. try:
  583. response = self._conn.getresponse()
  584. except BadStatusLine, e:
  585. ### hmm. if getresponse() ever closes the socket on a bad request,
  586. ### then we are going to have problems with self.sock
  587. ### should we keep this behavior? do people use it?
  588. # keep the socket open (as a file), and return it
  589. self.file = self._conn.sock.makefile('rb', 0)
  590. # close our socket -- we want to restart after any protocol error
  591. self.close()
  592. self.headers = None
  593. return -1, e.line, None
  594. self.headers = response.msg
  595. self.file = response.fp
  596. return response.status, response.reason, response.msg
  597. def close(self):
  598. self._conn.close()
  599. # note that self.file == response.fp, which gets closed by the
  600. # superclass. just clear the object ref here.
  601. ### hmm. messy. if status==-1, then self.file is owned by us.
  602. ### well... we aren't explicitly closing, but losing this ref will
  603. ### do it
  604. self.file = None
  605. if hasattr(socket, 'ssl'):
  606. class HTTPS(HTTP):
  607. """Compatibility with 1.5 httplib interface
  608. Python 1.5.2 did not have an HTTPS class, but it defined an
  609. interface for sending http requests that is also useful for
  610. https.
  611. """
  612. _connection_class = HTTPSConnection
  613. class HTTPException(Exception):
  614. pass
  615. class NotConnected(HTTPException):
  616. pass
  617. class UnknownProtocol(HTTPException):
  618. def __init__(self, version):
  619. self.version = version
  620. class UnknownTransferEncoding(HTTPException):
  621. pass
  622. class IllegalKeywordArgument(HTTPException):
  623. pass
  624. class UnimplementedFileMode(HTTPException):
  625. pass
  626. class IncompleteRead(HTTPException):
  627. def __init__(self, partial):
  628. self.partial = partial
  629. class ImproperConnectionState(HTTPException):
  630. pass
  631. class CannotSendRequest(ImproperConnectionState):
  632. pass
  633. class CannotSendHeader(ImproperConnectionState):
  634. pass
  635. class ResponseNotReady(ImproperConnectionState):
  636. pass
  637. class BadStatusLine(HTTPException):
  638. def __init__(self, line):
  639. self.line = line
  640. # for backwards compatibility
  641. error = HTTPException
  642. #
  643. # snarfed from httplib.py for now...
  644. #
  645. def test():
  646. """Test this module.
  647. The test consists of retrieving and displaying the Python
  648. home page, along with the error code and error string returned
  649. by the www.python.org server.
  650. """
  651. import sys
  652. import getopt
  653. opts, args = getopt.getopt(sys.argv[1:], 'd')
  654. dl = 0
  655. for o, a in opts:
  656. if o == '-d': dl = dl + 1
  657. host = 'www.python.org'
  658. selector = '/'
  659. if args[0:]: host = args[0]
  660. if args[1:]: selector = args[1]
  661. h = HTTP()
  662. h.set_debuglevel(dl)
  663. h.connect(host)
  664. h.putrequest('GET', selector)
  665. h.endheaders()
  666. status, reason, headers = h.getreply()
  667. print 'status =', status
  668. print 'reason =', reason
  669. print
  670. if headers:
  671. for header in headers.headers: print header.strip()
  672. print
  673. print h.getfile().read()
  674. if hasattr(socket, 'ssl'):
  675. host = 'sourceforge.net'
  676. selector = '/projects/python'
  677. hs = HTTPS()
  678. hs.connect(host)
  679. hs.putrequest('GET', selector)
  680. hs.endheaders()
  681. status, reason, headers = hs.getreply()
  682. print 'status =', status
  683. print 'reason =', reason
  684. print
  685. if headers:
  686. for header in headers.headers: print header.strip()
  687. print
  688. print hs.getfile().read()
  689. if __name__ == '__main__':
  690. test()