Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect Javascript to Python sharing data with JSON format in both ways?

I'm trying to find out how to create a local connection between a Python server and a Javascript client using the JSON format for the data to be retrieved. Particularly, I need to make some queries on the HTML client side, send these queries to the server on JSON format and run them on the Python server side to search for data on a SQLite Database. And after getting the results from the database, send those results back to the client in JSON format too.

By now, I just can run the query on Python and code it on JSON like this:

import sqlite3 as dbapi
import json

connection = dbapi.connect("C:/folder/database.db")
mycursor = connection.cursor()
mycursor.execute("select * from people")
results = []
for information in mycursor.fetchall():
        results += information

onFormat = json.dumps(results)
print(onFormat)

I know this code does something alike (in fact it runs), because it calls a service on a server which returns data in JSON format (but the server in this example is NOT Python):

<html>
    <head>
        <style>img{ height: 100px; float: left; }</style>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div id="images"></div>
    <script>
      $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
      {
        tags: "mount rainier",
        tagmode: "any",
        format: "json"
      },
      function(data) {
        $.each(data.items, function(i,item){
          $("<img/>").attr("src", item.media.m).appendTo("#images");
          if ( i == 3 ) return false;
        });
      });</script>

    </body>
</html>

What I need is to know how should I run (locally) the python program to be an available running web-service and how should be the Javascript to retrieve the data from the python server.

I've looking for this on internet everywhere but I didn't find this answer anywhere because the only answers they give are on how to code JSON inside Python or inside Javascript but not connecting both. Hope somebody can help me on this!!!

like image 392
AngelBlond8 Avatar asked Jul 31 '12 19:07

AngelBlond8


People also ask

Can Javascript and Python work together?

Answer: No, Python cannot replace Javascript. In fact, the two languages complement each other. Javascript is used as a client-side scripting language, whereas Python is mostly used as a server-side scripting language.

How pass data from Javascript to Python?

To pass variables from Python Flask to JavaScript, we can call render_template with the data argument with the dictionary of data we want to pass to the template. to call render_template with the template file name and the data set to the data dict with the data we want to pass to the template.


1 Answers

Here's a "hello world" example of a flask web-application that can serve static html and javascript files, search database using parameter from a javascript request, and return results to javascript as json:

import sqlite3
from flask import Flask, jsonify, g, redirect, request, url_for

app = Flask(__name__)

@app.before_request
def before_request():
    g.db = sqlite3.connect('database.db')

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

@app.route('/')
def index():
    return redirect(url_for('static', filename='page.html'))

@app.route('/json-data/')
def json_data():
    # get number of items from the javascript request
    nitems = request.args.get('nitems', 2)
    # query database
    cursor = g.db.execute('select * from items limit ?', (nitems,))
    # return json
    return jsonify(dict(('item%d' % i, item)
                        for i, item in enumerate(cursor.fetchall(), start=1)))

if __name__ == '__main__':
    app.run(debug=True, host='localhost', port=5001) # http://localhost:5001/
else:
    application = app # for a WSGI server e.g.,
    # twistd -n web --wsgi=hello_world.application --port tcp:5001:interface=localhost

The database setup code is from Using SQLite 3 with Flask.

static/page.html and static/json-jquery.js files are from Ajax/jQuery.getJSON Simple Example, where the javascript code is modified slightly to pass a different url and nitems parameter:

$(document).ready(function(){
    $('#getdata-button').live('click', function(){
        $.getJSON('/json-data', {'nitems': 3}, function(data) {
            $('#showdata').html("<p>item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"</p>");
        });
    });
});
like image 54
jfs Avatar answered Oct 20 '22 00:10

jfs