将Cherrypy中的数据传递给Javascript前端图表

Passing data in Cherrypy to a Javascript front-end chart

本文关键字:Javascript 前端 Cherrypy 数据      更新时间:2023-09-26

我是一名软件工程师,但我从来没有做过任何web开发。

这次,我负责制作一个仪表板来分析一些性能统计数据。

为了完成这个任务,我第一次尝试从头开始学习Django,但最终只浪费了几个星期。

我开始使用cherryypy构建一些小应用程序,下面是我到目前为止写的代码。它是Ajax代码和MySQL查询代码的大杂烩。

特别是功能submit222()与本项目关系不大。

在下面的代码中,成功连接和查询数据库。

res包含多行时间戳(x轴)和请求数(y轴)。

我想在res中传递这些数据,这样我就可以在网页中显示时间戳和请求数量的图表。

使用Google chart的图表(https://google-developers.appspot.com/chart/interactive/docs/gallery/annotationchart)

我现在没有一个工作视图文件,我找不到一个合适的例子来参考解决这个问题。

任何人都可以写一个简单的Javascript从这个python代码的res视图,并建立一个图表(或者,如果这是太多了,谁能解释如何传递res到Javascript)?

我真的想自己解决这个问题,没有任何人的帮助,我想我不可能解决这个问题。

谢谢。

MEDIA_DIR = os.path.join(os.path.abspath("."), u"media")
def connect(thread_index): 
    # Create a connection and store it in the current thread 
    cherrypy.thread_data.db = MySQLdb.connect(some db, some id, some password, 'storm')
# Tell CherryPy to call "connect" for each thread, when it starts up 
cherrypy.engine.subscribe('start_thread', connect)
class AjaxApp(object):
    @cherrypy.expose
    def index(self):
        # Sample page that displays the number of records in "table" 
        # Open a cursor, using the DB connection for the current thread 
        c = cherrypy.thread_data.db.cursor() 
        query = """select refresh_time,
                          num_requests
                     from model group by refresh_time"""
        c.execute(query) 
        res = c.fetchall()
        c.close()
        return open(os.path.join(MEDIA_DIR, u'index.html'))
    @cherrypy.expose
    def submit222(self, name):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(dict(title="Hello, %s" % name))
config = {'/media':
                {'tools.staticdir.on': True,
                 'tools.staticdir.dir': MEDIA_DIR,
                }
        }
def open_page():
    webbrowser.open("http://127.0.0.1:8080/")
cherrypy.engine.subscribe('start', open_page)
cherrypy.tree.mount(AjaxApp(), '/', config=config)
cherrypy.engine.start()

如果这不是你想要的,请告诉我。刚开始的web编程可能很难概念化客户端和服务器端将要发生的事情。坚持住!

import cherrypy
import os
import json
MEDIA_DIR = os.path.join(os.path.abspath("."), "media")

class AjaxApp(object):
    @cherrypy.expose
    def index(self):
        # Sample page that displays the number of records in "table" 
        # Open a cursor, using the DB connection for the current thread 
        return """
        <html>
        <head>
        <script lang="javascript">
        function GetData()
        {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            if(window.XMLHttpRequest)
                xmlhttp=new XMLHttpRequest();
            else// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.onreadystatechange=function()
            {
                if(xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    var someData_notJSON = JSON.parse(xmlhttp.responseText);
                    document.getElementById('Data').innerHTML = 'asdf: ' + someData_notJSON.asdf + ' and asdfw: ' + someData_notJSON.asdfw;
                }
            }
            xmlhttp.open("GET","/submit222", true);
            xmlhttp.send();
        }
        </script>
        </head>            
            <body onload="GetData();">
                <div id="Data">hi</div>
            </body>
        </html>
        """
    @cherrypy.expose
    def submit222(self):
        # get data from db
        res = { 'asdf': 1,
               'asdfw' : 3 }
        return json.dumps(res)

config = {'/media':
                {'tools.staticdir.on': True,
                 'tools.staticdir.dir': MEDIA_DIR,
                }
        }
cherrypy.tree.mount(AjaxApp(), '/', config=config)
cherrypy.engine.start()