Abstract: This paper will bring you the development function of the management platform website based on Flask framework and JQuery.

【 Write in front 】

You want to develop a website? B: well..

Flask? What is it? I never heard of it…

Will the JQuery? Is it a Python library?

What can you do? I will open the website F12

Okay, so let’s write a simple form management platform.

Based on Flask framework and JQuery to achieve the development function of the management platform website, IT took me 2 days to write the code from scratch. And to the specific implementation process, I have sorted out and summarized nearly half a month. As far as I am concerned, I am very satisfied with the whole process and the result.

[The effect is as follows]

Step 1: Understand the Flask framework

1. Understand the mainstream Web framework for Python

(1) Django: Simply put, Django is a heavy weapon. It is the most versatile development framework with everything you need. But more onerous, suitable for enterprise-level Web development;

(2) Flask: It is a Web development micro-framework, small and flexible, rich third-party libraries, suitable for developing small Web;

(3) Tornado: It is naturally asynchronous and has strong performance, but the framework provides few functions and requires developers to implement it by themselves;

Therefore, the code implementation in this paper is mainly implemented based on Flask.

2. Know the Flask framework

(1) HelloWorld implementation

Almost all of the programming is based on “Hello World,” so here’s a quick overview of what HelloWorld involves.

from flask import Flask app = Flask(name) @app.route(‘/’) def hello_world(): return “Hello world!” if name == ‘main‘: app.run()

Declare a Flask framework object and then define the route ‘/’, i.e. the URL is http://127.0.0.1:5000/; If defined path for ‘/ new’, the corresponding access address need to change to http://127.0.0.1:5000/new. Also, @app.route is a decorator.

(2) How to achieve specific IP address or port access?

app.run(debug=True,host=”x.x.x.x”,port=”1234″)

Through the parameter definition of app.run() method, the debugging function is realized respectively, and the access URL is changed to http://x.x.x.x:1234

Here the debugging function is very useful, not only to help developers reload the web page, but also to print detailed error information to help locate.

(3) How to display your own specific HTML template on the Web

from flask import Flask,render_template app = Flask(name) @app.route(‘/’) def hello_world(): return render_template(‘test.html’) if name == ‘main‘: app.run()

Just import the render_template library and change to the corresponding method when the function returns.

Test.html must be saved in the project directory and in the template file, otherwise an error will be reported. (This is because the render_template method is defined with the template path written by default)

Step 2: Understand the Sqlite3 database

Web data interaction is inseparable from the management of the background database. This section focuses on python’s own SQlite3 database. Compared to other “formal” databases such as Mongo, Solr, MySQL, etc., SQlite3 is relatively simple and lightweight.

1. Installation and creation of SQlite3 database

The SQlite3 database can be downloaded and installed using the PIP command

Create database:

con = sqlite3.connect(‘material.db’)

If there is a database material. Db, connect to the database. If the database does not exist, create the database first and then connect.

2, create table

Label = [‘ ID ‘, ‘network IP’, ‘address’ and ‘responsible’, ‘contact’] content = [‘ 1 ‘, ‘10.10.10.10’, ‘hangzhou binjiang’, ‘brother peng’, ‘123456’] def the create () : sql = ‘create table {0} ({1},{2},{3},{4},{5})’.format(tablename,label[0],label[1],label[2],label[3],label[4]) result = cur.execute(sql) con.commit() return True if result else False

Create table Table name (each field name is 1, each field name is 2…)

Currently, the input type and length of fields in the data table are not restricted. For example, if the rule ID is mandatory, the rule ID is an integer, and the rule length is less than 10 bytes, you need to change it to

sql = ‘create table matrial_table (“ID” int[10] primary key not null )’

Similarly, other fields can be limited by type and length in the same way.

Note: After cur.execute(), remember that con.mit () commits to the database, otherwise the data will not actually be written to the database.

3. Insert data

def insert(): sql = ‘insert into {0} ({1},{2},{3},{4},{5}) values({6},”{7}”,”{8}”,”{9}”,”{10}”)’.format(tablename,label[0],label[1], label[2],label[3],label[4],content[0],content[1],content[2],content[3],content[4]) result = cur.execute(sql) con.commit() return True if result else False

Insert into table name (1, 1, 2) Values (values 1, 2…)

Note that “{7}” is in double quotes, why? Because “{7}” corresponds to the network IP address, it is a string. Therefore, double quotation marks are required; otherwise, an error will be reported.

4. Query data

def query(): sql = ‘select * from {0}’.format(tablename) result = cur.execute(sql) return list(result)

Simply described as follows: the select of XX, XX from the name of the table where the field name 1 = “number one”

Update table_name set table_name =” 1 “where table_name =” 2″

Select * from table_name where table_name = 1 where table_name = 1

[supplementary]

If a DB database is generated, how do YOU view it? You can download SQLite Expert, and when you open it, you can easily view the database, and you can add, delete, change and query the data table using graphical buttons.

Step 3: Know HTML

1. Written by Flask framework method

How Flask calls HTML templates has already been explained, so let’s go straight to the code for the Flask framework method shown above

Coding = UTF-8 # @auther: “Good” # @date: 2019/9/23 # @software: PyCharm from flask import flask,render_template

import sqlite3 app = Flask(name) con = sqlite3.connect(‘material.db’,check_same_thread=False) @app.route(‘/’) def Material_Mangement(): SQL = ‘select * from {0}’. Format (“material_table”) cur.execute(SQL) content Fetchall = cur.fetchall() # Fetchall = [tuple[0] for tuple in cur.description] return render_template(‘test.html’,content=content,labels=labels) if name == ‘main’: app.run(debug=True)

Dynamic routing, SQlite3 database operations, debugging mode Settings, see previous blog posts. But there are two things I want to mention:

(1) If the check_same_thread=False parameter is not added when the database is connected

Database connection error: sqlite3. ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread ID XX.

This is because the SQlite3 database is being accessed by multiple threads causing conflicts, so be careful here.

All labels = [tuple[0] for tuple in cur.description]; all labels = [tuple[0] for tuple in cur.description];

2. Html file (show table content only)

<! -- Bootstrap CSS --> <link rel="stylesheet" Href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title> Material Management platform </title>Copy the code

Form management platform

{% for i in labels %} {% endfor %} {% for i in content %} {% for j in i %} {% endfor %} {% endfor %}

{{ i }}
{{ j }}

</div>
Copy the code

The corresponding effect looks like this:

Because when I first started flask, I only debugged HTML, but I didn’t even know how to write HTML. So the above code this code is a reference from the great god (blog.csdn.net/a19990412/a…

Once FAMILIAR with the code, I felt that there were several pieces that were relevant to the code I was implementing.

(1) Title title modification

(2) Length and width of the table:

. col-xs-
And col – sm –And COL-MD -* (COL-XS stands for ultra-small screen, COL-MD – medium screen, col-SM – small screen) are mainly used to adapt to the table display of different screens. Therefore, the corresponding values need to be adjusted adaptively.

Set the ID of the table: <table class=”table table-striped table-bordered table-hover”, ID =”test”> I don’t have to set the ID here, but if I’m going to edit the table later, I’m going to add the ID so that I can locate the table, TAB = document.getelementById (“test”)

3. Html file (add edit, submit button)

Based on the above points, I modified the HTML content again. The new HTML code is as follows:

<! -- Bootstrap CSS --> <link rel="stylesheet" Href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title> Table management platform </title>Copy the code

Form management platform

{% for i in labels %} {% endfor %} {% for i in content %} {% for j in i %} {% endfor %} {% endfor %}

{{ i }}
{{ j }}

</div>
Copy the code

Compared to the HTML file in step 2, I mainly added two pieces of content this time:

(1) Add edit and submit buttons:


Placing these two lines of code at the end of each line of the table generates the corresponding button

(2) Implementation of editing function:

Function corresponding to edit button is based on JQuery,

This code, of course, I also reference another great god (blog.csdn.net/luo201227/a…

But after I got familiar with the code, I commented it based on my own understanding of the code.

Careful students will notice that nothing happens when I click the “submit” button. Yes, the “submit” feature, which I’ll cover in the next section.

Step 4: Understand JQuery

1, the implementation of the submission function, for me, the most difficult is HTML to the front of the data transmission. Therefore, I reference the editing function, a little bit of my own writing. Here is the sample code:

(1) HTML file preparation front interface submission function

I understand that this line of code is to declare the JQuery library, not other JS libraries. (May be misunderstood)

Finally, add this line of code and the problem is solved!

(2) Get the current line number

At first, I couldn’t get the line number, and I didn’t know how to debug it. With the guidance of my colleagues, I learned to use alert(TD.innerhtml) to see what was being retrieved.

To obtain the current line:

var td = event.parentElement; var rownum = td.parentElement.rowIndex;

Through alert debugging, it is found that there is no response when clicking submit. And to

var td = event.srcElement; var rownum = td.parentElement.rowIndex;

The result is that nothing is retrieved

It took me nearly 2 hours to keep looking up information and trying to write for such a small problem. Finally, if you are not familiar with HTML, you should find someone to guide you.

Finally, with the help of others, achieve the function of obtaining the current line:

(3) Get the contents of each table

tab.rows[0].cells[0].innerHTML

When I get data in a cell, the most validation is that I can’t get a TAB, which is a table element. Because I didn’t put an ID in the table element, i.e

So I’m going to add id=”test”

To be fair, those 20 lines of HTML are the most I’ve ever spent on this form management platform. At this point, the function of the table management platform is basically complete!

[Step 5] Add new functions

The above functions only realize the function of editing and saving existing data, but what if the user wants to add new data? My first thought was to let users change the database themselves, haha. I have to write new features. I’m too tired to write.

Here is an introduction to the new features and sample code.

1. How to add “Add” button




This line should be easy to follow if the previous HTML makes sense.

2. How to dynamically add table rows and columns after clicking the “Add” button