DEV Community

Prajval Singh
Prajval Singh

Posted on

Complete Flask - Part 1: Basics of Flask

Prerequisites:

  • Python
  • A text editor of your choice
  • Lots of excitement!

Ok, you learned Python and want to use your skills to build something.

One of the main uses of Python is web development,
and there are quite a few technologies to do that.

Some of the most popular ones are:

  • Flask
  • Django
  • FastAPI

You are going to learn Flask today, which is a micro-framework and minimalistic.

To get started open up a terminal and make sure your Python is working by typing: python

I am using Python 3.9.0 but you can use any version greater than 3.6

Install flask by using: pip install flask

Basic Hello World

So now let's get coding by creating a basic Hello World app.

Create an app.py file in the root folder and import the Flask class from flask like this:

from flask import Flask
Enter fullscreen mode Exit fullscreen mode

Then create an app instance:

app = Flask(__name__)
Enter fullscreen mode Exit fullscreen mode

__name__ refers to the name of the current module and it is passed as an argument to Flask.

Now create a route decorator with '/' (single slash means home page):

@app.route('/')
Enter fullscreen mode Exit fullscreen mode

Just below the decorator create a home function that returns the text "Hello, World!":

def home():
    return "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

The complete code of hello world app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

Run the app using flask run and if you are getting an error like could not locate a flask application, rename the hello world file to app.py as I already mentioned and that should work.

Now go to localhost:5000 and you should see Hello, World!

That's it for Part 1, I will be releasing Part 2 soon and there is a lot to cover so stay tuned!

Top comments (0)