Introduction

In each section, I will show pieces of code for you to follow along. All the code used in the tutorial is available in this GitHub Repository.

What is HTTP and What Does it Have to do with Flask?

HTTP is the protocol for websites. The internet uses it to interact and communicate with computers and servers. Let me give you an example of how you use it everyday.

When you type the name of a website in the address bar of your browser and you hit enter. What happens is that an HTTP request has been sent to a server.

For example, when I go to my address bar and type google.com, then hit enter, an HTTP request is sent to a Google Server. The Google Server receives the request and needs to figure how to interpret that request. The Google Server sends back an HTTP response that contains the information that my web browser receives. Then it displays what you asked for on a page in the browser.

How is Flask involved?

We will write code that will take care of the server side processing. Our code will receive requests. It will figure out what those requests are dealing with and what they are asking. It will also figure out what response to send to the user.

To do all this we will use Flask.

What is Flask?

It makes the process of designing a web application simpler. Flask lets us focuson what the users are requesting and what sort of response to give back.

Learn more about micro frameworks.

How Does a Flask App Work?

The code lets us run a basic web application that we can serve, as if it were a website.

Image for post

basic flask app template

This piece of code is stored in our main.py.

**Line 1: **Here we are importing the Flask module and creating a Flask web server from the Flask module.

Line 3: name means this current file. In this case, it will be main.py. This current file will represent my web application.

We are creating an instance of the Flask class and calling it app. Here we are creating a new web application.

**Line 5: **It represents the default page. For example, if I go to a website such as “google.com/” with nothing after the slash. Then this will be the default page of Google.

Image for post

This is what the @app.route(“/”) will represent

Line 6–7: When the user goes to my website and they go to the default page (nothing after the slash), then the function below will get activated.

**Line 9: **When you run your Python script, Python assigns the name “main” to the script when executed.

If we import another script, the **if statement will prevent other scripts from running. **When we run main.py, it will change its name to main and only then will that if statement activate.

**Line 10: **This will run the application. Having debug=True allows possible Python errors to appear on the web page. This will help us trace the errors

#web-development #backend-development #flask-framework #python

Flask Framework Basics (Python)
1.15 GEEK