Frage

I am a software engineer, but I've never done any web development.

This time, I am in charge of making a dashboard to analyze some performance stats.

I first tried to learn Django from scratch for this task, but only ended up wasting weeks.

I started building some small app using cherrypy, and what follows is the code that I have written so far. It's a hodgepodge of some codes for Ajax and some codes for MySQL queries.

Especially, function submit222() is not very relevant to this project.

In the following code, connection and query to the database are successfully made.

res contains multiple rows with timestamp(x-axis) and the number of requests(y-axis).

I want to pass these data in res, so that I could show a chart of the timestamp and the number of requests in the webpage.

A chart using Google Chart(https://google-developers.appspot.com/chart/interactive/docs/gallery/annotationchart)

I do not have a working view file at this time, and I could not find a proper example to refer to for solving this problem.

Can anyone write a simple Javascript for the view that takes res from this python code and builds a chart(or if that's too much can anyone explain how to pass res to Javascript)?

I really tried to figure this out by myself, and without anyone's help, I do not think I could figure this out.

Thank you.

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()
War es hilfreich?

Lösung

Let me know if this is not what you're going for. Beginning web programming can be hard to conceptualize what's going to happen on the client and server side. hang in there!

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

Hope this helps.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top