Setting a web app using Flask & Python
As a data scientist, we worked with Jupyter Notebook and Python to run our code. I will try to explain how to use Flask to present your work as a web app.
- Have an Integrated Development Environment (IDE)
Any editor is fine, preferably with a markdown. I use Sublime Text as my IDE.
2. Set up Environment
Open up terminal, and run pip3 install Flask
.
Once that is done, Flask is installed! Yay!
3. Set up an application
Let’s start with something simple. A ‘Hello World’ App.
a. Create a new project. In this case, I have added this project under Projects/flask_tutorial
. Once created, open the folder in your IDE. We are going to add code in there.
b. Under the flask_tutorial folder, create a new file app.py
. This is where the app will run.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World’
if __name__ == '__main__':
app.run()
Paste this into app.py
. This is the underlying code to get the app up and running.
@app.route('/')
signifies where the url is supposed to be. /
is the index page. The method hello_world
right below @app.route('/')
is where it is being called when the index page is served. When a request is being sent for the index page, this method is called, in this case, printing ‘Hello World’.
c. Setting up the connection
Go to terminal and run this command:
set FLASK_APP=app.py
python -m flask run
4. When the command is executed, you will get a localhost and a port, the default will be http://127.0.0.1:5000/. Enter that into your browser and you will see ‘Hello World’ printed on the screen!
5. There you have it! A simple web app!