[Python] Organize the basic structure of Flask apps (Aim for de-copying)


Until now, I wrote the flask code as" magic "without knowing it well, so I will investigate it once and organize it. The goal is

――Be able to understand what is happening with the description --Understand the grammatical structure of the written code and verbalize it so that you can examine it later.

I will try to organize it aiming at this area.

Basic structure of flask app

Let's take a look at the basic structure of a simple web app.

I referred to here such as explanation (the script has some differences) Getting Started with Flask — Flask Handson 1 documentation

#① Module import
from flask import Flask 

#② Web application creation
app = Flask(__name__) 

#③ Endpoint setting (routing)
def hello():
    return 'Hello World!'

 #④ Start Web application~~~~
if __name__ == '__main__':

If you run this script and access "" in your browser, you should see "Hello World!" On your screen. If all goes well, it means that the web app can be launched locally.

Grasp the rough flow and image

The above script is roughly divided into four parts.

-** (1) Module import : Enables you to use a code file packed with the functions required to create an application. - ② Create a web app : Prepare the "core of the app" packed with the necessary functions. - ③ Specify endpoint (routing) : Write the URL accessed from the browser and the corresponding process here. - ④ Launch the web application **: Allow the application to be launched (displayed in the browser) when the file is executed.

When we make a web application with Flask, we will make various parts of ③. Importing ① is one of the basic grammars of python. And ②④ is a flask operation, so basically it seems that there is no need to change the code, and this is the part that is often written as "magic".

Take a closer look at each part

① Module import

from flask import Flask

I'm importing the Flask class of the flask module. This allows you to take advantage of the functionality of the Flask class within this script.

What is a module?

A python file packed with functions and classes. It seems good to think that the file saved under the name hogehoge.py is one module.

② Web application creation

app = Flask(__name__)

I'm creating an instance of the Flask class by passing Flask (__ name__) and __name__ as the first argument and assigning it to ʻapp. This ʻapp is an image that contains the core of the flask app, and you can define the routing with ʻapp.route () (③) or start the local server with ʻapp.run () in the future. Will be.

About the global variable __name__

__name__ is one of the attributes of the module and seems to be a global variable (it's a strange name, isn't it? And its identity is a variable that stores "where the program is called and executed". It's a strange name.

When this .py file is launched directly, the __name__ will contain the string __main__. On the other hand, when this file is called by ʻimport from another script, the module name (file name without extension) will be entered in name`.

(I still don't understand what's happening when I pass this to the first argument of Flask ())

③ Endpoint setting (routing)

def hello():
    return 'Hello World!'

This description defines the routing It's a simple description, but it seems that a lot of things are condensed.

Here's a quick quote from Getting Started with Flask — Flask Handson 1 documentation).

The line @ app.route ('/') registers the action for the app with the URL /.

In other words, when we access the URL "http://hogehoge.com/" (path is /), we create an action "I will return this kind of processing" with a function and link them one-to-one. I am. In this example, the return value of the hello () function (the string after return) will be displayed on the web page. It seems that this function is called "view function".

Now, what does the strange symbol @ represent here?

The line starting with> @ is called a decorator and does some processing for the functions and classes defined in the next line. @ app.route ('/') performs the process of mapping the function defined in the next line to the specified URL.

I think the "decorator" here is a slightly advanced Python language grammar. It seems to be quite difficult to understand the grammar around here and how the view function works and the result is displayed on the Web, so I would like to deepen my understanding while learning a little more.

Decorators and high-rise functions

A "decorator" is a python description method that can smartly describe processing using a "high-rise function". A "high-rise function" is a function that receives a function as an argument and processes it, and a function that returns a function as a return value. That is. Here, it is thought that the decorator is used to pass the function hello () to the higher-rise function route () for processing. (Since the understanding of this area is ambiguous, please point out if it is wrong)

Arrangement of terms

--Routing: Linking URLs with actions. Here, the path and the view function are linked. --Endpoint: Refers to the URL to access. --URL and path: To specify the location of the file. URLs are like absolute paths, addresses on the Internet. --View function: A function that describes what kind of action is returned in response to a request.

④ Start Web application

if __name__ == '__main__':

Finally, run ʻapp.run () to start the local server and launch the app. The ʻif statement determines "whether this program was executed directly". As seen in (2), when the file is directly executed as a script, __main__ is assigned to __name__. In other words, here, if the program is executed directly, ʻapp.run ()` will be executed and the application will be launched.

run () method

--You can specify "host", "port number", and "debug mode" in the run () function of this Flask with keyword arguments. Can be started without it. --For example, you can start it by writing ʻapp.run (host ='', port = 8080, debug = True). --ʻApp.run (debug = True) -> Run in debug mode --ʻApp.run (host ='') -> Specify the host --ʻApp.run (port = 8080) -> Specify port number (5000 by default)

Arrangement of terms

--Host: (Under summary) --Port number: (summarizing)

(Remarks) WSGI standard

--Meaning of Web Server Gateway Interface. --The standardized interface standard for connecting a web server and a web application is called the WSGI standard. --Many Python frameworks such as Flask and Django use this WSGI standard. ――If you just develop a web application normally, you don't have to be very conscious of it.

in conclusion

It is not necessary for a real beginner to be aware of it, but I feel that if you deepen your understanding to move on to the next step, you will be able to do more. The latter half was pretty quick, so I'll fix it again according to my understanding.

Read the document. Quickstart --Flask v0.5.1 documentation API — Flask Documentation (1.0.x)

Recommended Posts

[Python] Organize the basic structure of Flask apps (Aim for de-copying)
I summarized the folder structure of Flask
Pandas of the beginner, by the beginner, for the beginner [Python]
Python Basic Course (at the end of 15)
The story of low learning costs for Python
Image processing? The story of starting Python for
This is the only basic review of Python ~ 1 ~
This is the only basic review of Python ~ 2 ~
Code for checking the operation of Python Matplotlib
This is the only basic review of Python ~ 3 ~
Basic story of inheritance in Python (for beginners)
Build API server for checking the operation of front implementation with python3 and Flask
the zen of Python
Summary of the basic flow of machine learning with Python
Basic knowledge of Python
Impressions of taking the Python 3 Engineer Certification Basic Exam
[Introduction to Python] Basic usage of the library matplotlib
Check the operation of Python for .NET in each environment
I wrote the basic grammar of Python with Jupyter Lab
[Note] List of basic commands for building python / conda environment
Consideration for Python decorators of the type that passes variables
(For myself) Flask_6 (Open db from python, Mysql basic (phpMyAdmin))
[Python] The biggest weakness / disadvantage of Google Colaboratory [For beginners]
Google search for the last line of the file in Python
Towards the retirement of Python2
About the ease of Python
Basic Python grammar for beginners
Basic usage of Python f-string
About the features of Python
The Power of Pandas: Python
A memorandum of understanding for the Python package management tool ez_setup
A pharmaceutical company researcher summarized the basic description rules of Python
How to change the log level of Azure SDK for Python
Wrap (part of) the AtCoder Library in Cython for use in Python
How to know the internal structure of an object in Python
The story of making a standard driver for db with python.
[Talking about the drawing structure of plotly] Dynamic visualization with plotly [python]
Practical edition of automating the testing of Flutter apps with Appium (Python)
python note: map -do the same for each element of the list
A memorandum regarding the acquisition of the Python3 engineer certification basic exam
The story of Python and the story of NaN
[Python] The stumbling block of import
First Python 3 ~ The beginning of repetition ~
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Next, use Python (Flask) for Heroku!
Change the Python version of Homebrew
About the basic type of Go
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
Basic grammar of Python3 system (dictionary)
See python for the first time
What is the python underscore (_) for?
Introductory table of contents for python3
[Python] Read the Flask source code
Record of Python introduction for newcomers
About the basics list of Python basics
Command for the current directory Python
Basic study of OpenCV with Python
Learn the basics of Python ① Beginners
Comparing the basic grammar of Python and Go in an easy-to-understand manner