Webprogramming

Making charts and output them as images to the browser in Django

6
Simple graph made with matplotlib

Simple graph made with matplotlib

Lets say you are working on a website made in Django. And you want to make some nice looking graphs real time, as images from dynamic data. This can be done by using the python 2D graph library matplotlib. The library can be found in the debian package python-matplotlib. A simple graph showing a sine curve, seen to the right, can be generated in regular python using the following code(taken from this example):

from pylab import *
 
t = arange(0.0, 2.0, 0.01)
s = sin(2*pi*t)
plot(t, s, linewidth=1.0)
 
xlabel('time (s)')
ylabel('voltage (mV)')
title('About as simple as it gets, folks')
grid(True)
show()

Output graph to browser from a Django view

If you want to output this graph as a PNG image to the browser from a view in Django, you can store the image in a string buffer and output this buffer using the HttpReponse class in Django and set the mime type to image/png.

from django.http import HttpResponse
from matplotlib import pylab
from pylab import *
import PIL, PIL.Image, StringIO
 
def showimage(request):
    # Construct the graph
    t = arange(0.0, 2.0, 0.01)
    s = sin(2*pi*t)
    plot(t, s, linewidth=1.0)
 
    xlabel('time (s)')
    ylabel('voltage (mV)')
    title('About as simple as it gets, folks')
    grid(True)
 
    # Store image in a string buffer
    buffer = StringIO.StringIO()
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
    pilImage.save(buffer, "PNG")
    pylab.cose()
 
    # Send buffer in a http response the the browser with the mime type image/png set
    return HttpResponse(buffer.getvalue(), mimetype="image/png")

How to restrict user access to content in folders using PHP and Apache .htaccess files

4

So I was faced with this problem: I needed to restrict access to content(images, files, documents..) in folders, and normally this is done by using a .htacces and .htpasswd file, but I needed more functionallity than this method provided. This extra functionality could be that you simply have a list of users in a database and want to authenticate and authorize users against this database using PHP. In this entry I explain a method I developed to do exactly this.

(more…)

Go to Top