Website development from scratch: form management platform based on flash and jquery

Time:2021-3-9

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

[write in front]

Do you want to develop a website? Yeah..

Do you know flask? What, I haven’t heard of…

Do you know jQuery? Is it a python library?

What would you do? I’ll open the website with F12

OK, let’s write a simple form management platform.

Based on the flash framework and jQuery to realize the development function of the management platform website, I spent 2 days to write the code from scratch; and I sorted out and summarized the specific implementation process intermittently for nearly half a month. In terms of self feeling, I am very satisfied with the realization of the whole process and results.

[the results are as follows]

Website development from scratch: form management platform based on flash and jquery

[step 1] understand the flash framework

1. Understand the mainstream web framework of Python

(1)Django:In short, it is a heavy weapon. It is the most versatile development framework. It has all the functions you want, but it is heavy and suitable for enterprise web development;

(2)Flask:It belongs to web development micro framework, small and flexible, and has rich related third-party libraries, which is suitable for developing small web;

(3)Tornado:It is inherently asynchronous and has strong performance, but the framework provides few functions and needs to be implemented by developers themselves;

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

2. Understanding the flash framework

(1) HelloWorld implementation:

Almost all programming is based on “Hello world”, so let’s talk about the content of Hello world.

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

app.run()

First declare the object of a flag framework, and then define the route ‘/’, that is, the URL address ishttp://127.0.0.1:5000/If the path is defined as’ / new ‘, the corresponding access address needs to be changed to’ / new ‘http://127.0.0.1:5000/new. In [email protected] app.route It’s a decorator.

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

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

Through the app.run The parameter definition of () method implements debugging function, and the access URL is changed tohttp://x.x.x.x:1234

The debugging function here is very easy to use. It can not only help developers reload the web page, but also print detailed error information to help locate it.

Website development from scratch: form management platform based on flash and jquery

(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 render_ Template library, and when the function returns, change it to the corresponding method.

But here we have to pay attention, test.html It must be saved in the project directory and the template file, otherwise an error will be reported. (this is because of render_ When defining the template method, the template path is written by default.)

[step 2] understand SQLite3 database

Web data interaction is inseparable from the management of background database. This chapter focuses on the SQLite3 database of Python. Compared with other “regular” databases, such as Mongo, Solr, mysql, etc., SQLite3 is quite simple and lightweight.

1. Installation and creation of SQLite3 database

With PIP command, you can download and install SQLite3 database

To create a database:

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

If there is a database material.db If there is no such database, create the database first and then connect;

2. Create data table

Label = [‘id ‘,’ network IP ‘,’ address’, ‘responsible person’, ‘contact information’]
Content = [‘1 ‘,’10.10.10.10’,’hangzhou Binjiang ‘,’pengge’,’123456 ‘]
def 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

The simple description is: create table table name (each field name 1, each field name 2 )

Currently, there are no restrictions on the input type and length of the fields in the data table. For example, if the rule ID is required, and it is plastic, and the length is within 10 bytes, it needs to be modified to

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

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

Note: during execution cur.execute Remember after () con.commit () submit the database, otherwise the data will not be written into 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

The simple description is: insert into table name (each field name 1, each field name 2 )Values (1, 2,…) )

Note here that “{7}” has double quotation marks. Why? Because “{7}” corresponds to the network IP and is a string, 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)

The simple description is: select XX, XX from table name, where field name 1 = “value 1”

5. Update data: update table name set field name 1 = value 1 “where field name 2 = value 2”

6. Delete a piece of data: delete from table name where field name 1 = value 1

[supplement]

If a DB database is generated, how to view it? You can download a SQLite expert, open it, you can view the database intuitively, and you can add, delete, modify and query the data table through the graphical button.

Step 3: understand HTML

1. Flash framework method writing

We have talked about how to call the HTML template by flash, so we will show the code of the flash framework method corresponding to the figure above

Coding = UTF-8 # @ Author: “pengge thief excellent” # @ date: September 23, 2019 # @ software: pychar from flash import flash, render_ template

import sqlite3
app = Flask(__name__)
con = sqlite3.connect(‘material.db’,check_same_thread=False)
@app.route(‘/’)
def Material_Mangement():

#Get database material_ Contents of table
cur = con.cursor()
sql = 'select * from {0}'.format("material_table")
cur.execute(sql)
content = cur.fetchall()
#Gets the header of the database table
labels = [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 operation, debugging mode settings, these knowledge please refer to the previous blog. But there are two points of knowledge that I would like to mention again:

(1) If you do not add check when connecting to the database_ same_ Thread = false parameter, then

Database connection will report an 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 accessed by multiple threads, resulting in conflicts, so here we should pay attention to the following.

(2) Get database header: labels = [tuple [0] for tuple in cur.description ]

2. HTML file (only show the table content)

<!doctype html>
<html>
<head>

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- 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

</head>
<body>
<div>

<div class="col-md-6 col-sm-12 col-xs-12">
    <div class="panel panel-default">
        <div>
            <h3>Form management platform</h3>
        </div>
        <div>
            <div>
                <table class="table table-striped table-bordered table-hover">
                    <thead>
                    <tr> {% for i in labels %} <td>{{ i }}</td> {% endfor %} </tr>
                    </thead>
                    <tbody> {% for i in content %} <tr> {% for j in i %} <td>{{ j }}</td> {% endfor %} </tr> {% endfor %} </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

</div>
<!– Optional JavaScript –>
<!– jQuery first, then Popper.js, then Bootstrap JS –>
<script integrity=”sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo” crossorigin=”anonymous”></script>
<script integrity=”sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49″ crossorigin=”anonymous”></script>
<script integrity=”sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy” crossorigin=”anonymous”></script>
</body>
</html>

The corresponding effect is as follows:

Because when I first contacted flash, I only debugged HTML, but I didn’t know how to write HTML at all. Therefore, the above code is a reference to the code of the great God(https://blog.csdn.net/a199904…)。

Familiar with this code, I think there are a few pieces of content and I want to achieve the code.

(1) Title Title Modification

(2) Length and width of the table: < div class = “col-md-6 col-sm-12 col-xs-12” >. col-xs-And col SM-And col MD – * (Col XS means super small screen, col MD medium screen, col SM small screen) are mainly used to adapt to the table display of different screens. Therefore, it is necessary to adjust the corresponding value adaptively.

(3) Set the ID of the table: < table class = table striped table bordered table hover “, id = test” >. In fact, it’s OK not to set the ID here, but when I want to edit the table later, adding the ID will facilitate me to locate the table. The method is: tab= document.getElementById (“test”)

3. HTML file (add edit, submit button)

According to the above points to be modified, I modified the HTML content again. The new HTML code is as follows:

<!doctype html>
<html>
<head>

<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- 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 > form management platform

</head>
<body>
<div>

<div class="col-md-12 col-sm-12 col-xs-12">
    <div class="panel panel-default">
        <div>
            <h3>Form management platform</h3>
        </div>
        <div>
            <div>
                <table class="table table-striped table-bordered table-hover">
                    <thead>
                    <tr> {% for i in labels %} <td>{{ i }}</td> {% endfor %} </tr>
                    </thead>
                    < tbody > {% for I in content%} < tr > {% for J in I%} < td > {J}} < / td > {% end for%} < td > < input type = "button" value = "Edit" ></td>
                            <td>< input type = submit "value = submit" ></td>
                        </tr> {% endfor %} </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

</div>
<!– Optional JavaScript –>
<!– jQuery first, then Popper.js, then Bootstrap JS –>
<script integrity=”sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo” crossorigin=”anonymous”></script>
<script integrity=”sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49″ crossorigin=”anonymous”></script>
<script integrity=”sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy” crossorigin=”anonymous”></script>
<script> (function(){

$('input[type="button"]').on('click', function(){ var $this = $(this),
      edit_status = $this.attr('edit_status'),
      status_value = edit_status && 1 == edit_status ? 0 : 1,
      $td_arr = $this.parent().prevAll('td');
    $ this.val (1 == status_ Value?'finish ':'edit').Attr ('edit ')_ status', status_ value);
    $.each($td_arr, function(){ var $td = $(this); if(1 == status_value) {
        $td.html('<input type="text" value="'+$td.html()+'">');
      } else if(0 == status_value){
        $td.html($td.find('input[type=text]').val());
      }
    });
  });
})(); </script>

</body>
</html>

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

(1) Add edit and submit button:

<td>< input type = button “value = Edit > < / td > < td > < input type = submit” value = submit “></td>

Put these two lines of code at the end of each line of the table, and the corresponding button will be generated

(2) The realization of editing function is as follows

The function corresponding to the Edit button is written based on jQuery,

Of course, I also refer to another great God for this code(https://blog.csdn.net/luo2012…)Because I know nothing about jQuery right now.

But after getting familiar with the code, I annotated it based on my understanding of the code.

< script > (function() {<! — defines the button that belongs to button. After clicking, the following function is generated — > $(‘input [type = “button”]). On (‘click ‘, function() {<! — gets the current event and performs the status of the current button. If it is in editing status, it performs the following function — > $(‘input [type = “button”])

var $this = $(this),
      edit_status = $this.attr('edit_status'),
      status_value = edit_status && 1 == edit_status ? 0 : 1,
      $td_arr = $this.parent().prevAll('td');
    $ this.val (1 == status_ Value?'finish ':'edit').Attr ('edit ')_ status', status_ Value); <! -- if the cell is in the editing state, get the value of each column element, and display it on the final HTML table -- > $. Each ($TD)_ arr, function(){ var $td = $(this); if(1 == status_ value) {
        $ td.html ('<input type="text" value="'+$ td.html () + '">'; <! -- if the button status is complete, the value in the cell will be displayed directly -- >} else if (0 = = status_ value){
        $td.html($td.find('input[type=text]').val());
      }
    });
  });
})(); </script>

Careful students will find that when I click the “submit” button, nothing happened. Yes, the “submit” function, which I’ll cover in the next chapter.

Step 4: learn about jquery

1. For me, the most difficult part is the transmission of foreground data by HTML. Therefore, I refer to the editing function and write a little bit by myself. Here is the sample code:

(1) HTML file writing foreground interface submission function

< script > (function() {<! — define the button whose attribute is submit. After clicking, the following function — > $(‘input [type = “submit”] ‘). On (‘click’, function() {<! — get the ID of the current line — >)

var td =  event.srcElement.parentElement ; var rownum =  td.parentElement.rowIndex ; <! -- get HTML table elements -- >
            var tab =  document.getElementById ("test"); <! -- take the value of each cell element and pass it to the background in the form of Dictionary -- >
            var data = { "ID": tab.rows [rownum]. Cells [0]. InnerHTML, "network IP": tab.rows [rownum]. Cells [1]. InnerHTML, "address": tab.rows [rownum]. Cells [2]. InnerHTML, "responsible person": tab.rows [rownum]. Cells [3]. InnerHTML, "contact information": tab.rows [rownum].cells[4].innerHTML,
            };
            Alert ("submitted successfully! ")
            $.ajax({
                type: "get",
                url: "/edit",
                data: data,
                dataType: "json" });
    });
    })();

(2) The background reads the submitted data and writes it to the database

@app.route(‘/edit’, methods=[‘get’])
def edit():

Label = ['id ',' network IP ',' address', 'responsible person', 'contact information']
content = [request.args.get(i) for i in label]
print(content)
sql = 'update {0} set {1}="{6}",{2}="{7}",{3}="{8}",{4}="{9}" where {5}={10}'.format('material_table',
      label[1], label[2], label[3],label[4],label[0],content[1],content[2],content[3],content[4],content[0])
cur = con.cursor()
cur.execute(sql)
con.commit () return "data written successfully! "

When implementing the “submit” function, I mainly encountered the following problems:

(1) After the HTML code is written, the program reports an error and prompts $. AJAX is not a function. I’ll go. I see the data interaction of other gods is also written like this. Why can’t I do this?

Looking at the online posts, they all said that they were undefined or in conflict with other libraries. Finally, I found out that it was because I didn’t declare that it was jQuery. You need to add a line of code before the script:

<script></script>

I understand the meaning of this line of code is to declare the jQuery library, not other JS libraries. (may be misunderstood)

Finally, after adding this line of code, the problem is solved successfully!

(2) Get the current line number

At the beginning, I was unable to get the line number, and I didn’t know how to debug it. Under the guidance of my colleagues, I learned to pass alert( td.innerHTML )To see what the current row content is.

The first way to get the current line from the Internet is as follows:

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

Through alert debugging, it is found that click Submit has no response at all

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

As a result, nothing is available

Just such a small problem took me nearly 2 hours to keep looking up information and trying to write. Finally, I want to say that if you are not familiar with HTML, you should find a God to bring your own.

Finally, with the help of others, the function of obtaining the current line is realized

(3) Get the contents of each table

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

When I get the data in the cell, the most important thing is that I can’t get the tab, which is the table element. Because I didn’t add ID in the table element

I found a lot of methods on the Internet, but they couldn’t be realized. Finally, I honestly added id = “test”

To be reasonable, these 20 lines of code in HTML are the most energy I spent on this table management platform. So far, the functions of the form management platform are basically in line!

[step 5] add new functions

The above functions only realize the function of editing and saving existing data, but what if users want to add new data? My first idea at that time was to let users change the database themselves, ha ha. I have to write new functions. I’m so tired that I don’t want to write them.

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

1. How to add a new button

<td>< input type = button “value = add” id = create “></td>

If the previous HTML can be understood, this line is not difficult to understand.

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

<script> (function () {

    $('input[id="create"]').on('click', function(){ var editTable=document.getElementById("tbody"); var tr=document.createElement("tr"); var td1=document.createElement("td");
        td1.innerHTML="";

        tr.appendChild(td1);
        editTable.appendChild(tr);

First, the TR element is defined, and then the TD element is added to the TR element. If there are multiple columns of data in the table, you only need to repeat the writing method of TD1 and copy and paste it.

In addition, the current td.innerTHML If you want to set the cell to edit status directly, change it to:

td1.innerHTML=”input[type=text] /”;

3. How to dynamically add “Edit” and “submit” buttons, take “Edit” as an example

var td9 = document.createElement(“td”) var myedit =document.createElement(“input”);
myedit.type = “button”;
myedit.value =”Edit” myedit.id = “edit” td9.appendChild(myedit)

The method of adding is the same as that of adding text box, except that the element type is input, and the type / value / ID of the next element should be added.

4. How to bind events to dynamically added buttons, take the submit function as an example

$(‘input[id=”submit”]’).on(‘click’, function(){

alert("test")

}

There are many posts about dynamically added buttons for event binding. They use the live method and the $(document). On (‘click ‘,’. Edit ‘, function() method. In fact, they don’t have to be so troublesome. They are exactly the same as the normal “submit” writing method.

5. Get the data in the current new row and submit it.

var tab = document.getElementById(“test”); var rownum = td1.parentElement.rowIndex;

$('input[id="submit"]').on('click', function(){ var data = { "ID":tab.rows[rownum].cells[0].innerHTML,
        };
        Alert ("add successfully! ")
        $.ajax({
                type: "get",
                url: "/create",
                data: data,
                dataType: "json" });
        });

This code and the implementation of the submit function are the same, much the same.

This article is from Huawei cloud community, written by Peng Ge.

Click follow to learn about Huawei’s new cloud technology for the first time~