Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Table Management platform based on Flask and JQuery

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "based on Flask and JQuery how to achieve table management platform", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "based on Flask and JQuery how to achieve table management platform" bar!

[the effect is as follows]

[first step] understand the Flask framework 1. Understand the mainstream web framework of python

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

(2) Flask: belongs to the web development micro-framework, small and flexible, rich in related third-party libraries, suitable for the development of 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 of this paper is mainly based on Flask.

2. Understand the Flask framework (1) HelloWorld implementation:

Almost all programming is based on "helloworld", so give a general account of what helloworld involves.

From flask import Flaskapp = Flask (_ _ name__) @ app.route ('/') def hello_world (): return "Hello world!" if _ _ name__ = ='_ main__': app.run ()

First declare an object of the Flask framework, and then define the route'/', that is, the URL address is http://127.0.0.1:5000/; if the path is defined as'/ new', the corresponding access address needs to be changed to http://127.0.0.1:5000/new. In addition, @ app.route is a decorator.

(2) how to access a specific IP address or port? App.run (debug=True,host= "x.x.x.x", port= "1234")

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

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

(3) how to display your specific html template from flask import Flask,render_templateapp = Flask (_ _ name__) @ app.route ('/') def hello_world (): return render_template ('test.html') if _ _ name__ = =' _ main__': app.run () on web

You just need to import the render_ template library and change it to the corresponding method when the function returns.

However, it should be noted that the test.html must be saved in the project directory and under the template file, otherwise an error will be reported. (this is because the template path is written by default when the render_template method is defined)

[step 2] learn about Sqlite3 database

Web data interaction is inseparable from the management of the background database. This chapter focuses on explaining the sqlite3 database that comes with python. Compared with other "regular" databases, such as mongo, solr, MySQL, etc., sqlite3 is quite simple and belongs to lightweight databases.

1. Installation and creation of sqlite3 database

Use the pip command to download and install the sqlite3 database

Create the database:

Con = sqlite3.connect ('material.db')

If there is a database material.db, connect to the database; if there is no such database, create the database before connecting

2. Create a data table

Label = ['ID',' network IP',' address', 'responsible person', 'contact information'] content = ['1Zhe 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

A brief 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 is shaping, and the length is less than 10 bytes, it needs to be modified to

Sql = 'create table matrial_table ("ID" int [10] primary key not null)'

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

Note: after executing cur.execute (), remember that con.commit () commits 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

A brief description is: insert into table name (each field name 1, each field name 2...) Values (numeric value 1, numeric value 2.)

It should be noted that "{7}" has double quotation marks. Why? Because "{7}" corresponds to the network IP, which is a string, you need to put double quotation marks, otherwise an error will be reported.

4. Query data def query (): sql = 'select * from {0}' .format (tablename) result = cur.execute (sql) return list (result)

It is simply described as: select XX,XX from table name where field name 1 = "numeric 1"

5. Update data: update table name set field name 1 = "numeric 1" where field name 2 = "numeric 2" 6, delete a piece of data: delete from table name where field name 1 = "numeric 1" [supplement]

If a db database is generated, how can I 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] learn about html

1. Flask framework method programming

I've already talked about how Flask calls the html template, so let's directly show the code of the flask framework method corresponding to the figure above.

# coding=utf-8# @ Auther: "Pengge thieves are excellent" # @ Date: 2019 Universe @ Software: PyCharmfrom flask import Flask,render_templateimport sqlite3app = Flask (_ _ name__) con = sqlite3.connect ('material.db') Check_same_thread=False) @ app.route ('/') def Material_Mangement (): # get the contents of the database material_table table cur = con.cursor () sql = 'select * from {0}' .format ("material_table") cur.execute (sql) content= cur.fetchall () # get the header labels 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, debug mode settings, please refer to the previous blog. However, there are two points of knowledge that I would like to mention again:

(1) if the check_same_thread=False parameter is not added when connecting to the database, the

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 due to conflicts caused by multithreaded access to the sqlite3 database, so note here.

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

2. Html file (only show the contents of the table)

Material management platform form management platform {% for i in labels%} {I}} {% endfor%} {% for i in content%} {% for j in i {{j}} {% endfor%} {% endfor%}

The corresponding effect is as follows:

Because when I first came into contact with flask, I only debugged html, but I never specifically touched how to write html at all. Therefore, the above code is a reference to the Great God's code (https://blog.csdn.net/a19990412/article/details/84955802).

After getting familiar with this code, I feel that there are several pieces of content related to the code I want to implement.

(1) title title modification

(2) the 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 value needs to be adjusted adaptively.

(3) set the ID: of the table. In fact, it is OK not to set id here, but when I want to edit the table later, adding id will make it convenient for me to locate the table. The method is: tab = document.getElementById ("test")

3. Html file (add edit, submit button)

Based on the points to be modified above, I re-modified the html content, and the new html code is as follows:

Form management platform {% for i in labels%} {I}} {% endfor%} {% for i in content%} {% for j in i {{j}} {% endfor%} {% endfor%} (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? 'done': 'edit'). Attr ('edit_status', status_value); $.each ($td_arr, function () {var $td = $(this); if (1 = = status_value) {$td.html (');} else if (0 = = status_value) {$td.html ($td.find ('input [type = text]'). Val ()) }});})

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

(1) add edit and submit buttons:

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

(2) the realization of editing function:

The function corresponding to the edit button is based on JQuery

Of course, I also refer to another great god's (https://blog.csdn.net/luo201227/article/details/50559988) for this code, because currently I know nothing about JQuery.

But after getting familiar with the code, I commented on my own understanding of the code.

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? 'done': 'edit'). Attr ('edit_status', status_value); $.each ($td_arr, function () {var $td = $(this); if (1 = = status_value) {$td.html ('') } else if (0 = = status_value) {$td.html ($td.find ('input [type = text]') .val ();}});});}) ()

Careful classmates will find that nothing happened when I clicked the "submit" button. Yes, the "submit" function, which I will introduce in the next chapter.

[step 4] learn about JQuery

1, the implementation of the submission function, for me, the most difficult thing is the transmission of html to the foreground data. Therefore, I refer to the editing function and write a little bit by myself. The following is the sample code:

(1) HTML document writing foreground interface submission function

(function () {$('input [type = "submit"]'). On ('click', function () {var td = event.srcElement.parentElement; var rownum = td.parentElement.rowIndex; var tab = document.getElementById ("test") Var data = {"ID": tab.rows [rownum] .cells [0] [xss_clean], "network IP": tab.rows[ rownum] .cells [1] [xss_clean], "address": tab.rows [rownum] .cells [2] [xss_clean] Responsible person: tab.rows [rownum] .cells [3] [xss_clean], "contact information": tab.rows [rownum] .cells [4] [xss_clean],} Alert ("submitted successfully!") $.ajax ({type: "get", url: "/ edit", data: data, dataType: "json"});}) ()

(2) the background reads the submitted data and writes 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 pitfalls:

(1) after the html code is written, it finds that the program reports an error and prompts $.ajax is not a function. I'll go. I think the data interaction of other gods is also written in the same way. why can't I do this?

Checking online posts, they all said that they were undefined or in conflict with other libraries, and finally I found out that it was because I did not declare it to be JQuery. You need to add a line of code before script:

I understand that this line of code means to declare that you want JQuery libraries, not other JS libraries. (may be misunderstood)

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

(2) get the current line number

At first, I couldn't get the line number, and I didn't know how to debug it. Under the guidance of my colleagues, I learned to use alert (td [XSS _ clean]) to see what the current line content is.

The 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 there is no response at all when you click submit; change it to

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

The result is that you can't get anything.

It took me nearly 2 hours to keep looking up the information and trying to write it. The last thing I want to say is that if you are not familiar with html, you should find a big god to take your own.

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

(3) get the contents of each table

Tab.rows [0] .cells [0] [xss_clean]

When getting the data in the cell, the most verified thing is that I can't get the tab, that is, the table element. Because I didn't add id to the table element before, that is,

Found a lot of methods on the Internet can not be achieved, and finally honestly add id= "test"

To be reasonable, these 20 lines of code in html are the ones that I spent the most energy on this table management platform. At this point, the function of the form management platform is basically completed!

[step 5] add new features

The above functions only implement 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, . I am also asked to write new features. I am so tired that I don't want to write them.

The following is an introduction to the new features and sample code.

1. How to add the "add" button

If the previous html can understand, this line is not difficult to understand.

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

(function () {$('input [id = "create"]'). On ('click', function () {var editTable=document.getElementById ("tbody"); var tr=document.createElement ("tr"); var td1=document.createElement ("td"); TD1 [XSS _ clean] = "; tr.appendChild (td1); editTable.appendChild (tr)

First define the tr element, and then append the td element to the tr element. If there are multiple columns of data in the table, just repeat the td1 and copy and paste it.

In addition, the current td.innerTHML is set to empty, so if you want to set the cell directly to the editing state, modify it to:

TD1 [XSS _ clean] = "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)

It is added in the same way as a text box, except that you need to note that the element type is Input and add the type/value/id of the following elements.

4. How to bind a dynamically added button to an event. 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, some using Live method, some using $_ (document) .on ('click','.edit',function () method), actually not so troublesome, and the normal "submit" method is exactly the same.

5. Get the data in the 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] [xss_clean],}; alert ("New success!") .ajax ({type: "get", url: "/ create", data: data, dataType: "json"});})

This code is the same as the implementation of the commit function, more or less the same.

Thank you for your reading, the above is the content of "how to achieve the form management platform based on Flask and JQuery". After the study of this article, I believe you have a deeper understanding of how to achieve the form management platform based on Flask and JQuery, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report