Python is so powerful. The popularity and growth of Python is increasing day by day. Not only that, it’s easy to learn and use. What makes it unique is hundreds of open source python libraries and framework. In this post, we explore Flask, a micro and light weight web framework that you can use to save your time and effort by providing the required functionality.
We’ll start by installing the required libraries to start working with Flask and end by writing our all time favorite program “Hello World”. Let’s dive in.
Requirements and Setup.
1- Install virtualenv.
python3 -m pip install --user virtualenv
2-Create a virtual environment.
3- Activate the environment.
4- Install Flask
pip3 install Flask
Hello World 😊
Before doing any thing, it’s necessary to understand the Folder layout for Flask web app.
/env app.py (Your python file) /env/static/styles main.css /env/static/img contains all the image /env/templates index.html
Hello World! program in Flask is easy and ten lines long :) These ten lines of code are sufficient to create a simple web page.
So, let’s get started.
The code, once all written out, will look like this:
# app.py from flask import Flask app = Flask(__name__) @app.route("/") def fun(): return 'Hello World!' if __name__== '__main__': app.run()
Line 2- Import the required library.
from flask import Flask
Line 3- Create a new App.
app = Flask(__name__)
Line 5- Declare a “decorator”.
@app.route(“/”) # at the endpoint /
Lines 6,7- Define a function.
def fun(): return 'Hello World!'
Lines 9,10- Run the application.
if __name__== '__main__': app.run()
Running the Website
Once you have finished developing the code you can test it by running it using terminal(Oh, don’t tell me you hate Command Line/Terminal). You can run the command based on your file name.
For example, in my case it is app.py.
Till next time :) Happy Learning.
If you liked this article make sure to 👏 it below, and follow me on Twitter here