Pinterest Stumbleupon Whatsapp
Advertisement

Ever wondered how to send data between two programming languages? Ever tried to send an object or multiple pieces of data?

Today I’ll be showing you how to use JSON to send data from JavaScript to Python. I’ll be covering how to setup a web server, along with all the code you need.

Prerequisites

You will need a few things to get started with this project. I’ll be running on Mac, which has Python installed already. You should be able to follow along reasonably well using Linux. If you are using Windows, you will need to download and install Python, and maybe brush up on your command line skills A Beginners Guide To The Windows Command Line A Beginners Guide To The Windows Command Line Read More .

You will need pip, a package manager for Python. This is installed by default with Python versions greater than 2.7.9.

Server Setup

You need a server to serve Python to a web page. There are many options for this. If you have a server setup already, you can skip this step.

There are many options you could use here. Tornado is a good choice, as is Twisted (I have written about Twisted before for a DIY network camera). I’ll be using Flask for this project.

Advertisement

Install Flask using pip (via the command line):

pip install Flask

That’s it! There are a few options to setup, but providing it installed correctly, you are good to go.

You may wish to consider using a Python Virtual Environment Learn How to Use the Python Virtual Environment Learn How to Use the Python Virtual Environment Whether you are an experienced Python developer, or you are just getting started, learning how to setup a virtual environment is essential for any Python project. Read More , however this is entirely optional.

Python Setup

Create a new file in your favorite text editor or Integrated Development Environment (IDE). I’m using Sublime Text 3 and PyCharm, but use whatever you are comfortable with.

Now perform some initial setup of Flask:

from flask import Flask
app = Flask(__name__)

This imports the required modules and configures your app. Now set up a path:

@app.route("/output")
def output():
	return "Hello World!"

This configures a path, which is like a page of a website. This may sometimes be called an endpoint or a route.

The def output() line defines a function or method called output, which will run whenever this endpoint is called. These methods do not have to use the same name as the endpoint — call it any suitable name. Inside this method is a simple Hello, World! string. Finally, setup your script to actually run when it is requested:

if __name__ == "__main__":
	app.run()

Go ahead and save this script as json_io.py in a suitable location. Go back to your Terminal and navigate to your project folder. Run the script:

python json_io.py

The word python is used to tell the computer that the following file should be run as a Python script. The filename afterwards is the name of the file you wish to run as Python. If everything works correctly, you should see a status message in the Terminal:

* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

This shows you the IP address your server is running on, as well as the port. These will be 127.0.0.1 and 5000. You can press CTRL > C to stop this running, but don’t do that just yet.

Enter the address into your browser, and you should see Hello, World! appear on the screen. You have now successfully setup a Python server and written your first script! You will need to restart the server (stop the script, then run it again) if you make any changes.

If you wish to view your scripts on a different computer on the same network, change app.run() to:

app.run("0.0.0.0", "5010")

There are two parts to this line. The first tells Flask to serve files on your local IP address (make sure you keep this as 0.0.0.0, even though that is not your IP address). The second part specifies the port. You can change the port if you wish to. Run the script again (remember to save and restart).

You should now be able to access your scripts from a different computer on the same network. Make sure to use your IP address (run ifconfig in the command line) and the port you entered previously. You may need to configure your firewall if you are using one.

The console will show you the HTTP response, and IP address of any device that connects to your server:

Python Server Access Details

Notice how the endpoint /df returned a 404 error? The endpoint is not setup! If you wish to access this over the internet, look into port forwarding What Is Port Forwarding & How Can It Help Me? [MakeUseOf Explains] What Is Port Forwarding & How Can It Help Me? [MakeUseOf Explains] Do you cry a little inside when someone tells you there’s a port forwarding problem and that’s why your shiny new app won’t work? Your Xbox won’t let you play games, your torrent downloads refuse... Read More .

Templates

Now that your server is all setup, it’s time to write some templates. You will use JSON to send data between Python and Javascript, and templates facilitate this. We have written about what JSON is What Is JSON? A Layman's Overview What Is JSON? A Layman's Overview Whether you plan to be a web developer or not, it's a good idea to at least know what is JSON, why it's important, and why it's used all around the web. Read More in the past, so go read up if you are not sure.

You will need to use a templating language. Jinja2 comes with Flask, so there is no extra setup needed.

A templating language works in conjunction with a web server. It takes the output of your Python scripts (the back-end code), and makes it easy to output to the user using HTML (the front-end). It’s important to note that templates should not be used for logic! Keep the logic in Python, and use templates only for displaying the data. It gets very messy if you start trying to get complex with the template.

Create a folder inside your project directory called templates. Flask recognizes files inside this folder as template files. Don’t place any Python scripts in here, this is where you can put your HTML files.

Create a file called index.html. Inside it, place the following code:

{{ name }}

This is the way to access a piece of data called name, which will be found inside your scripts. Go back to your json_io.py. script, and modify the output function. Instead of returning hello world, enter this code:

return render_template("index.html", name="Joe")

This will load the index.html file you created earlier, and substitute the {{ name }} template tag for the string Joe. You can use this method to load any page inside your template folder, and pass them any amount of data.

The Code

Now that you know how templates work, here’s the full HTML code you need. Paste this inside your index.html file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
// setup some JSON to use
var cars = [
	{ "make":"Porsche", "model":"911S" },
	{ "make":"Mercedes-Benz", "model":"220SE" },
	{ "make":"Jaguar","model": "Mark VII" }
];

window.onload = function() {
	// setup the button click
	document.getElementById("theButton").onclick = function() {
		doWork()
	};
}

function doWork() {
	// ajax the JSON to the server
	$.post("receiver", cars, function(){

	});
	// stop link reloading the page
 event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<a href="" id="theButton">Click Me</a>

Notice how this does not include CSS, or any HTML headers. These are required for webpages (this example will work without them), so look into these at W3Schools if you care to.

Python JSON HTML Button

There is not too much going on in this file. A JSON list of rally cars is setup. There is a bit of text and a button. When the button is pressed, jQuery is used to POST the list of cars to the server. This will go to the receiver endpoint, which you will create next. Make sure you read our guide to jQuery if you want to learn more about how that is working in this context.

Here’s the code you need for json_io.py:

#!flask/bin/python

import sys

from flask import Flask, render_template, request, redirect, Response
import random, json

app = Flask(__name__)

@app.route('/')
def output():
	# serve index template
	return render_template('index.html', name='Joe')

@app.route('/receiver', methods = ['POST'])
def worker():
	# read json + reply
	data = request.get_json()
	result = ''

	for item in data:
		# loop over every row
		result += str(item['make']) + '\n'

	return result

if __name__ == '__main__':
	# run!
	app.run()

This code defines two endpoints. The default one (/) serves the previous html page. When the button is pressed, a POST request is made to the /receiver endpoint. The second part of the route definition (methods = [‘POST’]) defines how this page can be accessed. As POST is the only way specified, this route will deny any other http requests (such as GET).

This /receiver endpoint simply loops over every JSON row, and appends the car make to a string, which then gets returned after the loop. The JSON is stored in the data variable, and as the request.get_json() was used, Python is aware that this is a JSON object. The item variable inside the for loop can be thought of like a row of data. Different elements of each row can be accessed by using their name in square brackets (item[‘make’]).

Open your browser developer tools (CMD > ALT > I on Mac OS/Chrome), and navigate to the network tab. Press the button, and you should see the server response appear:

Python JSON Response

Try modifying the initial JSON and see what happens. Let’s modify the Python to do something different, depending on the JSON. Here’s the new code you need for the for loop:

	for item in data:
		# loop over every row
		make = str(item['make'])
		if(make == 'Porsche'):
			result += make + ' -- That is a good manufacturer\n'
		else:
			result += make + ' -- That is only an average manufacturer\n'

This uses a simple if statement to change the output, depending on the input. You could easily adapt this to write to a database, or run a different piece of code. Here’s what it looks like now:

Python JSON Conditional

You should now have a solid understanding of how to setup a Python server, and how you can respond to JSON requests.

Do you use Flask with Python? Is there a different tool you use? What programming paradigms would you be interested in knowing more about? Let us know in the comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *