Moab Web Services > References > Client Code Samples > Python Code Examples

Python Code Examples

Notice the use of the json module to build a Python object from the return JSON data. If you want, you an also use json.dumps to create a JSON string from a Python object.

Simple request (GET)

import httplib
import base64
import string
import json
def get(base, port, url):
	conn = httplib.HTTPConnection(base, port, timeout=60)
	conn.request('GET', url, None, { 'Authorization' : 'Basic '+string.strip(base64.encodestring('admin:secret'))})
	return conn.getresponse().read()

data = get("localhost", 8080, "/mws/rest/jobs?format=json")
print json.loads(data)

Complex request (POST)

import httplib
import base64
import string
import json
def post(base, port, url, payload):
	conn = httplib.HTTPConnection(base, port, timeout=60)
	conn.request('POST', url, payload, { 'Authorization' : 'Basic '+string.strip(base64.encodestring('admin:secret')), 'Content-Type' : 'application/json' })
	r = conn.getresponse()
	return r.read()

# Note that json.dumps may also be used to create the json string from a python object
data = post("localhost", 8080, "/mws/rest/jobs", '{"commandFile":"/tmp/test.sh","initialWorkingDirectory":"/tmp","user":"adaptive","requirements":[{"requiredNodeCountMinimum":1}]}')
print json.loads(data)

Related Topics 

© 2015 Adaptive Computing