home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / atom / client.py < prev    next >
Encoding:
Python Source  |  2010-02-26  |  6.6 KB  |  183 lines

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