Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*
- from time import gmtime, strftime
- import webbrowser
- class ReportMaker:
- """This class creates tables and Google charts from data passed as a python dictionary. Formats vary by report/chart type"""
- def createPieChart(self,data_dict):
- """\nCreates a Google Charts Pie Chart with a properly formatted dictionary (see below):
- {
- "Creating a nice Chart":
- [
- ["Name","Visits"],
- ["Joe",50],
- ["Bob",28],
- ["Steve", 82]
- ],
- "Creating another nice Chart":
- [
- ["Tool","Inventory"],
- ["Hammer",15],
- ["Screwdriver",7],
- ["Saw", 5]
- ]}
- """
- dtg = strftime("%d_%b_%Y_%H%M", gmtime())
- myfile = open(dtg+".html","w")
- myhtml="""<!DOCTYPE html><head>
- <!-- Latest compiled and minified CSS -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
- <!-- Latest compiled and minified JavaScript -->
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>"""
- myhtml1 ="""<script type="text/javascript">
- google.charts.load('current', {'packages':['corechart']});
- google.charts.setOnLoadCallback(drawChart);
- function drawChart() {
- var data = google.visualization.arrayToDataTable("""
- myhtml2 = """);
- var options = {{
- title: '{0}',
- is3D: true,
- }};
- var chart = new google.visualization.PieChart(document.getElementById('{0}'));
- chart.draw(data, options);
- }}
- </script>\n\n
- <!- END OF SCRIPT->\n\n"""
- myhtml2_5 = """</head>
- <body><div>""" #start the main div
- myhtml3="""<div id="{0}" style="min-height:600px; width:50%; margin:0px; padding:0px; float: {1};"></div>\n\n
- <!- END OF DIV->\n\n""" #start each sub div for individual charts
- myfile.write(myhtml)
- for chart in data_dict.keys():
- myfile.write(myhtml1 + str(data_dict[chart]).replace('[[[','[[').replace(']]]',']]') + myhtml2.format(chart))
- myfile.write(myhtml2_5)
- mycounter = 2
- for chart in data_dict.keys():
- if mycounter % 2 == 0:
- myfile.write(myhtml3.format(chart,"left"))
- mycounter+=1
- else:
- myfile.write(myhtml3.format(chart,"right"))
- myfile.write("<br />")
- mycounter+=1
- myfile.write('</div></body></html>')
- print "[!] {0}.html was created".format(dtg)
- webbrowser.open("{0}.html".format(dtg))
- def createTable(self, table_dict):
- """Creates a number of tables from a properly formatted dictionary containing table values"""
- dtg = strftime("%d_%b_%Y_%H%M", gmtime())
- myfile = open(dtg+".html","w")
- myhtml_header="""<!DOCTYPE html><head>
- <style>
- h1 {
- display: block;
- font-size: 2em;
- margin-top: 0.67em;
- margin-bottom: 0.67em;
- margin-left: 0;
- margin-right: 0;
- font-weight: bold;
- }
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 100%;
- }
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
- tr:nth-child(even) {
- background-color: #dddddd;
- }
- </style>
- <!-- Latest compiled and minified CSS -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
- <!-- Latest compiled and minified JavaScript -->
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
- </head><body>
- """
- myfile.write(myhtml_header)
- for tb in table_dict.keys():
- myfile.write("<h1>{0}</h1><table><tr>".format(tb))
- for column_header in table_dict[tb][0]:
- myfile.write("<th>{0}</th>".format(column_header))
- myfile.write("</tr>")
- for row in table_dict[tb][1]:
- myfile.write("<tr>")
- for rowdata in row:
- try:
- myfile.write("<td>{0}</td>".format(str(rowdata)))
- except UnicodeEncodeError:
- myfile.write("<td>{0}</td>".format("[!] Unicode Error"))
- myfile.write("</tr>")
- myfile.write("</table><br />")
- myfile.write("</body></html>")
- myfile.close()
- print "[!] {0}.html was created".format(dtg)
- webbrowser.open("{0}.html".format(dtg))
- def createTimeChart(self, data_dict):
- """\nCreates a Google Charts Line Chart with a properly formatted dictionary (see below):
- {
- "Creating another nice Time Chart":
- [
- [("Day of the Week","string"),("Customers","number"),("Deliveries","number")],
- ["Monday",25,6],
- ["Tuesday",38,12],
- ["Wednesday",12,8],
- ["Thursday",2,14],
- ["Friday",5,25]
- ],
- "Creating a nice Time Chart":
- [
- [("Day of the Week","string"),("Customers","number"),("Deliveries","number")],
- ["Monday",66,9],
- ["Tuesday",24,12],
- ["Wednesday",16,8],
- ["Thursday",2,18],
- ["Friday",46,21]
- ]
- }
- """
- #this data in organized wrong. fix the nested lists to remove one level like the second example above
- dtg = strftime("%d_%b_%Y_%H%M", gmtime())
- myfile = open(dtg+".html","w")
- myhtml = """<!DOCTYPE html><head>
- <!-- Latest compiled and minified CSS -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
- <!-- Latest compiled and minified JavaScript -->
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
- <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>"""
- myhtml1 = """<script type="text/javascript">
- google.charts.load('current', {
- packages: ['corechart', 'line']
- });
- google.charts.setOnLoadCallback(drawBackgroundColor);
- function drawBackgroundColor() {
- var data = new google.visualization.DataTable();"""
- myhtml1_1 = """var options = {{
- hAxis: {{
- title: 'Time',
- direction: -1,
- slantedText: true,
- slantedTextAngle: 75 // here you can even use 180,
- }},
- vAxis: {{
- title: 'Units',
- scaleType: 'log'
- }},
- backgroundColor: '#FFFFFF',
- height: 700,
- interpolateNulls: true
- }};
- var chart = new google.visualization.LineChart(document.getElementById('{0}'));
- chart.draw(data, options);
- }}
- </script>\n"""
- # start writing the html file
- myfile.write(myhtml)
- # iterate over the dictionary for each chart we will create
- for chartName in data_dict.keys():
- myfile.write(myhtml1) # create a JavaScript function for each chart
- for value in range(len(data_dict[chartName][0])): # create the columns one per a line this includes y and x * n values (n=number of lines you want to see)
- myfile.write("\n\tdata.addColumn('{0}', '{1}');".format(data_dict[chartName][0][value][1],data_dict[chartName][0][value][0]))
- # add the data list, the way python "prints" it works perfect for this JS library
- myfile.write("\ndata.addRows({0});".format(str(data_dict[chartName][1:]).replace("[[[","[[").replace("]]]","]]")))
- myfile.write(myhtml1_1.format(chartName))
- myfile.write('</head><body>')# start the body element
- # create the div elements that display the charts with header
- for chartName in data_dict.keys():
- myfile.write("\n<div><h2>{0}</h2>\n<!--chart div element here-->\n".format(chartName))
- myfile.write("<div id='{0}'></div>\n<!--end chart div element here-->\n</div>".format(chartName))
- myfile.write("</body></html>")
- myfile.close()
- print "[!] {0}.html was created".format(dtg)
- webbrowser.open("{0}.html".format(dtg))
- if __name__ == '__main__':
- main()
Add Comment
Please, Sign In to add comment