Python back-end program: Flask connects to the database mysql, and implements basic SQL addition, deletion, modification and query (including all codes, which can run through)

Table of contents

1. Project Background

1.1 Technology stack

1.2 Summary

Two, source code

2.1 sever.py

2.2 server_conf.py

3. Run the demo (graphic tutorial)

3.1 Data preparation

3.2 Start the service

3.3 Test GET: select_data

3.4 Test PATCH: update_data

3.5 Test DELETE: delete_data

3.6 Test POST: insert_data


1. Project Background

1.1 Technology stack

The python version is python3.10.11, other packages can use the corresponding version of python, framework: flask2.3.2, IDEA is pycharm, use postman to simulate the front end, database: mysql

1.2 Summary

It’s just a small case to quickly get started with flask and front-end and back-end interactions. There is a lot of room for optimization, such as: code robustness, readability, format standards, code is not concise, etc., and the implementation is not flexible enough. It is hard-coded, and the operation of the database must be careful, especially the deletion, insertion and modification. All scenarios must be considered to avoid accidents. This code is not advocated in real application scenarios, ps: readers can also learn flask_resrless use

Two, source code

Create a new folder locally such as: sql_platform, save the 2.1 and 2.2 source codes as two py files, and place them under sql_platform.

2.1 sever.py

"""
Author : rebeccayanhan
Time   : 2023/5/22 下午5:45
File   : server.py
"""

from flask import Flask, jsonify, request
from service_conf import *
import pymysql
import json

app = Flask(__name__)


def create_mysql_conn():
    # pymysql连接rebecca数据库
    conn = pymysql.connect(host=mysql_params['host'],
                           port=mysql_params['port'],
                           user=mysql_params['user'],
                           passwd=mysql_params['passwd'],
                           db=mysql_params['db'],
                           charset=mysql_params['charset'])

    return conn


@app.route("/")
def hi():
    return "Hi!"

@app.route("/select_data")
def select():
    conn = create_mysql_conn()
    # 创建一个游标
    cursor = conn.cursor()
    query_sql = "select * from student;"
    n = cursor.execute(query_sql)
    ls = ['Sno', 'Sname', 'Sex', 'Sage', 'Sdept']
    result_dic = {'count': n, 'table_name': 'student'}
    ls_2 = []
    for row in cursor:
        temp = {}
        for i in range(len(row)):
            temp[ls[i]] = row[i]
        ls_2.append(temp)
    result_dic['info'] = ls_2
    cursor.close()
    return json.dumps(result_dic)


@app.route("/insert_data", methods=["POST"])
def insert():
    conn = create_mysql_conn()
    # 创建一个游标
    cursor = conn.cursor()
    # 这个info_list = request.form.get("info")通过url
    # 下面这个通过body
    info_list = request.json.get("info")
    for info in info_list:
        sno = info['Sno']
        sname = info['Sname']
        sex = info['Sex']
        sage = info['Sage']
        sdept = info['Sdept']
        query_sql = "insert into student(Sno, Sname, Sex, Sage, Sdept) values({}, {}, {}, {}, {});".format(sno,
                                                                                                           repr(sname),
                                                                                                           repr(sex),
                                                                                                           sage,
                                                                                                           repr(sdept))
        cursor.execute(query_sql)
    cursor.close()
    conn.commit()

    ret_message = {"code": 0, "status": "successful"}
    return ret_message


@app.route("/update_data", methods=['PATCH'])
def update():
    conn = create_mysql_conn()
    cursor = conn.cursor()
    info_list = request.json.get("info")
    for info in info_list:
        sname = info['Sname']
        if sname == '李勇':
            query_sql = "update student set sage=90 where sname='{}';".format(sname)
            print(query_sql)
            cursor.execute(query_sql)
    # 修改后需要commit
    cursor.close()
    conn.commit()
    ret_message = {"code": 0, "status": "successful"}
    return ret_message


@app.route("/delete_data", methods=['DELETE'])
def delete():
    conn = create_mysql_conn()
    cursor = conn.cursor()
    info_list = request.json.get("info")
    for info in info_list:
        sno = info['Sno']
        query_sql = "delete from student where Sno={};".format(sno)
        cursor.execute(query_sql)
    # 删除后需要commit
    cursor.close()
    conn.commit()
    ret_message = {"code": 0, "status": "successful"}
    return ret_message


if __name__ == "__main__":
    app.run()

2.2 server_conf.py

"""
Author : rebeccayanhan
Time   : 2023/5/22 下午5:45
File   : server_conf.py
"""

# 读写参数
mysql_params = {
    'host': '127.0.01', 
    'user': 'root',          #数据库用户名
    'passwd': '********',    #用户密码
    'db': 'rebecca',         #数据库的名字
    'port': 3306,            #端口号
    'charset': 'utf8'        #编码方式
}

3. Run the demo (graphic tutorial)

3.1 Data preparation

Create a database first, here I use the rebecca I created myself

 Then store a few pieces of data in the database, as shown in the table below.

View the port number of the database

show global variables like 'port';

 3.2 Start the service

Start the server.py file

The startup is successful, as shown in the figure below, click http://127.0.0.1:5000/

 Appears, the service runs successfully

3.3 Test get: select_data

 The corresponding code is the select function (def select(): that line starts)

Select GET, URL input

http://127.0.0.1:5000/select_data

Select the json structure

3.4 Test PATCH: update_data

 The corresponding code is the updata function (def update(): that line starts)

Through this function, I hope to change Li Yong's age to 90. The current data is that Li Yong's age is 20 

select * from student where sname='李勇';

 Enter  http://127.0.0.1:5000/update_date , and body

{
    "info": [
        {
            "Sno": 201215121,
            "Sname": "李勇",
            "Sex": "男",
            "Sage": 20,
            "Sdept": "CS"
        }
    ]
}

Click send, as shown in the figure below, it shows that it has been successful 

 Check the data again, it has been modified successfully

3.5 Test DELETE: delete_data

 The corresponding code is the delete function (def delete(): the line starts)

The code implementation is to delete through the student number sno, delete the person with the student number equal to 201215123,

Postman performs the following input and selection

{
    "info": [
        {
            "Sno": 201215123,
            "Sname": "李勇",
            "Sex": "男",
            "Sage": 20,
            "Sdept": "CS"
        }
    ]
}

 Enter http://127.0.0.1:5000/delete_data , click send, as shown in the figure below, it shows that it has been successful 

delete result

3.6 Test POST: insert_data

 The corresponding code is the insert function (def insert(): that line starts)

To insert a new data, postman performs the following input and selection

{
    "info": [
        {
            "Sno": 112873981211,
            "Sname": "rebecca",
            "Sex": "女",
            "Sage": 18,
            "Sdept": "CS"
        }
    ]
}

Enter http://127.0.0.1:5000/insert_data  , click send, as shown in the figure below, it shows that it has been successful 

Check whether the database is inserted successfully, as shown in the figure. (You can also view it through get)

Guess you like

Origin blog.csdn.net/weixin_45440484/article/details/130854529