def postImage(img_data, data, job):
    """
    Sends the data to the data service via a post

    Args:
        * img_data(np.Array): Numpy array of i x j x channels
        * data (cube): The cube metadata is used for the post
            metadata
        * job (Job): job
    """
    tempfilep = os.path.join(tempfile.gettempdir(), "temp.png")

    with open(tempfilep, "wb") as img:
        imageproc.writePng(img_data, img,
                  nchannels=3, alpha=False)
    payload = getPostDict(data, img_data, job)

    print "Attempting to post image"
    try:
        with open(tempfilep, "rb") as img:
            # for attempt in range(100): # deals with connection errors etc
            r = requests.post(conf.img_data_server, data=payload, files={"data": img})
            time.sleep(2)
                # if r.status_code == 201:
                #     break
        if r.status_code != 201:
            raise IOError(r.status_code, r.text, "for messge", payload)  
        else:
            print "Headers: ", r.headers
            print "Status code: ", r.status_code  
    finally:
        os.remove(tempfilep)
def proc_cube(cube):
    for i, frt_cube in enumerate(cube.slices_over("time")):
        print "Processing timestep ", i, "...",
        img_array = imageproc.tileArray(frt_cube.data)
        img_array /= img_array.max()
        img_array *= 255
        print "Writing image"
        with open("data%03d.png" % i, "wb") as img:
            imageproc.writePng(img_array, img, nchannels=3, alpha=False)
    
    print "Writing video"
    sp.call(["avconv", "-y",
            "-r", "1", "-i", "data%03d.png",
            "-r", "1", "-vcodec", os.getenv("CODEC", "libtheora"), "-qscale:v", os.getenv("QUALITY", 2), os.getenv("FILE_OUT", "out.ogv"])
    print "Cleaning up"
    fs = glob.glob("./data???.png")
    for f in fs:
        os.remove(f)
        
if __name__=="__main__":
    varname = os.getenv("VAR_NAME")
    if varname != None:
        cube = iris.load_cube(os.getenv("FILE_IN"), iris.Constraint(varname))
    else:
        cube = iris.load_cube(os.getenv("FILE_IN"))
    proc_cube(cube)
def postImage(img_data, data, field_width, field_height):
    """
    Sends the data to the data service via a post

    Args:
        * img_data(np.Array): Numpy array of i x j x channels
        * data (cube): The cube metadata is used for the post
            metadata
    """
    tempfilep = os.path.join(tempfile.gettempdir(), "temp.png")
    with open(tempfilep, "wb") as img:
        imageproc.writePng(img_data, img,
                  height=field_height, width=field_width*2,
                  nchannels=3, alpha=False)
    payload = getPostDict(data)
    try:
        with open(tempfilep, "rb") as img:
            r = requests.post(conf.img_data_server, data=payload, files={"data": img})
        if r.status_code != 201:
            raise IOError(r.status_code, r.text)
    finally:
        os.remove(tempfilep)