/atom/service.py

http://radioappz.googlecode.com/ · Python · 740 lines · 676 code · 16 blank · 48 comment · 12 complexity · 4dfc1acbbc1a42a1d4226c2edf18155e MD5 · raw file

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2006, 2007, 2008 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
  17. AtomService: Encapsulates the ability to perform insert, update and delete
  18. operations with the Atom Publishing Protocol on which GData is
  19. based. An instance can perform query, insertion, deletion, and
  20. update.
  21. HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
  22. to the specified end point. An AtomService object or a subclass can be
  23. used to specify information about the request.
  24. """
  25. __author__ = 'api.jscudder (Jeff Scudder)'
  26. import atom.http_interface
  27. import atom.url
  28. import atom.http
  29. import atom.token_store
  30. import os
  31. import httplib
  32. import urllib
  33. import re
  34. import base64
  35. import socket
  36. import warnings
  37. try:
  38. from xml.etree import cElementTree as ElementTree
  39. except ImportError:
  40. try:
  41. import cElementTree as ElementTree
  42. except ImportError:
  43. try:
  44. from xml.etree import ElementTree
  45. except ImportError:
  46. from elementtree import ElementTree
  47. import atom
  48. class AtomService(object):
  49. """Performs Atom Publishing Protocol CRUD operations.
  50. The AtomService contains methods to perform HTTP CRUD operations.
  51. """
  52. # Default values for members
  53. port = 80
  54. ssl = False
  55. # Set the current_token to force the AtomService to use this token
  56. # instead of searching for an appropriate token in the token_store.
  57. current_token = None
  58. auto_store_tokens = True
  59. auto_set_current_token = True
  60. def _get_override_token(self):
  61. return self.current_token
  62. def _set_override_token(self, token):
  63. self.current_token = token
  64. override_token = property(_get_override_token, _set_override_token)
  65. #@atom.v1_deprecated('Please use atom.client.AtomPubClient instead.')
  66. def __init__(self, server=None, additional_headers=None,
  67. application_name='', http_client=None, token_store=None):
  68. """Creates a new AtomService client.
  69. Args:
  70. server: string (optional) The start of a URL for the server
  71. to which all operations should be directed. Example:
  72. 'www.google.com'
  73. additional_headers: dict (optional) Any additional HTTP headers which
  74. should be included with CRUD operations.
  75. http_client: An object responsible for making HTTP requests using a
  76. request method. If none is provided, a new instance of
  77. atom.http.ProxiedHttpClient will be used.
  78. token_store: Keeps a collection of authorization tokens which can be
  79. applied to requests for a specific URLs. Critical methods are
  80. find_token based on a URL (atom.url.Url or a string), add_token,
  81. and remove_token.
  82. """
  83. self.http_client = http_client or atom.http.ProxiedHttpClient()
  84. self.token_store = token_store or atom.token_store.TokenStore()
  85. self.server = server
  86. self.additional_headers = additional_headers or {}
  87. self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (
  88. application_name,)
  89. # If debug is True, the HTTPConnection will display debug information
  90. self._set_debug(False)
  91. __init__ = atom.v1_deprecated(
  92. 'Please use atom.client.AtomPubClient instead.')(
  93. __init__)
  94. def _get_debug(self):
  95. return self.http_client.debug
  96. def _set_debug(self, value):
  97. self.http_client.debug = value
  98. debug = property(_get_debug, _set_debug,
  99. doc='If True, HTTP debug information is printed.')
  100. def use_basic_auth(self, username, password, scopes=None):
  101. if username is not None and password is not None:
  102. if scopes is None:
  103. scopes = [atom.token_store.SCOPE_ALL]
  104. base_64_string = base64.encodestring('%s:%s' % (username, password))
  105. token = BasicAuthToken('Basic %s' % base_64_string.strip(),
  106. scopes=[atom.token_store.SCOPE_ALL])
  107. if self.auto_set_current_token:
  108. self.current_token = token
  109. if self.auto_store_tokens:
  110. return self.token_store.add_token(token)
  111. return True
  112. return False
  113. def UseBasicAuth(self, username, password, for_proxy=False):
  114. """Sets an Authenticaiton: Basic HTTP header containing plaintext.
  115. Deprecated, use use_basic_auth instead.
  116. The username and password are base64 encoded and added to an HTTP header
  117. which will be included in each request. Note that your username and
  118. password are sent in plaintext.
  119. Args:
  120. username: str
  121. password: str
  122. """
  123. self.use_basic_auth(username, password)
  124. #@atom.v1_deprecated('Please use atom.client.AtomPubClient for requests.')
  125. def request(self, operation, url, data=None, headers=None,
  126. url_params=None):
  127. if isinstance(url, (str, unicode)):
  128. if url.startswith('http:') and self.ssl:
  129. # Force all requests to be https if self.ssl is True.
  130. url = atom.url.parse_url('https:' + url[5:])
  131. elif not url.startswith('http') and self.ssl:
  132. url = atom.url.parse_url('https://%s%s' % (self.server, url))
  133. elif not url.startswith('http'):
  134. url = atom.url.parse_url('http://%s%s' % (self.server, url))
  135. else:
  136. url = atom.url.parse_url(url)
  137. if url_params:
  138. for name, value in url_params.iteritems():
  139. url.params[name] = value
  140. all_headers = self.additional_headers.copy()
  141. if headers:
  142. all_headers.update(headers)
  143. # If the list of headers does not include a Content-Length, attempt to
  144. # calculate it based on the data object.
  145. if data and 'Content-Length' not in all_headers:
  146. content_length = CalculateDataLength(data)
  147. if content_length:
  148. all_headers['Content-Length'] = str(content_length)
  149. # Find an Authorization token for this URL if one is available.
  150. if self.override_token:
  151. auth_token = self.override_token
  152. else:
  153. auth_token = self.token_store.find_token(url)
  154. return auth_token.perform_request(self.http_client, operation, url,
  155. data=data, headers=all_headers)
  156. request = atom.v1_deprecated(
  157. 'Please use atom.client.AtomPubClient for requests.')(
  158. request)
  159. # CRUD operations
  160. def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
  161. """Query the APP server with the given URI
  162. The uri is the portion of the URI after the server value
  163. (server example: 'www.google.com').
  164. Example use:
  165. To perform a query against Google Base, set the server to
  166. 'base.google.com' and set the uri to '/base/feeds/...', where ... is
  167. your query. For example, to find snippets for all digital cameras uri
  168. should be set to: '/base/feeds/snippets?bq=digital+camera'
  169. Args:
  170. uri: string The query in the form of a URI. Example:
  171. '/base/feeds/snippets?bq=digital+camera'.
  172. extra_headers: dicty (optional) Extra HTTP headers to be included
  173. in the GET request. These headers are in addition to
  174. those stored in the client's additional_headers property.
  175. The client automatically sets the Content-Type and
  176. Authorization headers.
  177. url_params: dict (optional) Additional URL parameters to be included
  178. in the query. These are translated into query arguments
  179. in the form '&dict_key=value&...'.
  180. Example: {'max-results': '250'} becomes &max-results=250
  181. escape_params: boolean (optional) If false, the calling code has already
  182. ensured that the query will form a valid URL (all
  183. reserved characters have been escaped). If true, this
  184. method will escape the query and any URL parameters
  185. provided.
  186. Returns:
  187. httplib.HTTPResponse The server's response to the GET request.
  188. """
  189. return self.request('GET', uri, data=None, headers=extra_headers,
  190. url_params=url_params)
  191. def Post(self, data, uri, extra_headers=None, url_params=None,
  192. escape_params=True, content_type='application/atom+xml'):
  193. """Insert data into an APP server at the given URI.
  194. Args:
  195. data: string, ElementTree._Element, or something with a __str__ method
  196. The XML to be sent to the uri.
  197. uri: string The location (feed) to which the data should be inserted.
  198. Example: '/base/feeds/items'.
  199. extra_headers: dict (optional) HTTP headers which are to be included.
  200. The client automatically sets the Content-Type,
  201. Authorization, and Content-Length headers.
  202. url_params: dict (optional) Additional URL parameters to be included
  203. in the URI. These are translated into query arguments
  204. in the form '&dict_key=value&...'.
  205. Example: {'max-results': '250'} becomes &max-results=250
  206. escape_params: boolean (optional) If false, the calling code has already
  207. ensured that the query will form a valid URL (all
  208. reserved characters have been escaped). If true, this
  209. method will escape the query and any URL parameters
  210. provided.
  211. Returns:
  212. httplib.HTTPResponse Server's response to the POST request.
  213. """
  214. if extra_headers is None:
  215. extra_headers = {}
  216. if content_type:
  217. extra_headers['Content-Type'] = content_type
  218. return self.request('POST', uri, data=data, headers=extra_headers,
  219. url_params=url_params)
  220. def Put(self, data, uri, extra_headers=None, url_params=None,
  221. escape_params=True, content_type='application/atom+xml'):
  222. """Updates an entry at the given URI.
  223. Args:
  224. data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The
  225. XML containing the updated data.
  226. uri: string A URI indicating entry to which the update will be applied.
  227. Example: '/base/feeds/items/ITEM-ID'
  228. extra_headers: dict (optional) HTTP headers which are to be included.
  229. The client automatically sets the Content-Type,
  230. Authorization, and Content-Length headers.
  231. url_params: dict (optional) Additional URL parameters to be included
  232. in the URI. These are translated into query arguments
  233. in the form '&dict_key=value&...'.
  234. Example: {'max-results': '250'} becomes &max-results=250
  235. escape_params: boolean (optional) If false, the calling code has already
  236. ensured that the query will form a valid URL (all
  237. reserved characters have been escaped). If true, this
  238. method will escape the query and any URL parameters
  239. provided.
  240. Returns:
  241. httplib.HTTPResponse Server's response to the PUT request.
  242. """
  243. if extra_headers is None:
  244. extra_headers = {}
  245. if content_type:
  246. extra_headers['Content-Type'] = content_type
  247. return self.request('PUT', uri, data=data, headers=extra_headers,
  248. url_params=url_params)
  249. def Delete(self, uri, extra_headers=None, url_params=None,
  250. escape_params=True):
  251. """Deletes the entry at the given URI.
  252. Args:
  253. uri: string The URI of the entry to be deleted. Example:
  254. '/base/feeds/items/ITEM-ID'
  255. extra_headers: dict (optional) HTTP headers which are to be included.
  256. The client automatically sets the Content-Type and
  257. Authorization headers.
  258. url_params: dict (optional) Additional URL parameters to be included
  259. in the URI. These are translated into query arguments
  260. in the form '&dict_key=value&...'.
  261. Example: {'max-results': '250'} becomes &max-results=250
  262. escape_params: boolean (optional) If false, the calling code has already
  263. ensured that the query will form a valid URL (all
  264. reserved characters have been escaped). If true, this
  265. method will escape the query and any URL parameters
  266. provided.
  267. Returns:
  268. httplib.HTTPResponse Server's response to the DELETE request.
  269. """
  270. return self.request('DELETE', uri, data=None, headers=extra_headers,
  271. url_params=url_params)
  272. class BasicAuthToken(atom.http_interface.GenericToken):
  273. def __init__(self, auth_header, scopes=None):
  274. """Creates a token used to add Basic Auth headers to HTTP requests.
  275. Args:
  276. auth_header: str The value for the Authorization header.
  277. scopes: list of str or atom.url.Url specifying the beginnings of URLs
  278. for which this token can be used. For example, if scopes contains
  279. 'http://example.com/foo', then this token can be used for a request to
  280. 'http://example.com/foo/bar' but it cannot be used for a request to
  281. 'http://example.com/baz'
  282. """
  283. self.auth_header = auth_header
  284. self.scopes = scopes or []
  285. def perform_request(self, http_client, operation, url, data=None,
  286. headers=None):
  287. """Sets the Authorization header to the basic auth string."""
  288. if headers is None:
  289. headers = {'Authorization':self.auth_header}
  290. else:
  291. headers['Authorization'] = self.auth_header
  292. return http_client.request(operation, url, data=data, headers=headers)
  293. def __str__(self):
  294. return self.auth_header
  295. def valid_for_scope(self, url):
  296. """Tells the caller if the token authorizes access to the desired URL.
  297. """
  298. if isinstance(url, (str, unicode)):
  299. url = atom.url.parse_url(url)
  300. for scope in self.scopes:
  301. if scope == atom.token_store.SCOPE_ALL:
  302. return True
  303. if isinstance(scope, (str, unicode)):
  304. scope = atom.url.parse_url(scope)
  305. if scope == url:
  306. return True
  307. # Check the host and the path, but ignore the port and protocol.
  308. elif scope.host == url.host and not scope.path:
  309. return True
  310. elif scope.host == url.host and scope.path and not url.path:
  311. continue
  312. elif scope.host == url.host and url.path.startswith(scope.path):
  313. return True
  314. return False
  315. def PrepareConnection(service, full_uri):
  316. """Opens a connection to the server based on the full URI.
  317. This method is deprecated, instead use atom.http.HttpClient.request.
  318. Examines the target URI and the proxy settings, which are set as
  319. environment variables, to open a connection with the server. This
  320. connection is used to make an HTTP request.
  321. Args:
  322. service: atom.AtomService or a subclass. It must have a server string which
  323. represents the server host to which the request should be made. It may also
  324. have a dictionary of additional_headers to send in the HTTP request.
  325. full_uri: str Which is the target relative (lacks protocol and host) or
  326. absolute URL to be opened. Example:
  327. 'https://www.google.com/accounts/ClientLogin' or
  328. 'base/feeds/snippets' where the server is set to www.google.com.
  329. Returns:
  330. A tuple containing the httplib.HTTPConnection and the full_uri for the
  331. request.
  332. """
  333. deprecation('calling deprecated function PrepareConnection')
  334. (server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
  335. if ssl:
  336. # destination is https
  337. proxy = os.environ.get('https_proxy')
  338. if proxy:
  339. (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
  340. proxy_username = os.environ.get('proxy-username')
  341. if not proxy_username:
  342. proxy_username = os.environ.get('proxy_username')
  343. proxy_password = os.environ.get('proxy-password')
  344. if not proxy_password:
  345. proxy_password = os.environ.get('proxy_password')
  346. if proxy_username:
  347. user_auth = base64.encodestring('%s:%s' % (proxy_username,
  348. proxy_password))
  349. proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
  350. user_auth.strip()))
  351. else:
  352. proxy_authorization = ''
  353. proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
  354. user_agent = 'User-Agent: %s\r\n' % (
  355. service.additional_headers['User-Agent'])
  356. proxy_pieces = (proxy_connect + proxy_authorization + user_agent
  357. + '\r\n')
  358. #now connect, very simple recv and error checking
  359. p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  360. p_sock.connect((p_server,p_port))
  361. p_sock.sendall(proxy_pieces)
  362. response = ''
  363. # Wait for the full response.
  364. while response.find("\r\n\r\n") == -1:
  365. response += p_sock.recv(8192)
  366. p_status=response.split()[1]
  367. if p_status!=str(200):
  368. raise 'Error status=',str(p_status)
  369. # Trivial setup for ssl socket.
  370. ssl = socket.ssl(p_sock, None, None)
  371. fake_sock = httplib.FakeSocket(p_sock, ssl)
  372. # Initalize httplib and replace with the proxy socket.
  373. connection = httplib.HTTPConnection(server)
  374. connection.sock=fake_sock
  375. full_uri = partial_uri
  376. else:
  377. connection = httplib.HTTPSConnection(server, port)
  378. full_uri = partial_uri
  379. else:
  380. # destination is http
  381. proxy = os.environ.get('http_proxy')
  382. if proxy:
  383. (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
  384. proxy_username = os.environ.get('proxy-username')
  385. if not proxy_username:
  386. proxy_username = os.environ.get('proxy_username')
  387. proxy_password = os.environ.get('proxy-password')
  388. if not proxy_password:
  389. proxy_password = os.environ.get('proxy_password')
  390. if proxy_username:
  391. UseBasicAuth(service, proxy_username, proxy_password, True)
  392. connection = httplib.HTTPConnection(p_server, p_port)
  393. if not full_uri.startswith("http://"):
  394. if full_uri.startswith("/"):
  395. full_uri = "http://%s%s" % (service.server, full_uri)
  396. else:
  397. full_uri = "http://%s/%s" % (service.server, full_uri)
  398. else:
  399. connection = httplib.HTTPConnection(server, port)
  400. full_uri = partial_uri
  401. return (connection, full_uri)
  402. def UseBasicAuth(service, username, password, for_proxy=False):
  403. """Sets an Authenticaiton: Basic HTTP header containing plaintext.
  404. Deprecated, use AtomService.use_basic_auth insread.
  405. The username and password are base64 encoded and added to an HTTP header
  406. which will be included in each request. Note that your username and
  407. password are sent in plaintext. The auth header is added to the
  408. additional_headers dictionary in the service object.
  409. Args:
  410. service: atom.AtomService or a subclass which has an
  411. additional_headers dict as a member.
  412. username: str
  413. password: str
  414. """
  415. deprecation('calling deprecated function UseBasicAuth')
  416. base_64_string = base64.encodestring('%s:%s' % (username, password))
  417. base_64_string = base_64_string.strip()
  418. if for_proxy:
  419. header_name = 'Proxy-Authorization'
  420. else:
  421. header_name = 'Authorization'
  422. service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
  423. def ProcessUrl(service, url, for_proxy=False):
  424. """Processes a passed URL. If the URL does not begin with https?, then
  425. the default value for server is used
  426. This method is deprecated, use atom.url.parse_url instead.
  427. """
  428. if not isinstance(url, atom.url.Url):
  429. url = atom.url.parse_url(url)
  430. server = url.host
  431. ssl = False
  432. port = 80
  433. if not server:
  434. if hasattr(service, 'server'):
  435. server = service.server
  436. else:
  437. server = service
  438. if not url.protocol and hasattr(service, 'ssl'):
  439. ssl = service.ssl
  440. if hasattr(service, 'port'):
  441. port = service.port
  442. else:
  443. if url.protocol == 'https':
  444. ssl = True
  445. elif url.protocol == 'http':
  446. ssl = False
  447. if url.port:
  448. port = int(url.port)
  449. elif port == 80 and ssl:
  450. port = 443
  451. return (server, port, ssl, url.get_request_uri())
  452. def DictionaryToParamList(url_parameters, escape_params=True):
  453. """Convert a dictionary of URL arguments into a URL parameter string.
  454. This function is deprcated, use atom.url.Url instead.
  455. Args:
  456. url_parameters: The dictionaty of key-value pairs which will be converted
  457. into URL parameters. For example,
  458. {'dry-run': 'true', 'foo': 'bar'}
  459. will become ['dry-run=true', 'foo=bar'].
  460. Returns:
  461. A list which contains a string for each key-value pair. The strings are
  462. ready to be incorporated into a URL by using '&'.join([] + parameter_list)
  463. """
  464. # Choose which function to use when modifying the query and parameters.
  465. # Use quote_plus when escape_params is true.
  466. transform_op = [str, urllib.quote_plus][bool(escape_params)]
  467. # Create a list of tuples containing the escaped version of the
  468. # parameter-value pairs.
  469. parameter_tuples = [(transform_op(param), transform_op(value))
  470. for param, value in (url_parameters or {}).items()]
  471. # Turn parameter-value tuples into a list of strings in the form
  472. # 'PARAMETER=VALUE'.
  473. return ['='.join(x) for x in parameter_tuples]
  474. def BuildUri(uri, url_params=None, escape_params=True):
  475. """Converts a uri string and a collection of parameters into a URI.
  476. This function is deprcated, use atom.url.Url instead.
  477. Args:
  478. uri: string
  479. url_params: dict (optional)
  480. escape_params: boolean (optional)
  481. uri: string The start of the desired URI. This string can alrady contain
  482. URL parameters. Examples: '/base/feeds/snippets',
  483. '/base/feeds/snippets?bq=digital+camera'
  484. url_parameters: dict (optional) Additional URL parameters to be included
  485. in the query. These are translated into query arguments
  486. in the form '&dict_key=value&...'.
  487. Example: {'max-results': '250'} becomes &max-results=250
  488. escape_params: boolean (optional) If false, the calling code has already
  489. ensured that the query will form a valid URL (all
  490. reserved characters have been escaped). If true, this
  491. method will escape the query and any URL parameters
  492. provided.
  493. Returns:
  494. string The URI consisting of the escaped URL parameters appended to the
  495. initial uri string.
  496. """
  497. # Prepare URL parameters for inclusion into the GET request.
  498. parameter_list = DictionaryToParamList(url_params, escape_params)
  499. # Append the URL parameters to the URL.
  500. if parameter_list:
  501. if uri.find('?') != -1:
  502. # If there are already URL parameters in the uri string, add the
  503. # parameters after a new & character.
  504. full_uri = '&'.join([uri] + parameter_list)
  505. else:
  506. # The uri string did not have any URL parameters (no ? character)
  507. # so put a ? between the uri and URL parameters.
  508. full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))
  509. else:
  510. full_uri = uri
  511. return full_uri
  512. def HttpRequest(service, operation, data, uri, extra_headers=None,
  513. url_params=None, escape_params=True, content_type='application/atom+xml'):
  514. """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
  515. This method is deprecated, use atom.http.HttpClient.request instead.
  516. Usage example, perform and HTTP GET on http://www.google.com/:
  517. import atom.service
  518. client = atom.service.AtomService()
  519. http_response = client.Get('http://www.google.com/')
  520. or you could set the client.server to 'www.google.com' and use the
  521. following:
  522. client.server = 'www.google.com'
  523. http_response = client.Get('/')
  524. Args:
  525. service: atom.AtomService object which contains some of the parameters
  526. needed to make the request. The following members are used to
  527. construct the HTTP call: server (str), additional_headers (dict),
  528. port (int), and ssl (bool).
  529. operation: str The HTTP operation to be performed. This is usually one of
  530. 'GET', 'POST', 'PUT', or 'DELETE'
  531. data: ElementTree, filestream, list of parts, or other object which can be
  532. converted to a string.
  533. Should be set to None when performing a GET or PUT.
  534. If data is a file-like object which can be read, this method will read
  535. a chunk of 100K bytes at a time and send them.
  536. If the data is a list of parts to be sent, each part will be evaluated
  537. and sent.
  538. uri: The beginning of the URL to which the request should be sent.
  539. Examples: '/', '/base/feeds/snippets',
  540. '/m8/feeds/contacts/default/base'
  541. extra_headers: dict of strings. HTTP headers which should be sent
  542. in the request. These headers are in addition to those stored in
  543. service.additional_headers.
  544. url_params: dict of strings. Key value pairs to be added to the URL as
  545. URL parameters. For example {'foo':'bar', 'test':'param'} will
  546. become ?foo=bar&test=param.
  547. escape_params: bool default True. If true, the keys and values in
  548. url_params will be URL escaped when the form is constructed
  549. (Special characters converted to %XX form.)
  550. content_type: str The MIME type for the data being sent. Defaults to
  551. 'application/atom+xml', this is only used if data is set.
  552. """
  553. deprecation('call to deprecated function HttpRequest')
  554. full_uri = BuildUri(uri, url_params, escape_params)
  555. (connection, full_uri) = PrepareConnection(service, full_uri)
  556. if extra_headers is None:
  557. extra_headers = {}
  558. # Turn on debug mode if the debug member is set.
  559. if service.debug:
  560. connection.debuglevel = 1
  561. connection.putrequest(operation, full_uri)
  562. # If the list of headers does not include a Content-Length, attempt to
  563. # calculate it based on the data object.
  564. if (data and not service.additional_headers.has_key('Content-Length') and
  565. not extra_headers.has_key('Content-Length')):
  566. content_length = CalculateDataLength(data)
  567. if content_length:
  568. extra_headers['Content-Length'] = str(content_length)
  569. if content_type:
  570. extra_headers['Content-Type'] = content_type
  571. # Send the HTTP headers.
  572. if isinstance(service.additional_headers, dict):
  573. for header in service.additional_headers:
  574. connection.putheader(header, service.additional_headers[header])
  575. if isinstance(extra_headers, dict):
  576. for header in extra_headers:
  577. connection.putheader(header, extra_headers[header])
  578. connection.endheaders()
  579. # If there is data, send it in the request.
  580. if data:
  581. if isinstance(data, list):
  582. for data_part in data:
  583. __SendDataPart(data_part, connection)
  584. else:
  585. __SendDataPart(data, connection)
  586. # Return the HTTP Response from the server.
  587. return connection.getresponse()
  588. def __SendDataPart(data, connection):
  589. """This method is deprecated, use atom.http._send_data_part"""
  590. deprecated('call to deprecated function __SendDataPart')
  591. if isinstance(data, str):
  592. #TODO add handling for unicode.
  593. connection.send(data)
  594. return
  595. elif ElementTree.iselement(data):
  596. connection.send(ElementTree.tostring(data))
  597. return
  598. # Check to see if data is a file-like object that has a read method.
  599. elif hasattr(data, 'read'):
  600. # Read the file and send it a chunk at a time.
  601. while 1:
  602. binarydata = data.read(100000)
  603. if binarydata == '': break
  604. connection.send(binarydata)
  605. return
  606. else:
  607. # The data object was not a file.
  608. # Try to convert to a string and send the data.
  609. connection.send(str(data))
  610. return
  611. def CalculateDataLength(data):
  612. """Attempts to determine the length of the data to send.
  613. This method will respond with a length only if the data is a string or
  614. and ElementTree element.
  615. Args:
  616. data: object If this is not a string or ElementTree element this funtion
  617. will return None.
  618. """
  619. if isinstance(data, str):
  620. return len(data)
  621. elif isinstance(data, list):
  622. return None
  623. elif ElementTree.iselement(data):
  624. return len(ElementTree.tostring(data))
  625. elif hasattr(data, 'read'):
  626. # If this is a file-like object, don't try to guess the length.
  627. return None
  628. else:
  629. return len(str(data))
  630. def deprecation(message):
  631. warnings.warn(message, DeprecationWarning, stacklevel=2)