fuel-main/fuelweb_test/helpers/http.py
2014-03-25 14:56:53 +00:00

65 lines
2.2 KiB
Python

# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base64
import json
import urllib2
from fuelweb_test import logger
class HTTPClient(object):
base64string = None
def __init__(self, url, user=None, password=None):
logger.info('Initiate HTTPClient with url %s', url)
self.url = url
if user and password:
creds = '{0}:{1}'.format(user, password)
logger.info('Set credentials to %s', creds)
self.base64string = base64.standard_b64encode(creds)
self.opener = urllib2.build_opener(urllib2.HTTPHandler)
def get(self, endpoint):
req = urllib2.Request(self.url + endpoint)
return self._open(req)
def post(self, endpoint, data=None, content_type="application/json"):
if not data:
data = {}
logger.info('self url is %s' % self.url)
req = urllib2.Request(self.url + endpoint, data=json.dumps(data))
req.add_header('Content-Type', content_type)
return self._open(req)
def put(self, endpoint, data=None, content_type="application/json"):
if not data:
data = {}
req = urllib2.Request(self.url + endpoint, data=json.dumps(data))
req.add_header('Content-Type', content_type)
req.get_method = lambda: 'PUT'
return self._open(req)
def delete(self, endpoint):
req = urllib2.Request(self.url + endpoint)
req.get_method = lambda: 'DELETE'
return self._open(req)
def _open(self, req):
if self.base64string:
req.add_header("Authorization", "Basic %s" % self.base64string)
return self.opener.open(req)