【问题标题】:How to stop the Django server from keep loading?如何阻止 Django 服务器继续加载?
【发布时间】:2017-05-17 18:50:25
【问题描述】:

我正在获取用户输入,用户输入保存在数据库中。从数据库中获取值以显示图形。我正在使用 matplotlib 包。当服务器第一次运行时,每次显示图表都没有问题,但是当我尝试再次显示图表时,页面会一直加载。每次我必须重新启动系统以停止加载页面。我尝试通过添加 close(),clf() 方法来解决问题,但问题仍然存在。

我正在使用 Python2.7、Django 1.10.4 和 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",{})

【问题讨论】:

    标签: python mysql django matplotlib


    【解决方案1】:

    你不能在生产环境中使用 matplotlib 的交互式版本——这会搞砸的。只需执行以下操作:

    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
    

    这只是图表部分。要在模板中实现此图表,只需在模板中添加如下所示的行。

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

    并确保它可以在网址中找到。

    【讨论】:

      【解决方案2】:

      您是否尝试过关闭连接和光标?即

      c.close()
      con.close()
      

      正如在这篇文章中看到的: Python MySQLdb: connection.close() VS. cursor.close()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-14
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多