Flask is a micro web framework written in Python
Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc.
virtualenv which is a virtual Python environment builder, is used to help a user to create multiple Python environments side-by-side. Thereby, it can avoid compatibility issues between the different versions of the libraries.
The following command installs virtualenv
sudo pip install virtualenv
Once installed, a new virtual environment is created in a folder.
So now we have a virtual environment Test created in the FlaskTest folder
We now install Flask in this environment.
sudo pip install Flask
Now we have Flask installed in our system and we can import it in our projects.
As we have setup environment to work with Flask library, lets run a sample code to test Flask. Let’s create a python file HelloWorld.py and write the following code:
from flask import Flask
app = Flask(__name__)
return 'HELLO WORLD’
if __name__ == '__main__':
app.run(host, port, debug, options)
All parameters for the run function are optional
Hostname to listen on. Defaults to 127.0.0.1 (localhost). You have to set it to ‘0.0.0.0’ to have server available externally
Default value is 5000
Default value is false. If it is set to true, we get debug information
To be forwarded to underlying Werkzeug server.
Now we can execute the program and see its working. Execute the program using the command
You will get the following output.
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Now if you open your browser and type in your localhost address that is, 127.0.0.1 along with the port number 5000
You can see HELLO WORLD being printed on your browser.
You can use Ctrl+C to stop running the program.
Now if you need to set a specific URL other than the homepage of localhost, you can specify it in the route() function.
If you change the route function in the above code to:
And run the program again, you can see that opening the homepage of localhost renders no output, but instead if you add the URL specified in route function to the homepage address:
Now you can see your program being run…
Have fun working with Flask library