Package tlib :: Package base :: Module HttpRequestor |
[hide private]
[frames] | no frames]

# Source Code for Module tlib.base.HttpRequestor

      1  import urllib2
      2  import urllib
      3  import json
      4  from logging import Logger
      5
      6 -class HttpRequestor(object):
      7      """
      8      Helper class for sending requests of HTTP with GET and POST
      9      """
     10
     11      api_url = ""                    #: domain url to use when sending requests
     12      api_method = ""                 #: api method to use when sending requests
     13      api_params = ""                 #: parameters to send to the method when sending requests
     14      api_header = {}                 #: Authorization to put into header when sending requests
     15      api_post_payload = {}           #: Payload to be delivered when sending a POST request
     16      logger = None                   #: logger to send loggin information to.  Logger comes from pytest test definitions
     17      api_path_params = ""            #:
     18      formatted_params = ""           #:
     19
     20 -    def __init__(self, api_url, logger):
     21          """
     22          Constructor for class
     23
     24          @param api_url: URL to the base of the API
     25          @type api_url: str
     26          @param logger: instance of a logging object configured in testing project
     27          @type logger: Logger
     28
     29          """
     30
     31          self.api_url = api_url
     32          self.logger = logger
     33
     34 -    def make_path_params(self, params):
     35          """
     36          Constucts a request with the parameters formated in path parameter format.
     37          EX: http://myserver.com/api/method/pathParam1/pathParam2
     38
     39          @param params: a list of parameter values to send to the api
     40          @type params: dict
     41          """
     42
     43          path_params = ""
     44
     45          for param in params:
     46              path_params = path_params + "/" + param
     47
     48          #path params must be at the start of the parameter list
     49          self.formatted_params = urllib.quote_plus(path_params, "/") + self.formatted_params
     50
     51 -    def make_query_params(self, params):
     52          """
     53          Constucts a request with the parameters formated in query parameter format.
     54          EX: http://myserver.com/api/method?queryParam=paramValue
     55
     56          @param params: a dictionary of parameter names and values to send to the api
     57          @type params: dict
     58          """
     59
     60          encoded_param = urllib.urlencode(params)
     61
     62          #query params must be at the end of the paramater list
     63          self.formatted_params = self.formatted_params + "?" + encoded_param
     64
     65 -    def make_get_request(self):
     66          """
     67          Sends a GET HTTP request.  Make sure you have set the classe's api_params,api_url and api_method first
     68
     69          Args :null
     70
     71          Returns : (file-like object) the HTTP response
     72
     73          Raises :null
     74          """
     75
     76          url = self.api_url + self.api_method
     77          request = urllib2.Request(url + self.formatted_params)
     78
     79          if len(self.api_header) > 0:
     80              for key in self.api_header.keys():
     81                  request.add_header(key, self.api_header[key])
     82
     83          self.logger.info(request.get_full_url())
     84          self.logger.info(request.get_data())
     85          self.logger.info(request.get_method())
     86
     87          try:
     88
     89              return urllib2.urlopen(request)
     90
     91          except urllib2.URLError, e:
     92              return e
     93          finally:
     94              self.formatted_params = ""
     95
     96 -    def make_post_request(self):
     97          """
     98          Sends a POST HTTP request.  Make sure you have set the classe's api_params,api_url,
     99          api_header and api_method first
    100
    101          Returns : (file-like object) the HTTP response
    102          """
    103          url = self.api_url + self.api_method
    104          request = urllib2.Request(url)
    105
    106          encoded_param = urllib.urlencode(self.api_params)
    107          request.add_data(encoded_param)
    108
    109          if self.api_post_payload:
    110              request.add_data(json.dumps(self.api_post_payload))
    111
    112          for key in self.api_header.keys():
    113              request.add_header(key, self.api_header[key])
    114
    115          try:
    116
    117              self.logger.info(request.get_full_url())
    118              self.logger.info(request.get_data())
    119              self.logger.info(request.get_method())
    120              return urllib2.urlopen(request)
    121
    122          except urllib2.URLError, e:
    123              return e
    124          finally:
    125              self.formatted_params = ""
    126
    127 -    def get_auth(self, credentials):
    128          """
    129          Creates the authentication for accessing HTTP
    130
    131          @param credentials: 'username' and 'password' keys for a dictionary containing the HTTP Basic Auth to access
    132          the api
    133          @type credentials: dict
    134          """
    135
    136          # create a handler for the username / password
    137          passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
    138          # none is so that all pages under the realm are opened with password
    139          passman.add_password(None, self.api_url, credentials['username'], credentials['password'])
    140
    141          # authenticate and open the website
    142          authhandler = urllib2.HTTPBasicAuthHandler(passman)
    143          opener = urllib2.build_opener(authhandler)
    144          urllib2.install_opener(opener)
    145