xyzio

Posts Tagged ‘save as html

Generating Charts with Python and matplotlib as Base64 images for embedding in HTML webpages

leave a comment »

This is code used to create the charts for my ‘Compare Expense Ratios‘ microsite. It uses matplotlib to generate a chart which is converted to a Base64 to be embedded directly into a webpage. This way there is no need to save an intermediate image.

#Inputs are a dictionary of lists that contains points to plot (points), the title, and the x and y-axis labels.
def mathPlotLib(points, title, xlabel, ylabel):
   import matplotlib
   matplotlib.use('Agg')
   from matplotlib import pyplot
   import base64
   import cStringIO
   import natsort

   #The two funds are the keys to the dicitonary
   fundOrder = []
   for fund in natsort.natsorted(points.keys()):
      #Plot the points and keep track of the order they are added for the legend
      pyplot.plot(points[fund])
      fundOrder.append(fund)

   # Add the legend, title, and x,y labels.
   pyplot.legend(fundOrder)
   pyplot.title(title)
   pyplot.xlabel(xlabel)
   pyplot.ylabel(ylabel)

   # Convert the image as png as a byte-string object
   my_stringIObytes = cStringIO.StringIO()
   pyplot.savefig(my_stringIObytes, format='png')

   # Seek to the beginning of the file and encode it as Base64
   my_stringIObytes.seek(0)
   b64png = base64.b64encode(my_stringIObytes.read())

   # Add the html wrapper to embed it as base64
   html = '<img src="image/png;base64,' + b64png + '" />'

   # Clean up
   my_stringIObytes.close()
   pyplot.clf()
   pyplot.close()

   return html

 

Written by M Kapoor

December 24, 2019 at 8:04 pm

Posted in Programming, python

Tagged with , ,

Generate and save a static page in Django

leave a comment »

Generate and save a static page in Django.

Where
html/static.html is a Django template
data is the data you want to pass into the page
static(request) is a function mapped to a url in urls.py

Then
Visiting the page will generate this static file

Code

from django.template.loader import render_to_string

def static(request):
    results = render_to_string('html/static.html', {'content': html})
    with open(r'C:tempstatic.html','w') as f:
        f.write(results)

Written by M Kapoor

August 23, 2018 at 4:56 am