Saltar al contenido

Flask, a python microframework for web development

Yesterday, a mate from my master’s degree wrote me an email asking for some help. He had developed a predictive algorithm using python and needed to feed it with items taken from a web site, showing back on the web the predictions obtained from the algorithm.

Although he is quite new in programming, he has gained lot of expertise working on the master’s practices and now is capable of programming python code without much hassle. The problem is that he was recommended to use a python web framework called Flask, and the word framework scared him and made him ask for some help to fight with this kind of wild animal unknown to him.

Taken directly from their web site, Flask is

A microframework for Python based on Werkzeug, Jinja 2 and good intentions

The web is very friendly, as well as the extensive documentation, and using this framework seems a tremendously easy task.

To help my friend, I made a simple app that could cover his needs, and thanks to the well documented API it didn’t took me more than 10 minutes. Web interface for predictive algorithm

from flask import Flask, request
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def init():
    if request.method == 'POST':
        word = request.form['word']
        # Insert here the code to get the prediction from the word introduced
        prediction = ""
        return "<b>Word introduced</b> = " + word + "<br><b>Prediction</b> = " + prediction + "<br><br><a href='/'>Back</a>"
    else:
        return '''
        <form method="post">
            <p><input type=text name=word>
            <p><input type=submit value=Send>
        </form>
    '''

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

Its operation is easy. We point the application to the root page (/) and there wait for GET and POST methods. After that we define a function called init to manage each request.

If we are on a POST request, it means that we have received information from the web form, so we now have to obtain the word entered by the user and apply our predictive algorithm. Lines 8 and 9 (highlighted) are the ones that my mate should work on to include his algorithm and obtain it’s results. After them, we simply print back the results with a return.

Flask POST

If we are on a GET request, we simply print the form to obtain the word that will be processed by the algorithm.

Flask GET

To make it work, simply install Flask and then execute the script:

$ pip install Flask
$ python myFlaskApp.py
 * Running on http://localhost:5000/

If everything went ok, you will have the application ready for your requests at http://localhost:5000

And that’s all. I hope it works for him and for anyone that would like to start using this awesome framework