Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data from Python to Javascript (JSON)

I know JSON to solve this problem, but I have problems in implementing it. Here is the detail of my approach:

  1. Data are calculated in Python
  2. Since the size of data is dynamic, so I need to use JavaScript to create extra HTML table rows for my outputs. As a result, I need to pass data from Python to JavaScript to let Javascript to 'see' the data.

HTML Code (below is a section of my HTML code to create the output page):

class OutputPage(webapp.RequestHandler):
    def func (a,b):
        return a+b #just an example

    def get(self):
        form = cgi.FieldStorage() 
        chem_name = form.getvalue('chemical_name')
        Para1 = form.getvalue('Para1')  #get values from input page--user inputs
        Para1 = float(Para1)
        Para2 = form.getvalue('Para2')  #get values from input page--user inputs
        Para2 = float(Para2)
        out = func (Para1,Para1)
        out_json=simplejson.dumps(out)  # I need to send out to JavaScript
        #writ output page
        templatepath = os.path.dirname(__file__) + '/../templates/'
        html = html + template.render (templatepath + 'outputpage_start.html', {})
        html = html + template.render (templatepath + 'outputpage_js.html', {})               
        html = html + """<table width="500" class='out', border="1">
                          <tr>  
                            <td>parameter 1</td>
                            <td>&nbsp</td>                            
                            <td>%s</td>
                          </tr>
                          <tr>  
                            <td>parameter 2</td>
                            <td>&nbsp</td>                            
                            <td>%s</td>
                          </tr>                                                      
                          </table><br>"""%(Para1, Para2)
        html = html + template.render(templatepath + 'outputpage_end.html', {})
        #attempt to 'send' Python data (out_json) to JavaScript, but I failed.
        html = html + template.render({"my_data": out_json})  
        self.response.out.write(html)

app = webapp.WSGIApplication([('/.*', OutputPage)], debug=True)

JavaScript Code (I use JavaScript to create additional inputs tables on the fly filename:'outputpage_js.html'):

<script>
<script type='text/javascript'> 

$(document).ready(function(){
    //I assume if my Json statement works, I should be able to use the following argument to create a HTML row
    $('<tr><td>Parameter 2</td><td>&nbsp</td><td>out_json</td>').appendTo('.app')   

</script>    

Thanks for the help!

like image 235
TTT Avatar asked Aug 14 '12 20:08

TTT


1 Answers

you don't have to "implement" JSON, python comes with a built in lib, called simplejson, which you can feed with normal dicts:

try: 
  import simplejson as json
except:
  import json
out = {'key': 'value', 'key2': 4}
print json.dumps(out)

EDIT: as tadeck pointed out, simplejson should be more up-to-date and is not equal to json, but there is a chance, simplejson is not available due to it is maintained externaly

EDIT 2: based on the discussion in this answer and the discussion on the page, i think, the best approach would be something like that:

python

# [...] generate dynamic data [...]
html = html + template.render (templatepath + 'outputpage_start.html', {})
html = html + template.render (templatepath + 'outputpage_js.html', {})               
html = html + """<table width="500" class='out' border="1" data-dynamic="%s">""" % json.dumps(your_generated_data_dict)
#tr/td elements and templating as needet
self.response.out.write(html)

javascript

$(function(){
    var your_generated_table = $('table'),
        dynamic_data = JSON.parse(your_generated_table.attr('data-dynamic'));
});

you then have the exact same structure your python dict has as a javascript object.

like image 150
DesertEagle Avatar answered Oct 14 '22 14:10

DesertEagle