在Cherrypy中将数据传递给JavaScript前端图表

0 投票
1 回答
2105 浏览
提问于 2025-04-18 00:15

我是一名软件工程师,但我之前从来没有做过网页开发。

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

一开始我尝试从零开始学习Django来完成这个任务,但结果浪费了好几周的时间。

后来我开始用cherrypy构建一个小应用,接下来是我到目前为止写的代码。这些代码混合了一些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()

1 个回答

2

如果这不是你想要的,请告诉我。刚开始学习网页编程的时候,理解客户端和服务器端发生的事情可能会很困难。坚持下去!

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()

希望这对你有帮助。

撰写回答