1. 程式人生 > 其它 >python 使用flask 快速搭建後臺服務

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>

執行結果