Skip to content
Advertisement

Flask ‘render_template’ after client POST request

So, I’m working on a small web application that has a small canvas, the user is supposed to draw something and then I want to do some python with the image from that canvas. Like this:

enter image description here

This is working fine. When I press “Click me!”, I call a JS function that POST the image to my Flask server. And this is also working, the thing is that after I receive the image, I want to render a new page to show some results, but this page is not rendering at all.

Now, I’m completely new to Javascript, barely know anything, basically every JS I’m using is copy pasted from the internet, so I’m assuming I must be missing something very simple, I just don’t know what.

Here is the server code:

from flask import Flask, render_template, request
import re
from io import BytesIO
import base64 
from PIL import Image

app = Flask(__name__)

@app.route("/")
def hello_world():
   return render_template('drawing.html')

@app.route("/hook", methods=['POST', 'GET'])
def hook():
   image_data = re.sub('^data:image/.+;base64,', '', request.form['imageBase64'])
   im = Image.open(BytesIO(base64.b64decode(image_data)))
   im.show()
   return render_template('results.html')

The first route just opens the canvas, the second is executed after the client’s request, which has this function:

function surprise() {
  var dataURL = canvas.toDataURL();
  $.ajax({
    type: "POST",
    url: "http://127.0.0.1:5000/hook",
    data:{
      imageBase64: dataURL
    }
  }).done(function() {
    console.log('sent');
  });}

Apparently, this is working. I have the line:

im.show()

Just so I can see the image and I get exactly the drawing from the canvas, which I’m now supposed to work on:

enter image description here

but the results page is not rendered afterwards, nothing happens. Why?

Advertisement

Answer

The problem is that you are returning the page to view in response to the call that posts the image. Instead, you should return a response (for example in a json format) containing the information regarding the result of the call just made (i.e. the post of the image) and consequently, on the client side, you must redirect the user to the appropriate page .

To understand why it is not working, print the content of the response returned from the call made

var response = '';
$.ajax({ type: "POST",   
         url: "http://127.0.0.1:5000/hook",   
         data:{
             imageBase64: dataURL
         },
         success : function(text)
         {
             response = text;
         }
});

alert(response);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement