/atom/client.py

http://radioappz.googlecode.com/ · Python · 182 lines · 81 code · 29 blank · 72 comment · 9 complexity · 34d7b6735437f73be022c26882ca3653 MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2009 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. """AtomPubClient provides CRUD ops. in line with the Atom Publishing Protocol.
  17. """
  18. __author__ = 'j.s@google.com (Jeff Scudder)'
  19. import atom.http_core
  20. class Error(Exception):
  21. pass
  22. class MissingHost(Error):
  23. pass
  24. class AtomPubClient(object):
  25. host = None
  26. auth_token = None
  27. ssl = False # Whether to force all requests over https
  28. def __init__(self, http_client=None, host=None,
  29. auth_token=None, source=None, **kwargs):
  30. """Creates a new AtomPubClient instance.
  31. Args:
  32. source: The name of your application.
  33. http_client: An object capable of performing HTTP requests through a
  34. request method. This object is used to perform the request
  35. when the AtomPubClient's request method is called. Used to
  36. allow HTTP requests to be directed to a mock server, or use
  37. an alternate library instead of the default of httplib to
  38. make HTTP requests.
  39. host: str The default host name to use if a host is not specified in the
  40. requested URI.
  41. auth_token: An object which sets the HTTP Authorization header when its
  42. modify_request method is called.
  43. """
  44. self.http_client = http_client or atom.http_core.ProxiedHttpClient()
  45. if host is not None:
  46. self.host = host
  47. if auth_token is not None:
  48. self.auth_token = auth_token
  49. self.source = source
  50. def request(self, method=None, uri=None, auth_token=None,
  51. http_request=None, **kwargs):
  52. """Performs an HTTP request to the server indicated.
  53. Uses the http_client instance to make the request.
  54. Args:
  55. method: The HTTP method as a string, usually one of 'GET', 'POST',
  56. 'PUT', or 'DELETE'
  57. uri: The URI desired as a string or atom.http_core.Uri.
  58. http_request:
  59. auth_token: An authorization token object whose modify_request method
  60. sets the HTTP Authorization header.
  61. Returns:
  62. The results of calling self.http_client.request. With the default
  63. http_client, this is an HTTP response object.
  64. """
  65. # Modify the request based on the AtomPubClient settings and parameters
  66. # passed in to the request.
  67. http_request = self.modify_request(http_request)
  68. if isinstance(uri, (str, unicode)):
  69. uri = atom.http_core.Uri.parse_uri(uri)
  70. if uri is not None:
  71. uri.modify_request(http_request)
  72. if isinstance(method, (str, unicode)):
  73. http_request.method = method
  74. # Any unrecognized arguments are assumed to be capable of modifying the
  75. # HTTP request.
  76. for name, value in kwargs.iteritems():
  77. if value is not None:
  78. value.modify_request(http_request)
  79. # Default to an http request if the protocol scheme is not set.
  80. if http_request.uri.scheme is None:
  81. http_request.uri.scheme = 'http'
  82. # Override scheme. Force requests over https.
  83. if self.ssl:
  84. http_request.uri.scheme = 'https'
  85. if http_request.uri.path is None:
  86. http_request.uri.path = '/'
  87. # Add the Authorization header at the very end. The Authorization header
  88. # value may need to be calculated using information in the request.
  89. if auth_token:
  90. auth_token.modify_request(http_request)
  91. elif self.auth_token:
  92. self.auth_token.modify_request(http_request)
  93. # Check to make sure there is a host in the http_request.
  94. if http_request.uri.host is None:
  95. raise MissingHost('No host provided in request %s %s' % (
  96. http_request.method, str(http_request.uri)))
  97. # Perform the fully specified request using the http_client instance.
  98. # Sends the request to the server and returns the server's response.
  99. return self.http_client.request(http_request)
  100. Request = request
  101. def get(self, uri=None, auth_token=None, http_request=None, **kwargs):
  102. """Performs a request using the GET method, returns an HTTP response."""
  103. return self.request(method='GET', uri=uri, auth_token=auth_token,
  104. http_request=http_request, **kwargs)
  105. Get = get
  106. def post(self, uri=None, data=None, auth_token=None, http_request=None,
  107. **kwargs):
  108. """Sends data using the POST method, returns an HTTP response."""
  109. return self.request(method='POST', uri=uri, auth_token=auth_token,
  110. http_request=http_request, data=data, **kwargs)
  111. Post = post
  112. def put(self, uri=None, data=None, auth_token=None, http_request=None,
  113. **kwargs):
  114. """Sends data using the PUT method, returns an HTTP response."""
  115. return self.request(method='PUT', uri=uri, auth_token=auth_token,
  116. http_request=http_request, data=data, **kwargs)
  117. Put = put
  118. def delete(self, uri=None, auth_token=None, http_request=None, **kwargs):
  119. """Performs a request using the DELETE method, returns an HTTP response."""
  120. return self.request(method='DELETE', uri=uri, auth_token=auth_token,
  121. http_request=http_request, **kwargs)
  122. Delete = delete
  123. def modify_request(self, http_request):
  124. """Changes the HTTP request before sending it to the server.
  125. Sets the User-Agent HTTP header and fills in the HTTP host portion
  126. of the URL if one was not included in the request (for this it uses
  127. the self.host member if one is set). This method is called in
  128. self.request.
  129. Args:
  130. http_request: An atom.http_core.HttpRequest() (optional) If one is
  131. not provided, a new HttpRequest is instantiated.
  132. Returns:
  133. An atom.http_core.HttpRequest() with the User-Agent header set and
  134. if this client has a value in its host member, the host in the request
  135. URL is set.
  136. """
  137. if http_request is None:
  138. http_request = atom.http_core.HttpRequest()
  139. if self.host is not None and http_request.uri.host is None:
  140. http_request.uri.host = self.host
  141. # Set the user agent header for logging purposes.
  142. if self.source:
  143. http_request.headers['User-Agent'] = '%s gdata-py/2.0.9' % self.source
  144. else:
  145. http_request.headers['User-Agent'] = 'gdata-py/2.0.9'
  146. return http_request
  147. ModifyRequest = modify_request