How to use python as a backend to write web pages-flask framework

What is Flask

Flask is a lightweight web application framework written in Python . Its WSGI toolbox uses Werkzeug, and its template engine uses Jinja2. Flask uses BSD authorization. The following programs are all running on their own server ( using ssh to connect in vs code )

Install flask module

First install using pip:

pip install flask

Create a templates folder (used to store html and other files) and app.py under the project folder, as shown in the figure:
Insert picture description here

Hello World

We can create a new index.html file in the templates file, its content is as follows:

<html>
    <h1>Hello Word!</h1>
</html>

In the app.py file created in the previous step, write:

from flask import Flask, render_template, request, jsonify
#创建Flask对象app并初始化
app = Flask(__name__)

#通过python装饰器的方法定义路由地址
@app.route("/")
#定义方法 用jinjia2引擎来渲染页面,并返回一个index.html页面
def root():
    return render_template("index.html")
#定义app在8080端口运行
app.run(port=8080)

After we have written the app.py file, we press F5Run, and the terminal outputs:
Insert picture description here
We access port 8080 of the server, that is, Hello World appears in front of us!
Insert picture description here

One step further: data binding

In the previous step, we simply built a static web page, and its display only depends on the front end and is fixed. How do we pass the value from the back end and display it on the front end? This requires the use of data binding .
Data binding , as the name implies, is to achieve a "dynamic" effect. When the background data is updated, the front-end page is automatically updated; the data on the front-end page is updated, and the background data is also automatically updated. Update. In the flask framework, the backend loads the web page first, puts the incoming data in a suitable location, and then uses the jinjia2 engine to render, and finally returns the rendered page.

Back-end incoming data

We first pass the data name and age that need to be bound in the render_template function:

from flask import Flask, render_template, request, jsonify
#创建Flask对象app并初始化
app = Flask(__name__)

#通过python装饰器的方法定义路由地址
@app.route("/")
#定义方法 用jinjia2引擎来渲染页面,并返回一个index.html页面
def root():
    return render_template("index.html",name="zxy",age=21)
#定义app在8080端口运行
app.run(port=8080)

In the front-end index.html, we get the incoming data:

<html>
    <h1>我是{
   
   {name}},今年{
   
   {age}}岁</h1>
</html>

We press F5run again , and access port 8080 of the server, the page displays:
Insert picture description here

Get data from the front end

So, how does the data submitted by the front end pass to the back end?
Here, I use ajax to achieve asynchronous transmission of data. We summarize the main steps as:

1. Introduce jQuery in the front-end page
2. Create two input boxes, a button for data input and event submission.
3. Write events in js and use ajax for data submission
4. Write corresponding event handling functions in the back-end app.py

The front-end index.html content is as follows:

<html>
    <!--引入jQuery包用于使用ajax-->
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <h1>请输入你的姓名和年龄</h1>
    <!--创建两个input输入框,定义id分别为name,age-->
    <input type="text" id="name" name="name" placeholder="姓名">
    <br>
    <input type="text" id="age" name="age" placeholder="年龄">
    <br>
    <!--创建button按钮,点击则激发submit()事件-->
    <button onclick="submit();">提交</button>
    <script>
        /*在这里编写submit()事件*/
        function submit() {
     
     
            $.ajax({
     
     
                url: "submit", /*数据提交到submit处*/
                type: "POST",  /*采用POST方法提交*/
                data: {
     
      "name": $("#name").val(),"age":$("#age").val()},  /*提交的数据(json格式),从输入框中获取*/
                /*result为后端函数返回的json*/
                success: function (result) {
     
     
                    if (result.message == "success!") {
     
     
                        alert(result.message+"你的名字是"+result.name+",你的年龄是"+result.age)
                    }
                    else {
     
     
                        alert(result.message)
                    }
                }
            });
        }
    </script>
</html>

When we complete the ajax data submission, we write the corresponding processing function submit() in the back-end app.py.
The content in app.py is as follows:

from flask import Flask, render_template, request, jsonify
#创建Flask对象app并初始化
app = Flask(__name__)

#通过python装饰器的方法定义路由地址
@app.route("/")
#定义方法 用jinjia2引擎来渲染页面,并返回一个index.html页面
def root():
    return render_template("index.html")

#app的路由地址"/submit"即为ajax中定义的url地址,采用POST、GET方法均可提交
@app.route("/submit",methods=["GET", "POST"])
#从这里定义具体的函数 返回值均为json格式
def submit():
    #由于POST、GET获取数据的方式不同,需要使用if语句进行判断
    if request.method == "POST":
        name = request.form.get("name")
        age = request.form.get("age")
    if request.method == "GET":
        name = request.args.get("name")
        age = request.args.get("age")
    #如果获取的数据为空
    if len(name) == 0 or len(age) ==0:
        return {
    
    'message':"error!"}
    else:
        return {
    
    'message':"success!",'name':name,'age':age}

#定义app在8080端口运行
app.run(port=8080)

After writing, we visit port 8080 of the server for testing, and the results are as follows:
Insert picture description here

Database Connectivity

The database is an indispensable part of a web page. In the previous example, the data was obtained from the front end or entered randomly. How to get data from the database?
First, we introduce the pymysql library and write the Database class, which is written in database.py:

import pymysql
class Database:
    #设置数据库的连接参数,由于我是在服务器中编写的,所以host是localhost
    host = "localhost"
    user = "root"
    password = "Zhangxy0212!!"
    #类的构造函数,参数db为欲连接的数据库。该构造函数实现了数据库的连接
    def __init__(self,db):
        connect = pymysql.connect(host=self.host,user=self.user,password=self.password,database=db)
        self.cursor = connect.cursor()
    #类的方法,参数command为sql语句
    def execute(self, command):
        try:
            #执行command中的sql语句
            self.cursor.execute(command)
        except Exception as e:
            return e
        else:
            #fetchall()返回语句的执行结果,并以元组的形式保存
            return self.cursor.fetchall()

We can create a new data.html file in the templates file to create a new page. The content of the file is as follows:

<html>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<h1>请输入你的名字</h1>
<input type="text" id="name" name="name">
<button onclick="show();">提交</button>
<!--result用来显示提交结果-->
<p id="result"></p>
<script>
    function show() {
     
     
        $.ajax({
     
     
            url: "show",
            type: "POST",
            data: {
     
      "name": $("#name").val()},
            /*不要忘记 result为后端处理函数的返回值!*/
            success: function (result) {
     
     
                if (result.status == "success") {
     
     
                    $("#result").text($("#name").val() + "是" + result.message)
                }
                else {
     
     
                    $("#result").text("出错了")
                }
            }
        });
    }
</script>
</html>

Triggering event button to show (); Next we write in app.py the rendering function data data.html page () and event handlers Show () .
Remember, these two functions must be added to create the app objects and between operational definition of port ! !
Since we want to use the written Database class to connect to the database, we need to introduce it at the top of app.py :

from database import Database

The data() function and show() function are as follows:

#通过python装饰器的方法定义路由地址
@app.route("/data")
#定义方法 用jinjia2引擎来渲染页面,并返回一个index.html页面
def data():
    return render_template("data.html")

#app的路由地址"/show"即为ajax中定义的url地址,采用POST、GET方法均可提交
@app.route("/show",methods=["GET", "POST"])
def show():
    #首先获取前端传入的name数据
    if request.method == "POST":
        name = request.form.get("name")
    if request.method == "GET":
        name = request.args.get("name")
    #创建Database类的对象sql,test为需要访问的数据库名字 具体可见Database类的构造函数
    sql = Database("test")
    try:
        #执行sql语句 多说一句,f+字符串的形式,可以在字符串里面以{}的形式加入变量名 结果保存在result数组中
        result = sql.execute(f"SELECT type FROM type WHERE name='{name}'")
    except Exception as e:
        return {
    
    'status':"error", 'message': "code error"}
    else:
        if not len(result) == 0:
            #这个result,我觉得也可以把它当成数据表,查询的结果至多一个,result[0][0]返回数组中的第一行第一列
            return {
    
    'status':'success','message':result[0][0]}
        else:
            return "rbq"

We press to F5run the app.py file and visit http://121.41.111.94/data
. The results are shown in the figure: One
Insert picture description here
more sentence, the content of the data table type is as follows:
Insert picture description here

screen

At this point, the basic process of building a simple web page using the flask framework is over!
I think you must have a question in your mind . Every time you run the python program F5, you always need to press Run. If you turn off VS Code, the process will be killed and the server page will not be displayed, as shown in the figure:
Insert picture description here
Then we need to be in the server Use screen to create a background, and put the app.py program to run in the background to achieve the purpose of continuous operation.

Create backend

Since my server is Centos, I use yum install screen to download the screen.
After the download is complete, enter the screen command anywhere on the server to create the background. The background is shown in the figure:
Insert picture description here
screen 0 will be displayed above.
We enter the file where the project is located. Try input command: python app.py as shown in the figure:

Insert picture description here
If we visit 121.41.111.94 again, we will find that the website has been launched! Even if we close the command line, the program continues to run in the background.

View delete background

If we need to view the background operation, enter the command in the server: screen -x
If you need to stop the background operation, first enter a certain background through screen -x [pid number] . After entering Ctrl+, the Coperation can be stopped.
If you delete the background, first enter a background through screen -x [pid number] , and enter exit after entering

end

Due to the project needs in the next semester of junior year, I temporarily learned the flask framework. This is my first time to write a CSDN blog. If there is something wrong, please correct me~

Guess you like

Origin blog.csdn.net/Littleflowers/article/details/113926184