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
1 |
sudo pip install virtualenv |
Once installed, a new virtual environment is created in a folder.
1 2 3 |
mkdir FlaskTest cd FlaskTest virtualenv Test |
So now we have a virtual environment Test created in the FlaskTest folder
We now install Flask in this environment.
1 |
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:
1 2 3 4 5 6 7 |
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'HELLO WORLD’ if __name__ == '__main__': app.run() |
1 |
app.run(host, port, debug, options) |
All parameters for the run function are optional
host
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
port
Default value is 5000
debug
Default value is false. If it is set to true, we get debug information
options
To be forwarded to underlying Werkzeug server.
Now we can execute the program and see its working. Execute the program using the command
1 |
python HelloWorld.py |
You will get the following output.
1 |
* 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:
1 |
@app.route('/hello') |
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
Leave a Reply