Tags

, , , , , , ,

The project I am working on uses a browser page – I am developing on the Chrome browser as the client interface and Flask/Python on the Raspberry Pi to communicate with the browser and connect with readings coming in from sensors.  I am coding the browser code in JQuery and using ajax to talk to Flask.

Technologies this blog post assumes some familiarity – and I bumbled around the last couple of months learning – include:

  • HTML
  • JQuery
  • ajax
  • Flask
  • Python
OOH!!! YIPPEE!! SO MUCH TO LEARN!!!!
 
So here I am, trying to figure out why my calls to ajax keep failing.  Geez.  I’m googling for the answer, trying to follow Stack Overflow Q&A’s…but I’m still having difficulty.  What do I do?  Well, first I stop.  Then do Yoga…ah…much better.
 
Guess what I found out?  There is this  Postman app that is a very sweet way to understand and debug ajax <-> Flask interactions.  I wrote a simple Flask app that helped me understand:
  • how to just get data from the server app using GET
  • how to pass input into the server app using PUT

Flask App

from flask import Flask, render_template, jsonify, request

import datetime

app = Flask(__name__)

 

@app.route(‘/’)

def test():

    return jsonify({‘message’ :’It works! ‘})

@app.route(‘/posttest’,methods=[‘POST’])

def posttest():

    value = request.get_json();

    print(value[‘message’])

    return(value[‘message’]);

app.run(debug=True, host=’localhost’, port=9999)

I saved this file on the Raspberry Pi as app.py.  It has two routes, one for a GET, one for a POST.  I don’t explicitly state the GET method because by default Flask assumes it.  Also, I use debug=True so that changes I make in the code cause Flask to automatically update.  This means I don’t have to stop and then restart app.py.

Starting up the Flask app:

$ python app.py

 * Running on http://localhost:9999/ (Press CTRL+C to quit)

 * Restarting with stat

 * Debugger is active!

 * Debugger PIN: 115-663-274

Sometimes I’ve messed up stopping the Flask app when I close the terminal window.  This can happen – for example – when doing ctrl-z instead of ctrl-c:

 

OSError: [Errno 48] Address already in use

Googling around, I found I can release the Flask app by running.  Of course, changing the port from 9999 if I’m using a different one.

sudo lsof -i :9999 | grep “python” | cut -d ” ” -f2 | xargs kill -9

GET

Let’s start up the Postman app and do a GET route to the Flask app.  Doing a GET is easy-peasy.Pasted Image 1 8 18 3 38 AM
 
Type in localhost:9999 (the port the Flask app is listening on), make sure the big-ol-method button is set to GET, then hit SEND.
 
YIPPEE!!! – the Body returns the JSON sent from the Flask app:

@app.route(‘/’)

def test():

    return jsonify({‘message’ :’It works! ‘})

See the little code button?  When clicked, we get the JQuery code to copy/paste:

NewImage

The headers aren’t needed, so I remove them.

Post

The POST method is what we’re most interested in because we want to pass input into my Python app running on the Raspberry Pi.  

Flask Part

Here’s the Flask part of the test for handling a POST to the /posttest route:

@app.route(‘/posttest’,methods=[‘POST’])

def posttest():

    value = request.get_json();

    print(value[‘message’])

    return(value[‘message’]);

The key here is DO NOT FORGET to add methods=[‘POST’].

Postman Part

The Postman setup for Post is slightly more “complicated” than the GET because the Flask route assumes it is getting JSON: {“message”:”<some text>”}.  Note:  The POST will fail unless the value is a text string.  This is ok for passing JSON data since Javascript includes the JSON.stringify() function.

Pasted Image 1 8 18 4 43 AM

After changing the button that selects the operation to POST, the URL is changed to include the route to /posttest .  When the POST is selected, The Body radio button is available to let Postman know we will be sending JSON.  Finally, the JSON – formatted to what the /posttest route is expected in the Flask app – is typed in.  Hit the Send button. Notice the response area includes the text from the message.

Now let’s look at the code so we can figure out how to add this to our JQuery:

var settings = {

  “async”: true,

  “crossDomain”: true,

  “url”: “http://localhost:9999/posttest&#8221;,

  “method”: “POST”,

  “headers”: {

    “Content-Type”: “application/json”,

    “Cache-Control”: “no-cache”,

    “Postman-Token”: “6148564a-2ce3-2e7a-f43d-710a094274de”

  },

  “processData”: false,

  “data”: “{\”message\”:\”test message\”}”

}

 

$.ajax(settings).done(function (response) {

  console.log(response);

});

From here, we can experiment with removing some of the extra “goo” auto-generators typically insert (like some of the headers…but NOT application-json).

 

So there you have it.  We’ve successfully interacted with our server side code that is stitched together with Flask.  Using Flask is great because that means we can write the server code in Python..  That’s it for now.  Thank you for reading this far.  Please find many things to smile about.