Equation solver webapp in Python
Question: I am making an equation solver webapp in Python (Flask framework). App takes
user input [a, b, c] and sent to server by calling a server side python
function and get the results displayed using AJAX.

Part of Client JavaScript:

    
    
    $.getJSON($SCRIPT_ROOT + '/_serverFunction', { form data });
    

Server Python function:

    
    
    @app.route('/_solve')
    def solve():
        a = request.args.get('a')
        b = request.args.get('b')
        c = request.args.get('c')
        cof = [a, b, c]
        roots = np.roots(cof)
        return jsonify(roots)
    

Above works just fine and i get the results displayed as per the input.

However, I would also like to show a graph representing the solution next to
the above results.

I am able to generate a dummy static graph at server using matplotlib and send
to the client with the following:

    
    
    <img src="/image.jpg" id='bg'>
    

Server side python code:

    
    
     @app.route('/image.jpg')
        def image_jpeg():
            image = StringIO()
            plot(image)
            image.seek(0)
            return send_file(image,
                             attachment_filename="image.jpg",
                             as_attachment=True)
    
    def plot(image):
        x = np.linspace(0, 100)
        y = np.sin(x)
        pyplot.plot(x, y)
        pyplot.savefig(image, format='jpg')
    

Above works and I get a static curve when i load the page. But I would like
this graph to change when user submits the input to the server to solve the
equation every time.

How to make the both calls to the solve() and image_jpeg() from the same same
AJAX call?

How do the I share the user data [a , b ,c] across functions so the graph can
be generated and sent back.

**_Update:_**

    
    
    $('img').attr('src',"data:image/png;base64"+ "," + data.imgdata);                             
    

On server:

    
    
        imgdata = image.getvalue()    
    import base64
    imgdata = base64.b64encode(imgdata)    
    

imgData is passed along with json.


Answer: One request can't become two, unfortunately, but there is a way of doing what
you want.

In order to achieve this, you could send the image as a [data
url](https://css-tricks.com/data-uris/) inside the JSON you request from your
server, then in JS you simply set the image element's **src** attribute the
data.

You would start by moving the **image_jpeg** function into your solve method,
since you have the image data in a string already all you need to do is encode
it into base64 and prefix it with **"data:image/png;base64,"** changing the
mime to suit the image format.

Also, to complete the answer, you can share user data across functions. You
would usually use Cookies, in Flask they wrap cookies in Sessions to make it
even easier for you, [take a
look](http://flask.pocoo.org/docs/0.10/quickstart/#sessions). That being said,
I don't think they fit this problem.

