1

I am getting user input,the user input is saved in the database. From database the values are fetched to display the graph. I am using matplotlib package. Every time the graph is displayed with no problem when the server is run for the first time , but when I try to display the graph again the page keeps on loading forever. Everytime I have to restart the system to stop the page from loading. I tried to solve the problem by adding close(),clf() methods, but the problem persisted.

I'm using Python2.7,Django 1.10.4 and mysql

**Views.py**

def show(request):
try:
    x = []
    y = []
    con = MySQLdb.connect("localhost", "root", "", "mydb")
    c = con.cursor()
    c.execute("select * from dummy")
    row = c.fetchone()
    while row != None:
        x.append(row[0])
        y.append(row[1])
        row = c.fetchone()
    plt.plot(x, y)
    plt.title("THE GRAPH")
    a = max(y)
    a1 = min(y)
    a2 = numpy.mean(y)
    plt.xlabel("X-AXIS",color='red')
    plt.ylabel("Y -AXIS",color='red')
    plt.text(-2,1,"Max Y-Value:"+str(a),verticalalignment="top",horizontalalignment="right")
    plt.text(-2,2,"Min Y-Value:"+str(a1), verticalalignment="top", horizontalalignment="left")
    plt.text(-2,3,"Avg Y-Value:"+ str(a2), verticalalignment="top", horizontalalignment="center")
    plt.show()
    return render(request,"back.html",{})
user7369931
  • 193
  • 1
  • 11

2 Answers2

1

Have you tried closing the Connection and curser? i.e

c.close()
con.close()

As seen in this post: Python MySQLdb: connection.close() VS. cursor.close()

Community
  • 1
  • 1
Paul Machin
  • 39
  • 1
  • 9
1

You cannot use the interactive version of matplotlib - this will screw up - for sure on a production environment. Just do the following:

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

def graphic(request):
        #other stuff goes here
        fig=Figure()
        fig1=fig.add_subplot(1,1,1)
        fig1.plot(x,y)
        canvas=FigureCanvas(fig)
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)
        return response

This is just the chart part. To implement this chart in a template just put a line like the following into your tempolate.

<img src='{% url "graphic" %}'>

And make sure that it can be found in the urls.

ger.s.brett
  • 3,267
  • 2
  • 24
  • 30