python 使用flask 快速搭建后台服务

复制代码
from flask_cors import CORS
from flask import Flask, request
import pymysql
import json

conn = pymysql.connect(user='root',
                       passwd="yyjeiq",
                       host="127.0.0.1",
                       database="fmg",
                       charset="utf8")

cursor = conn.cursor(pymysql.cursors.DictCursor)

app = Flask(__name__)

# 解决跨域问题
CORS(app, resources=r"/*")


@app.route("/index", methods=['GET', 'POST'])
def index():
    sql = 'select e.id, e.name, e.sex, e.age, d.name as dep_name from emp as e join dep as d on e.dep_id = d.id;'
    cursor.execute(sql)
    result = cursor.fetchall()
    print(result, type(result))
    # 获取参数
    # print(request.args.get("username"))
    return  json.dumps(result)


app.run()
复制代码

 

测试html

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
    <style>
        table {
            margin-top: 20px;
            width: 600px;

        }

        tr {
            width: 100%;
            display: flex;
            font-weight: 400;
        }

        th {
            flex: 1;
        }

        td {
            flex: 1;
            text-align: center;
        }
    </style>
</head>

<body>
    <button id="test">测试</button>

    <table border="1" cellpadding="1" cellspacing="0">
        <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>性别</th>
                <th>年龄</th>
                <th>所属部门</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <script>
        const btn = document.querySelector("#test")
        const tbody = document.querySelector("tbody")

        btn.addEventListener("click", () => {
            getData()
        })

        async function getData() {
            const res = await axios.post("http://127.0.0.1:5000/index?username=fmg")
            let html = ''
            // for (let i = 0; i < res.data.length; i++) {
            //     console.log(i)
            // }
            res.data.forEach(i => {
                html += `
                <tr>
                    <td>${i.id}</td>
                    <td>${i.name}</td>
                    <td>${i.sex}</td>
                    <td>${i.age}</td>
                    <td>${i.dep_name}</td>
                </tr>
                `
            })
            tbody.innerHTML = html
        }
    </script>
</body>

</html>
复制代码

 

运行结果

 

posted @   深海里的星星i  阅读(241)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
点击右上角即可分享
微信分享提示