0

I'm trying to pass some data retrieved from a database with python to javascript.

The code below works. I can access the data in javascript but I can only pass one row at a time.

#!le/usr/bin/env python3
import sys
import re
import datetime
import sqlite3
import json
import time
SQLDB = '/home/daylene/db/PiLN.sqlite3'
db = sqlite3.connect(SQLDB) 
db.row_factory = sqlite3.Row
cursor = db.cursor()
sql = '''SELECT segment, dt, set_temp, temp, pid_output
               FROM firing WHERE run_id=? ORDER BY dt;
          '''
p = ((54),)
cursor.execute(sql, p)
columns = [column[0] for column in cursor.description]
results = []
for row in cursor.fetchall():
    results.append(dict(zip(columns,row)))
print(json.dumps(results[-1]))

And the working javascript

  <script>
        $(document).ready(function () {
            showGraph();
        });


        function showGraph()
        {
            $.ajax({
              mimeType: 'application/json; charset=iso-8859-1',
              url:  'data.cgi',
              //data: JSON.stringify( query ),
              contentType: "application/json",
              dataType: 'json',
              method: 'POST',
              async: false,
              success:  function (response)
                {
                    //document.write(response);
 
                    var time = response["dt"];
                    var temp = response["temp"];
                    //document.write(response);
                    //for (var i in response) {
                     //   time.push(response.time);
                      //  temp.push(response.temp);
                    //}

                    var chartdata = {
                        labels: time,
                        datasets: [
                            {
                                label: 'time',
                                backgroundColor: '#49e2ff',
                                borderColor: '#46d5f1',
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#666666',
                                data: temp
                            }
                        ]
                    };

                    var graphTarget = $("#graphCanvas");

                    var barGraph = new Chart(graphTarget, {
                        type: 'bar',
                        data: chartdata
                    });
                }
            
            
        });
    }
        </script>

uncommentating document.write(response); and changing to print(json.dumps(results)) does not work. Nothing is returned with document.write(response);

Adding this does not work

for row in results:
    results1.append(json.dumps(row))
print(results1)

and then adding this also does not work

results1 = []
for row in results:
    results1.append(json.dumps(row))
print(json.dump(results1)

The output of print(results) (shortened)

[{"segment": 4, "dt": "2020-07-09 19:58:55", "set_temp": 1145, "temp": 1145.02, "pid_output": 83.49}, {"segment": 4, "dt": "2020-07-09 19:59:24", "set_temp": 1145, "temp": 1145.15, "pid_output": 80.76}, {"segment": 4, "dt": "2020-07-09 19:59:54", "set_temp": 1145, "temp": 1145.16, "pid_output": 80.6}, {"segment": 4, "dt": "2020-07-09 20:00:24", "set_temp": 1145, "temp": 1145.15, "pid_output": 80.73}, {"segment": 4, "dt": "2020-07-09 20:00:55", "set_temp": 1145, "temp": 1145, "pid_output": 83.73}, {"segment": 4, "dt": "2020-07-09 20:01:24", "set_temp": 1145, "temp": 1145.08, "pid_output": 82.1}, {"segment": 4, "dt": "2020-07-09 20:01:54", "set_temp": 1145, "temp": 1145.13, "pid_output": 80.99}]

Any guidance is appreciated.

6
  • Your "output of print(results) (shortened)" looks like multiple rows. If you are confused because it all prints on one line in the console. try: import pprint ; pprint(results) Commented Aug 20, 2020 at 15:54
  • No I'm aware that it's more than one line. I'd like to send the entire thing to JavaScript and be able to access the data with response[x]["dt"] where x if a row number. Commented Aug 20, 2020 at 16:06
  • You should be able to. Why are you using response["dt"]; instead of response[x]["dt"] ? Commented Aug 20, 2020 at 16:14
  • That was an example of what was working. I can get the results of one line passed to javascript. When trying pass the entire "results" variable, document.write(response); generates nothing in javascript. So it's not getting passed correctly. I just have no idea how to fix it. Commented Aug 20, 2020 at 16:21
  • I don't see how you are returning the json response. You are only showing code that prints it in the console. Try: return json.dumps(results) Commented Aug 20, 2020 at 16:25

2 Answers 2

1

The easiest way to serve data to your JS frontend from Python is by making a server that serves HTTP requests.

Using simple flask for example:

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/my-data")
def get_data():

    my_data = [{"segment": 4, "dt": "2020-07-09 19:58:55"}, {}]

    return jsonify(my_data)

if __name__ == "__main__":
    app.run(port=8080, host="0.0.0.0")

And then you can request the data from http://localhost:8080/my-data in your Javascript.

Sign up to request clarification or add additional context in comments.

1 Comment

This is part of a much larger project that already uses jinja2 templates and google charts. I'm trying to move to chartjs for offline charts. The chart will be inside a template and needs to be updated dynamically.
0

Bleh, I figured it out. It wasn't the code but rather the size of the data I was trying to pass. Trying a smaller array worked fine.

I finally thought to check the lighttpd logs and I'm getting this.

(mod_cgi.c.588) response headers too large for /app/data.cgi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.