【 abstract 】

In the Web Framework preludes, we looked at Flask and Django in their respective scenarios, and concluded that we preferred to use Flask, so the rest of the series will focus on Flask.

Interpretation of the style is still continue, of course, we have been adhering to the thought, that is from the scene, the first is an urgent need to use that part of the learning, use less than the first not to learn, also recently built a new term for minimizing the overhand Range (Minimize Range), means to complete a requirements needed to Minimize the scope of knowledge.

Flask’s presentation begins now

“Flask”

Flask, as a lightweight Web framework, takes advantage of its “light” quality. We quickly integrate it with the previous CMDB topics, and instead of adding, deleting, modifying and querying data sources through command lines, we do operations through API requests.

Start the Flask

It only takes a few lines (literally) to start Flask’s code, as follows:

# app.py
from flask import Flask

app = Flask(__name__)

if __name__ == "__main__":
    app.run()
Copy the code

After installing Flask’s third-party packages in the environment, usually by executing PIP Install Flask, you can start the Flask project by typing Python app.py on the command line.

The output after startup is as follows:

There are six lines of output that cover five points, but only the last two are covered here, and the others will be covered in the extras and subsequent chapters (because they won’t be needed at the moment).

The Running on http://127.0.0.1:5000/ line indicates that the Flask application is now listening locally on 127.0.0.1 and port 5000

The app.run() function takes host and port as the first two arguments, and defaults to 127.0.0.1 and 5000 when they are not passed

You can now access the url from your browser, but when you open your browser and type in the url above, it looks like this:

Not Found Is a 404 error in the HTTP status code, indicating that the accessed link resource does Not exist. This is because we just started a back-end application and listened on a socket without defining any routing functions.

2. Add routes

Now add some code as follows:

# app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index() :
    return "hello world"

if __name__ == "__main__":
    app.run(debug=True)
Copy the code

Normally, you need to stop the program and restart it after making changes, but by passing in the debug parameter, you can save the code and load it dynamically for the changes to take effect directly.

The page is refreshed as follows:

The @app.route(“/”) is a Python decorator syntax, which will be explained in a later tutorial. For the moment, you need to know that adding a line of @app.route to a normal function registers it in the Flask into a route. App.route (“/”) passes the Path of the URL without the IP and port number. Flask routing can be interpreted as a dictionary, which stores the functions corresponding to Path, so that when accessing Flask back-end applications through urls, you can find the corresponding functions to call, and then return data.

Third, combine CMDB

Now, put the previous CMDB code cmdb.py and data file data.json in the same directory as app.py, and follow the second step to add several routes corresponding to CDMB.

First add a function to cmdb.py that will enable Flask to call the CMDB instance objects, as shown below

# cmdb.py
def cmdb_handler() :
    try:
        file_store = Store("file"."data.json")  # instantiate a file storage object
        cmdb = CMDB(file_store)  The incoming read data source instantiates a CMDB object
        return cmdb
    except Exception as e:
        raise Exception("get cmdb handler failed, err: %s" % str(e))
Copy the code

Import the function that creates the CMDB instance object in app.py

# app.py
from flask import Flask
from cmdb import cmdb_handler

CMDB = cmdb_handler()

app = Flask(__name__)

@app.route("/")
def index() :
    return "hello world"
  
  
@app.route("/get")
def get() :
    "" "query CMDB "" "
    ret = CMDB_HANDLER.execute("get", path)
    return ret
  
  
@app.route("/init", methods=["POST"])
def init() :
    """ Initialize region """
    ret = CMDB_HANDLER.execute("get", region)
    return ret

  
@app.route("/add", methods=["POST"])
def add() :
    """ Add information """
    ret = CMDB_HANDLER.execute("get", path, attr)
    return ret
  
  
@app.route("/update", methods=["POST"])
def update() :
    """ Modify the message """
    ret = CMDB_HANDLER.execute("get", path, attr)
    return ret
  

@app.route("/delete", methods=["POST"])
def delete() :
    """ Delete message """
    ret = CMDB_HANDLER.execute("get", path, attr)
    return ret
  
if __name__ == "__main__":
    app.run(debug=True)
Copy the code

Route (“/init”, methods=[“POST”]). The route decorator can pass in another parameter, methods, which limits how HTTP requests can be made. Methods =[“POST”] Indicates that the URL receives only POST requests. If this parameter is not sent, the GET method is allowed by default.

The default browser initiates a GET request to access the URL. If the request initiation mode does not match the mode allowed by the back-end route, the following symptom occurs

Tips

It should be noted here that different frameworks handle restrictions on request methods differently.

In the Flask, as long as the URL of the request is the same as the name of the route definition, the match succeeds. After the match, the Flask verifies the Method of the request to determine whether the request mode is consistent with the receiving mode Allowed by the route. If the request mode is inconsistent, Method Not Allowed is returned.

However, other frameworks, such as Golang’s Web framework, combine the name of the route with the type of request it is allowed to receive and compare it with the received HTTP request. If they do Not match, a 404 Not Found error is reported.

That is, Flask uniquely defines a route by name, whereas other frameworks uniquely define a route by name and Method.

4. Receiving parameters

The Flask application does not define the parameters that you need to pass in to invoke the CMDB function

1.GET Request parameters

The code for the CMDB query function is as follows:

@app.route("/get")
def get() :
    "" "query CMDB "" "
    ret = CMDB_HANDLER.execute("get", path)
    return ret
Copy the code

Since this is an HTTP request, the path parameter in the above code needs to be obtained from an HTTP request. Here is a GET request

http://ip:port/path?key1=value1&key2=value2
Copy the code

The HTTP request parameters are processed by the Flask framework and stored in Request. args, which is a dictionary, so the code can be modified as follows:

from flask import Flask, request

@app.route("/get")
def get() :
    "" "query CMDB "" "
    path = request.args.get("path"."/")  # if path is not passed, path defaults to /
    ret = CMDB_HANDLER.execute("get", path)
    return ret
Copy the code
2.POST request parameters

The code for adding data to the CMDB is as follows:

@app.route("/add", methods=["POST"])
def add() :
    """ Add information """
    ret = CMDB_HANDLER.execute("get", path, attr)
    return ret
Copy the code

As you can see from the code above, this route is only allowed to receive POST requests. There is no clear distinction, or indeed no distinction, between GET requests, or POST requests that must be made, and anything can be done through GET requests, which we’ll explain in more detail in the extras.

However, because when adding information in CMDB, the content that needs to be passed in is JSON string, there are escape problems and readability problems in the parameters of GET request, so we use POST request to deal with.

There are many types of parameters that can be accepted in a POST request. The types are defined by the Content-Type field of HTTP request Headers. The common types are Application/JSON or Application/X-www-form-urlencoded. Let’s use the latter for the moment and modify the code as follows:

from flask import Flask, request

@app.route("/add")
def add() :
    """ Add information """
    path = request.form.get("path")
    attr = request.form.get("attr")
    ret = CMDB_HANDLER.execute("add", path, attr)
    return ret
Copy the code

【 summary 】

This chapter mainly introduces the following contents:

1. The start of the Flask

2. Definition of routing functions

3. Obtain HTTP parameters

4. The combination of Web applications and CMDB

This is just the tip of the Flask iceberg, and we’ll be looking for further improvements to the code in the next chapter.

【 原 文 】

As you can see, we only applied Flask’s extremely limited knowledge, and did not apply it to a particularly complex project architecture, and some of the knowledge was not deeply explored. In fact, many requirements could be fulfilled, which is the minimum scope of operation I mentioned at the beginning. This is also very much in line with the philosophy of programming: don’t over-design, don’t refactor early.

Flask has a lot of official documentation and a lot of well-explained books. I personally agree that I can systematically learn a certain technology. However, people often ask me why I still can’t write code after reading a lot of books on Zhihu. In fact, this is also a problem that most friends with less programming experience will encounter: they know too much.

Know too much

“Knowing” and “knowing more” are in quotation marks, because knowing more is a good thing, and knowing more is a good thing.

But the problem is that some friends for a lot of knowledge didn’t really understand, also creates the illusion of more, because indeed also see a lot of, before this goes to me in Python and automated transport reform hand village 】 【 object-oriented language – 3 after the article mentioned: instruction and inductive learning, haven’t seen friends can go to see some links.

Reading knowledge explanation in books or documents essentially belongs to instruction learning, and what is learned is knowledge points. However, learning programming is a kind of inductive learning, which requires continuous application of knowledge points learned to repeatedly verify that the knowledge points are practical from multiple angles. Finally, it can be called “learning it”.

So some friends will have a feeling after reading the book, SO many knowledge points I know, but I still can’t write code, work needs or can’t start, the fundamental reason is knowledge points in the brain piled up too much, but can’t digest; In more general terms, it means taking too big a step.

So in order to avoid from entry to give up, I hope you remember that slow is fast.


Welcome to add my personal public account [Python Playing automated Operation and Maintenance] to the reader exchange group, to get more dry content