[Flask] Flask issues with JSon queries and environment variable "flask-app" problem..

mhysnm1964 at gmail.com mhysnm1964 at gmail.com
Sat Sep 14 21:40:53 EDT 2019

Hello all,


I am sure this is something simple and I am overlooking the cause of the
problem. I am new to JavaScript programming and accessing data using JSon
via Python.  I am not a professional developer and doing this for interest
sake and learning more about programming.


I am creating a personal budget program for my own use using Python flask
and JavaScript. The JavaScript is going to handle get and post requests. The
get request is to retrieve SQL Queries in a dict or array format. Contained
in the dict will be dates, strings, integers and floats only. The date is
formatted in yyyy-mm-dd format. The test script I am using does not contain
dates at this stage. Once I work out the cause of my issue,. then I will be
modifying other functions which the query results will include dates in the
Json sserialised string. 


The prime issue is why my JavaScript code is not retrieving the data from my
flask app. The 2nd issue is why I am getting a encoding file type error. The
other parts of my flask app which does not involve JavaScript work fine. 


Examples I have seen have the script in the HTML code and they are using
ginger and flask functions to provide the URL to the JavaScript. I have done
this as well with the same errors seen in the chrome debug output. I have
used an absolute and relative paths with the same failure. This has been
done in the JavaScript file or within the HTML code. Below is the error


error messages from Firefox console:

WarningThe script from "http://localhost:5000/static/test_json.js" was
loaded even though its MIME type ("text/plain") is not a valid JavaScript
MIME type.

localhost:5000 ErrorSyntaxError: missing { before function body

WarningThe script from "http://localhost:5000/static/Accordion.js" was
loaded even though its MIME type ("text/plain") is not a valid JavaScript
MIME type.



Chrome development console: 

test_json.js:31 Uncaught SyntaxError: Unexpected token )

:5000/favicon.ico:1 Failed to load resource: the server responded with a
status of 404 (NOT FOUND)


               1. I cannot find any syntax code in the test_json.js file.

2. Do not understand why Firefox is complaining about the file type when
Chrome does not. I am getting this for both .js files.

3. The Chrome error is telling me it cannot find the data request source. If
I put the absolute path of "http://localhost/transactions_summary_report"
into Firefox. The data comes up as a tree which you can navigate. In the
Javascript I have used the same absolute path where
"/transactions_summary_report" is currently with no difference with error
messages. If I put the absolute path into the browser address bar, the Json
data is loaded.


I do not know if this is an JavaScript error or python. I have even used
known working JavaScript examples with the same result. Below is the current
version of the code.


JavaScript code for test_json:

/* standard Ajax xhr function */

function getHTTPObject() {

    var xhr;

    if (window.XMLHttpRequest) { // check for support

        // if it's supported, use it because it's better

        xhr = new XMLHttpRequest();

    } else if (window.ActiveXObject) { // check for the IE 6 Ajax

        // save it to the xhr variable

        xhr = new ActiveXObject("Msxml2.XMLHTTP");

    } // end if 

    return xhr;


function ajaxCall(dataUrl, callback) {

    /* use our function to get the correct Ajax object based on support */

    var request = getHTTPObject();

    request.onreadystatechange = function () {

        if (this.readyState == 4 && this.status === 200) {

            // save the ajax response to a variable

            var tableData  = JSON.parse(request.responseText);

            // make sure the callback is indeed a function before executing

            if (typeof callback === "function") {


            } // end check for function 

        } // end ajax check

    } // end state check function 

    request.open("GET", dataURl, true);


} // end function for loading ajax data 

ajaxCall ("/transactions_summary_report", function(data)) {




The python flask view code:


import re, csv, glob, os

from datetime import datetime

from flask import render_template, flash, redirect, url_for, request,
jsonify, json, Response 

from app import app, db

from app.forms import * 

from app.models import * 

from sqlalchemy import extract


@app.route('/', methods=['GET'])

@app.route('/index', methods=['GET'])

def index():

    tables = Accounts.query.all()

    return render_template('index.html', title='Budget Program Main Page',
tables = tables) 



def transactions_summary_report():

    report = [] # array of dicts.

    # loop through all the categories.

    for row in

        # create the dict to store the total of each sub-category and grand

        record = {'Category':'', 'Totals':[], 'grand_total':0}

        record['Category'] = row.categories.category # assigning the current

        # now loop through all the sub-categories and total the values.
Place them into the key total array.

        for subcat in SubCategories.query.filter(SubCategories.category_id
== row.category_id).all():

            res =
gory_id == subcat.id).all()

            if res[-1].total is not None:

            # assign the sub-category total to dict.

                record ['Totals'] += res

            # end if

        # calculate the grand total and add to dict.

        res =
ry_id == row.category_id).all()

        if res[-1].grand_total  is not None:

            record['grand_total'] = res[-1].grand_total

            report.append(record) # assign record dict to the array

    # return response code plus serialise the dict. Dict does not contain

    return jsonify(report)

    #return Response(json.dumps(report), mimetype='application/json')


Note: I have used the last line in the above code as well with the same
errors. Now for the HTMl index code:


{% extends "base.html" %}


{% block content %}

    <h1> Total costs Per Category and Sub-Category  </h1>

    <div class="data">

    <table id='reports_table'>

        <caption> Transactions Summary</caption>


            <th scope='col'>Category</th>

            <th scope='col'>sub_Category</th>

            <th scope='col'>Totals</th>





        <script type="text/javascript" src="static/test_json.js"></script>

{% endblock %}





Sean Murphy


 <mailto:seanmmur at cisco.com> seanmmur at cisco.com

Tel: +61 2 8446 7751






Cisco Systems, Inc.

The Forum 201 Pacific Highway






	Think before you print.

This email may contain confidential and privileged material for the sole use
of the intended recipient. Any review, use, distribution or disclosure by
others is strictly prohibited. If you are not the intended recipient (or
authorized to receive for the recipient), please contact the sender by reply
email and delete all copies of this message.

ent/company-registration-information.html> click here for Company
Registration Information.





-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/flask/attachments/20190915/69ccae4b/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: image001.png
Type: image/png
Size: 21354 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/flask/attachments/20190915/69ccae4b/attachment-0001.png>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: image002.gif
Type: image/gif
Size: 134 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/flask/attachments/20190915/69ccae4b/attachment-0001.gif>

More information about the Flask mailing list