Skip to content

[Python] Flask Study Notes (0): Create a basic static web page

Last Updated on 2021-06-29 by Clay

I have always wanted to make a tool website, so I started to learn basic HTML knowledge.

For this reason, I practiced using Flask and Django. This article is to record some of my learning and understanding of Flask.


Introduction

Flask is a lightweight web development framework. In the official documents, it will be mentioned at the beginning: the so-called "lightweight" does not mean that you only need one python script to complete all the requirements.

Flask only has the most basic core functions, but you can expand various functions according to your needs.

And it is worth mentioning that since it is a framework developed in python, so you can use python to complete many background tasks, which is very convenient.


Installation

If you have no python interpreter in your environment, you can refer: [Python] Tutorial(1) Download and print "Hello World"

And if you are use Flask in the first time, you need to use the following command to install it:

pip3 install Flask

Hello World

Before installation, you can try to run a basic web page, it have no any more function and just show Hello World on the screen. Yes, this is boring.

# -*- coding: utf-8 -*-
from flask import Flask

app = Flask(__name__)


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


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



Output:


Click "http://127.0.0.1:5000/" url and you will open the following web page via default browser.


Below we explain the code line by line. Here we import the Flask-related package and use the "app" variable to give Flask this object.

from flask import Flask

app = Flask(__name__)



Here, we first use "app.route('/')" to register a space "/" (this symbol means the root directory), and define the program we want to execute below. As you can see, it is a string that returns "Hello World!".

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



This part is to execute the app variables that we initialized just now, using the "run()" function to execute.

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



By the way, if the Port is set to 5000, it is Flask's default Port. If you want to change it, you can modify the executed part of the last line to:

if __name__ == '__main__':
     app.run(host='127.0.0.1', port=8000)



In this way, the Port will be opened at 8000, and the number can be set arbitrarily.

If the webpage is opened normally without any problems, then congratulations! Flask can work normally on the computer. This first step is very important. Confirming that Flask can work is the basis for all future notes.


References


Read More

Leave a ReplyCancel reply

Exit mobile version