rrdweb/rrd.py
changeset 32 47e977c23ba2
parent 29 c756e522c9ac
--- a/rrdweb/rrd.py	Tue Jan 25 01:19:40 2011 +0200
+++ b/rrdweb/rrd.py	Tue Jan 25 01:28:06 2011 +0200
@@ -4,7 +4,9 @@
 
 import rrdtool
 
+import tempfile
 import logging
+import os
 
 log = logging.getLogger('rrdweb.rrd')
 
@@ -89,16 +91,58 @@
 
     return func(*args)
 
-def graph (out_path, *args, **opts) :
+def graph (out, *args, **opts) :
     """
-        Create a graph from data stored in one or several RRDs.
+        Render a graph image and/or print a report from data stored in one or several RRDs.
 
-        Graph image output is written to the given path.
+        If the output path is given, the graph data is written to the given file, otherwise a temporary file is
+        created. The resulting output file is returned as an opened file object, ready to read() the graph data.
 
-        Returns... something to do with the image's dimensions, or even the data itself?
+        In the temporary file case, the returned file is unlinked before being returned.
+
+        If out is explicitly given as False, no graph output is generated, and graph_file is returned as None.
+
+        Returns a (width, height, [ report output lines ], graph_file) tuple.
     """
+    
+    # open/tempfile
+    if out is None :
+        # tempfile
+        tmp_fd, out_path = tempfile.mkstemp('.png')
 
-    return run_cmd(rrdtool.graph, (out_path, ), opts, args)
+        # disregard the tmp_fd, we re-open the file after it's been written out
+        os.close(tmp_fd)
+        
+    elif out is False :
+        # no output
+        tmp_fd = None
+        out_path = ''
+
+    else :
+        # direct output
+        tmp_fd = None
+        out_path = out
+    
+    # render
+    try :
+        # invoke
+        width, height, output = run_cmd(rrdtool.graph, (out_path, ), opts, args)
+        
+        # return resulting file
+        if out_path :
+            out_file = open(out_path, 'r')
+
+        else :
+            # no graph output
+            out_file = None
+
+        return width, height, output, out_file
+
+    finally :
+        if tmp_fd :
+            # cleanup tempfile
+            # XXX: definately not portable to windows
+            os.unlink(out_path)
 
 def create (rrd_path, *args, **opts) :
     """