Flask App for Data Science. Data scientists generally work in the... | by Kayli Leung | Towards Data Science

Data scientists generally work in the back end. Building an interactive app is not a strength of mine, but it can be a great way to show off the work that you can do. In this post, I will discuss some tips for creating a Flask App that I have learned while building a website for my Travel Recommendation System.
Before we even start thinking about beautifying our app, you should have all your functions in a separate py file as opposed to within a Jupyter Notebook. This step is necessary as Flask cannot communicate with Jupyter, but it can communicate with py files.
The organization of your repository will be important for deployment to a website. Upon entering your repository there should be a folder that has the same name as the repository. In this folder should be everything that your app will need. For example, a recommend.py was necessary for my app, but a scrape.py was not because it was only used to collect data.
The other file you will need in this folder is __init__.py. This can be an empty file, but this allows the code to be run when the package is imported. Finally, you will need a web_app folder. This folder will contain the files needed to run your app including bootstrap static and template folders.
travel_destination_recommendation    travel_destination_recommendation         __init__.py         recommend.py         web_app              __init__.py              static              templates              app.py
When you want to run/test your app you will use the following code in the command line while you are in the highest directory:
FLASK_APP = travel_destination_recommendation.web_app.app.py
In app.py you can import your custom functions with:
from ..recommend import custom_functions
In the app.py file is where we import from flask. There are some tools you want to import:
Flask
request (allows for communication with Javascript)
render_template (creates the template from HTML)
jsonify (everything needs to be returned in JSON format)
from flask import Flask, request, render_template, jsonifyapp = Flask(__name__, static_url_path="")
There needs to be something for your app to show up on. This is where your first function will be. Any function that communicates with the HTML, starts with the decorator @app.route(‘/’). Within the parenthesis is the tag of the HTML that we want to interact with. The / on its own represents the homepage.
@app.route('/')def index():    """Return the main page."""    return render_template('theme.html')
I would recommend, especially for a first app, to start without any design. I start with this function. It takes in text from a text box and returns a prediction.
with open('model.pkl', 'rb') as f:         model = model.load(f)@app.route('/predict', methods=['GET','POST'])def predict():         """Return a random prediction."""         data = request.json     prediction = model.predict_proba([data['user_input']])         return jsonify({'probability': prediction[0][1]})
The piece of code above connects to the following bit of HTML that creates one text box, and a button that is labeled “Predict!”
<html>    <head>        <title>Predict</title>        <script type="text/javascript" src="brython.js"></script>        <script type="text/javascript" src="brython_stdlib.js"></script>       </head>        <body onload="brython(1)">        <script type="text/python3">            from browser import document, ajax            import json            import warnings           def show_results(response):                  if response.status==200:                         document["result"].html = response.text                  else:                        warnings.warn(response.text)           def get_prediction(ev):                  """Get the predicted probability."""                  req = ajax.ajax()                  req.bind('complete', show_results)                  req.open('POST', '/predict', True)              req.set_header('content-type','application/json')                data = json.dumps({'user_input': document['user_input'].value})        req.send(data)                  document["predict_button"].bind("click", get_prediction)            </script>      <textarea id="user_input"></textarea>          <button id="predict_button">Predict!</button>          <div id="result"></div>   </body></html>
So that is quite a bit of code. Let’s break it down. The first thing we want to make sure we do is set the script to brython. Brython stands for browser python and allows for the use of python in the Javascript environment. Set this in both the script as well as the body.
In the script of the body is where we want our code to be. We need to have two separate functions to collect data and to show results. In show_results we only want to a result, if one exists. In the if statement, we reference the HTML document’s div id “result” because this is where we want the result to be shown.
In get_predication, we have the parameter ev which means event. This means that the function will be called when a particular event occurs (we’ll come back to this later).
The req.bind(‘complete’, show_results) line connects this function to the show_results function.
The next line req.open(‘POST’, ‘/predict’, True) connects this function to the function we created in our app.py file through the decorator.
The data is what we can communicate to the app.py file. Notice that the results should be dumped into JSON format. There are two “user_input” noted in this line. The one in the dictionary is the key, which is referenced in the app.py function as part of the data. This data is sent to the app.py function through the req.send(data) line. The document[“user_input”] is the id of the text box.
Now that the function is complete, we need to have the event that triggers the function. We want the make a prediction when the predict button is clicked. The last line in the script connects the button with a specific id and binds a “click” to the function get_prediction.
This is a very basic Flask app. By making small changes over time we can create a beautiful app. As a Data Scientist, you don’t need to be a master of web development, but it can be a fun tool to show off what your model can do.
Thanks to my coach for my Flask starting point, check out his Spam predictor here. To check out a detailed Flask app, take a look at my repository.