My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Intro to Flask

Sahaj Gupta's photo
Sahaj Gupta
·Jan 30, 2021·

3 min read

Hi there ! today in this blog we will be seeing how easy it is to get started with Flask but before that let's see what Flask is and set up virtual environment.

Flask

Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications.

lightweight : refers to small in size

WSGI : synchronize web server

This means that flask is a small in size synchronized web server which is designed to make things easy.

Setting up virtual environment

I use python venv for creating my virtual enivorment but you can use whatever you like.

python3 -m vevn vevn

This line will create a folder named venv in your current folder inside this venv folder resides your virtual environment.

To activate your virtual environment in linux or mac

source venv/bin/activate

for windows

venv/bin/activate.bat

Now the Flask Part

With you venv activated first we need to install flask via pip.

pip install flask

and let it install might take a minite or two

Now create a file name it whatever you want but as for the convention i'll name it app.py


from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

That's. It you have made your first flask application. you can run it as you run any other python file.

python3 app.py

your app will be running on localhost:5000 or 127.0.0.1:5000 And you will see something like

app.py

Now obviously you will have some doubts like,

  • what does __name__ refers to in 2nd line?
  • what is the meaning of route ?
  • why did we use if block?

Starting with the first question.

What is the meaning of __name__?

__name__ refers to the name of the file. If it's a standalone file like one we just created then __name__ = app and if file is inside some module let's say module name is test then __name__ = test.app

What is the meaning of route?

route refers to the endpoint of a site. thing which is after the domain and before ? example www.learncodeonline.in/courses?sort=asce here courses is route and / means home page => www.learncodeonline.in

Why did we use if block?

if block is just there to make sure that flask only runs when it is runned via python3 app.py not when this file is imported into anyother file basically main is the file name when you run it via python

That's it for todays blog. I hope you can get some value out of this. Thanks for reading 😀

My Links : Instagram : Github : G-mail