Welcome, guest | Sign In | My Account | Store | Cart

Have you ever published a recipe to UtilityMill.com and then wished that you could remotely execute your program? Now that is easy to do with the following supporting library! Running the latest version of your program is easy with the "run_latest(name, query)" command and requires no knowledge of UM's API -- just supply the program's name and keyword arguments that it requires for execution. "utility_mill" is easy to use and can be customized with access to more specific commands available to you. You do not need to know the latest version number? Just use "get_results(name, version, query)" instead to save a call to the server!

Python, 57 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import urllib.request
import urllib.parse
import xml.dom.minidom

################################################################################

INFO = 'http://utilitymill.com/api/{API}/utility/{NAME}/info'
RUN = 'http://utilitymill.com/api/{API}/utility/{NAME}/{VERSION}/run?{QUERY}'

################################################################################

def run_latest(name, **query):
    version = get_version(name)
    results = get_results(name, version, query)
    return results

################################################################################

def get_version(name):
    string = fix(info('xml', name))
    dom = xml.dom.minidom.parseString(string)
    value = extract(dom, 'number', 'TEXT_NODE')
    dom.unlink()
    return value

def get_results(name, version, query):
    string = fix(run('xml', name, version, query))
    dom = xml.dom.minidom.parseString(string)
    value = extract(dom, 'output', 'CDATA_SECTION_NODE')
    dom.unlink()
    return value

################################################################################

def info(api, name):
    url = INFO.format(API=api, NAME=name)
    return urllib.request.urlopen(url).read().decode()

def run(api, name, version, query):
    query = urllib.parse.urlencode(query)
    url = RUN.format(API=api, NAME=name, VERSION=version, QUERY=query)
    return urllib.request.urlopen(url).read().decode()

################################################################################

fix = lambda xml: '<' + xml.split('<', 1)[1].rsplit('>', 1)[0] + '>'

def extract(dom, tag_name, node_type):
    elements = dom.getElementsByTagName(tag_name)
    assert len(elements) == 1, 'XML Error'
    element = elements[0]
    if element.childNodes:
        assert len(element.childNodes) == 1, 'XML Error'
        child = element.childNodes[0]
        assert child.nodeType == getattr(child, node_type), 'XML Error'
        return child.nodeValue
    return ''

1 comment

greg p 14 years, 10 months ago  # | flag

Wow, cool beans. I can't wait to try it out.