Dealing With Flask & AJAX

Flask is nice, though I disagree with their slogan that it is fun. Sleeping is fun. So is eating candy. Dealing with web technology is not, and never will be.

However, like happiness in my life, the documentation for dealing with async calls is lacking. To save others some time and frustration, here are some code samples. These all assume you have jQuery loaded.

Basic AJAX

Say you just want to send a POST back to the server with no parameters. This is rather simple.

JS:

$.ajax({
    url: '/someUpdate',
    type: 'POST'
});

Flask:

@app.route( '/someUpdate', methods = [ 'POST' ] )
def some_update( ):
    #do stuff
    return jsonify( "success" )
GET Request

Now let's get a bit harder. What if we want to send a GET request with a single parameter back to the server?

JS:

$.getJSON( '/getSomething', { 'thing' : some_js_value } , function( data ) {
    //do stuff with data
});

Flask:

@app.route( '/getSomething', methods = [ 'GET' ] )
def get_something( ):
    thing = request.args.get( 'thing', '', type = str )

    return jsonify( "success" )
POST Request

What about a POST request with a single parameter?

JS:

$.ajax({
    url: '/someDelete',
    data: JSON.stringify( "thing" ),
    contentType: 'application/json',
    type: 'POST',
    success: function() {
        //do stuff
    }
});

Flask:

@app.route( '/someDelete', methods = [ 'POST' ] )
def delete_recipe( ):
    db = get_db( )

    db.execute( 'delete from thing where name = ?', [ request.json ] )
    
    db.commit( )
    return jsonify( "success" )
POST'ing an Array

What if you want to POST an array?

JS:

var things = [ ];

$.ajax({
    url: '/postArrayOfThings',
    data: JSON.stringify( things ),
    contentType: 'application/json',
    type: 'POST'
});

Flask:

@app.route( '/postArrayOfThings', methods = [ 'POST' ] )
def post_array_of_things( ):
    db = get_db( )

    for thing in request.json:
        # db.execute(  )

    db.commit( )
    return jsonify( "success" )

If we have an array of objects like:

var items = [ ];

$.each( function( ) {
    items.push( { 'thing1' : thing1.val( ), 'thing2' : thing2.val( ) } );
});

We can access those keys easily in Flask:

    for thing in request.json:
        db.execute( 'insert into things (thing1, thing2) values (?, ?)', [ thing[ 'thing1' ], thing[ 'thing2' ] ] )
GET'ing Array of SQLite Results

Note: There is probably a better way to do this. However, I can't find it.

Say we have a SQLite table called things. Things has two columns, 'thing' and 'tiny_thing.' Each 'thing' is mapped to multiple 'tiny_things' like so:

Thing       Tiny_Thing
----------------------
Muffin      Berry
Muffin      Flour
Muffin      Starch
Muffin      Whiskey

From the GET section, we know how to pass a 'thing' up to the server, but how do we return an array of tiny_things? We can't just jsonify the results of fetchall because flask will explode.

Flask:

@app.route( '/getTinyThingsForThing', methods = [ 'GET' ] )
def get_tiny_things_for_thing( ):
    thing = request.args.get( 'thing', '', type=str )
    db = get_db( )

    cur = db.execute( 'select tiny_thing from things where thing = ?', [ thing ] )

    tiny_things = cur.fetchall( )
    tiny_things_parsed = []
    for tiny_thing in tiny_things:
        tiny_things_parsed.append( tiny_thing[ 0 ] ) #sqlite stores all results as tuples 

    return jsonify( tiny_thing_parsed )

Remember, if you put any of my code in production, I'm so sorry.