Technology Sharing

[Flask Notes] A complete Flask program

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

As mentioned earlier, Flask is a lightweight web development framework. Why is it lightweight? Because it can be run with just a few lines of code. Let's take a look at the simplest flask framework.

Install Flask

Before looking at the Flask framework, we need to install the flask module first. Anyone who has learned python must know that the installation of the flask module is actually very simple. Just use the command

pip install flask
  • 1

It can be installed. One thing to mention here is that if you encounter a download failure when installing the module, it is mostly because Python uses the official download module address to download by default, and this address is sometimes not stable when accessed in China. It is recommended to use Tsinghua's download source to download, which is much faster and will not often report errors or timeouts.

https://pypi.tuna.tsinghua.edu.cn/simple
  • 1

The method of use is also very simple. There are two methods. The first is to add a-iParameters, followed by a URL, will download the module from this address, as follows

pip install flask -i https://pypi.tuna.tsinghua.edu.cn/simple
  • 1

The above method can only be used for temporary downloads and cannot change the download source permanently. Here is another method to change the default download source.

pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
  • 1

After the change, you canpip config listCheck whether the change is successful. If the change is successful, it will be displayed as follows

(.venv) ❯❯ pip config list
global.index-url='https://pypi.tuna.tsinghua.edu.cn/simple'
  • 1
  • 2

A minimal and complete Flask program

After Flask is installed successfully, we can look at an example. This is a complete flask program, which is also a small unit required for flask to run. We save the following code into a py file, such as my_flask.py

from flask import Flask

app = Flask(__name__)

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

if __name__ == '__main__':
    app.run(debug=True)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

As shown in the code above, flask can be run in just 10 lines of code, so flask is a lightweight web framework. Although the code above is short, it has everything you need to run flask. The application instance, routing and view function constitute the simplest Flask program.

Applications

The application instance is actually the application object of Flask. The object here is not your girlfriend, but a web application core that can include request processing, routing distribution, and view function calls.app = Flask(__name__)If we look at the source code of the Flask example, we can find that it contains a lot of content, such as running startup parameters, routing rules, definition of sending and receiving requests, etc., which will not be discussed in detail here.

routing

Routing is used to handle the correspondence between URLs and functions. Here we must talk about the entire working principle of the web to facilitate understanding. First, look at the following figure
insert image description here
The web browser initiates a request, the web server receives the request and sends it to the Flask application. After the Flask application receives the requested URL, it looks for the corresponding processing function. This is how the entire routing works.
And corresponding to the above program, that is the function

@app.route('/')
def index():
    return "Hello, World!"
  • 1
  • 2
  • 3

If you learn Python in depth, you will know that@app.route('/')It is a decorator used to register view functions. The content in the brackets is the path to be used.'/'It means the root path, that ishttp://127.0.0.1:5000; If it is changed to‘/login/’It means using the login path, that ishttp://127.0.0.1:5000/login/; If written as'/user/<name>'It becomes a dynamically variable route, that is,<name>It will change dynamically according to the content of the transmission, such ashttp://127.0.0.1:5000/user/jay, this jay needs the browser to be attached to the route.
This is a simplification in Flask for ease of use. The actual traditional way of defining routes does not use decorators. Since the traditional method is no longer commonly used, it will not be discussed in detail here.
There is one more thing that must be mentioned about routing. Flask's dynamic and variable routing only supports string, int, float, and path types. For example,<name>The string type is used. This type does not need to be written by default. It can match any character sequence except the slash (/). For the other types, if you need to identify them, you need to write the type, such as'/path/<path:my_path>'

View Functions

The view function is the function that handles inbound requests, which is the function defined in the route.

def index():
    return "Hello, World!"
  • 1
  • 2

The above function is the so-called view function. It is used to process incoming requests and return responses.

response

The response is mentioned above, but what is it? The response is the value returned by the view function, which can be a string or a complex form. You can also use the render_template() function provided by Flask to return an HTML. At the same time, the response can also directly use the redirect() function to redirect the route.

start up

The above is the five internal organs of the Flask program, but there is still one entry point missing to make Flask run, which is the last two lines in this code

if __name__ == '__main__':
    app.run(debug=True)
  • 1
  • 2

first rowif __name__ == '__main__':Anyone who has learned Python knows that this is the entry point of Python, that is, running the current file or module directly as the main program.
second lineapp.run(debug=True)It calls the Flask object created above and executes the run() function to make Flask run. The debug is passed as a parameter to the run() function to let Flask know that it is started in debug mode. In debug mode, Flask will automatically load the reloader and debugger.
Then we go to the command line, enter the directory of the my_flask.py file, and enter the command linepython my_flask.pyYou can start the program, as shown in the figure below.
insert image description here
We open the browser and enterhttp://127.0.0.1:5000You can see Hello, World!, as shown below
insert image description here

At this point, we have covered all the concepts that this complete Flask program should have. Of course, these are the most basic content. To fully develop a web application based on Flask, there is still a lot to learn, such as templates, databases, front-end technology, etc. The author also learns while writing, and also draws on the Feynman learning method to make himself remember better. If there are any omissions and errors in the writing process, please point them out.