Skip to content

Instantly share code, notes, and snippets.

@alexwoolford
Last active August 29, 2015 14:24
Show Gist options
  • Save alexwoolford/ac342289bb90c5dda524 to your computer and use it in GitHub Desktop.
Save alexwoolford/ac342289bb90c5dda524 to your computer and use it in GitHub Desktop.

Get the data and render the report to HTML:

import MySQLdb
from jinja2 import Environment, PackageLoader

# get the data
conn = MySQLdb.connect(host='localhost', user='biggusd', passwd='Inc0ntinentia', db="test")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
sql = "select * from daily_report"
cursor.execute(sql)
rows = list(cursor.fetchall())

# render the template
env = Environment(loader=PackageLoader('report_generator', 'templates'))
template = env.get_template('report.html')

with open("/path/to/daily_report.html", 'w') as f:
    f.write(template.render(rows=rows))

The report template:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Daily Report</title>
        <head>
          <title>Bootstrap Example</title>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
          <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        </head>
    </head>
    <body>

        <div class="container">
           <table class="table table-striped">

               <tr>
                   <td>Source</td>
                   <td>Date</td>
                   <td>Ad Attempts</td>
                   <td>Ad Impressions</td>
                   <td>Win Rate</td>
                   <td>Revenue</td>
                   <td>MTD</td>
                   <td>YTD</td>
                   <td>CPM</td>
               </tr>

               {% for row in rows %}
               <tr>
                   <td>{{ row.source }}</td>
                   <td>{{ row.date }}</td>
                   <td>{{ row.ad_attempts }}</td>
                   <td>{{ row.ad_impressions }}</td>
                   <td>{{ row.win_rate }}</td>
                   <td>{{ row.revenue }}</td>
                   <td>{{ row.mtd }}</td>
                   <td>{{ row.ytd }}</td>
                   <td>{{ row.cpm }}</td>
               </tr>
               {% endfor %}
           </table>

        </div>

    </body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment