Search code examples
javascriptpythonbottleweb-frameworksmako

How to reference returned data in javascript from a web framework like bottle?


I want to query my database, and return the results to javascript.

javascript files that I'm serving using bottle

    @app.route('/static/<filename:path>', name='static')
    def send_static(filename):
        return static_file(filename, root='static')

and I'm not sure if I'm doing this correctly, but I added another route to specify which js file should get it.

    @app.route('/static/js/app.js')
    def ello():
        cur.execute("SELECT * FROM places")
        places= cur.fetchall()
        return {'places':places}

and then in that app.js file, I want to be able to do something like:

    console.log(places);

But I'm not really sure how to escape it. I'm using mako for the html templating which works fine but everything I've tried for javascript results in

    Uncaught SyntaxError: Unexpected token {

as suggested here: https://stackoverflow.com/a/14157401/1543640


Solution

  • As it looks to me, you are trying to create a JavaScript file through Python. That sounds like a very awkward and inconvenient way to go about exchanging data between two worlds.

    A common practice to communicate between the front-end (JavaScript) and the back-end (a Python app in your case) is through JSON (which, in turn, is JavaScript). On a very basic level, you let your Python app construct valid JSON and make it available on a specific route for your JavaScript to consume.

    An example would be:

    @app.route('/some/route/to/consume')
    def fetch():
        """
        Fetch all the fancy stuff from the database.
        """
        db = Database()
        # Fetch all records, convert them into JSON
        result = json.dumps(db.get_stuff())
        return result
    

    This function will fetch all records from the database (with a fictional function db.get_stuff()) and, convert the result to valid JSON and return it. The important bit is the json_dumps() function from the Python json module. It will convert valid Python data structures into valid JSON data structures.

    Next you should write your actual JavaScript file to consume that JSON and let it do whatever you want it to do. This can be done via an XHR call (AJAX), for example.

    If the data that will be exposed on your route is not public, do take common security practices in mind and protect the route from unwanted eyes.