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>Documenttitle>
<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>IDth>
<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>
运行结果