Skip to content

Instantly share code, notes, and snippets.

@mccun934
Created January 26, 2012 01:52
Show Gist options
  • Save mccun934/1680417 to your computer and use it in GitHub Desktop.
Save mccun934/1680417 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import base64
import httplib
import urllib
try:
import json
except ImportError:
import simplejson as json
def process_response(response):
response_body = response.read()
try:
response_body = json.loads(response_body, encoding='utf-8')
except:
pass
print response.status
print response_body
print response.getheaders()
return (response.status, response_body, response.getheaders())
def https_connection(host, port=443):
return httplib.HTTPSConnection(host, port)
def build_url(path, queries=()):
path_prefix = '/headpin/api'
path = '/'.join((path_prefix, path))
path = urllib.quote(str(path))
queries = urllib.urlencode(queries)
if queries:
path = '?'.join((path, queries))
return path
def prepare_body(body, multipart):
content_type = 'application/json'
#if multipart:
# content_type, body = self._encode_multipart_formdata(body)
#elif not isinstance(body, (type(None), Bytes, file)):
body = json.dumps(body)
return (content_type, body)
def request(method, path, queries=(), body=None, multipart=False, customHeaders={}):
username = 'admin'
password = 'admin'
headers = {}
raw = ':'.join((username, password))
encoded = base64.encodestring(raw)[:-1]
headers['Authorization'] = 'Basic ' + encoded
connection = https_connection('cubert.usersys.redhat.com')
url = build_url(path,queries)
content_type, body = prepare_body(body, multipart)
headers['content-type'] = content_type
headers['content-length'] = str(len(body) if body else 0)
print url
connection.request(method, url, body=body, headers=dict(headers.items() + customHeaders.items()))
return process_response(connection.getresponse())
def POST(path, body, multipart=False, customHeaders={}):
return request('POST', path, body=body, multipart=multipart, customHeaders=customHeaders)
def register(name, org):
#path = "/consumers/?owner=%s" % org
path = "environments/166/systems"
#path = "/api/organizations/%s/systems" % org
sysdata = {
"name" : name,
"cp_type" : "system",
"facts" : {
"distribution.name": "Fedora",
"cpu.cpu_socket(s)": "1"}
}
return POST(path, sysdata)[1]
register('restfulserver', 'ACME_Corporation')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment