前端根据后端暴露出的接口发送请求拿到数据,js对数据进一步处理,渲染展示,一气呵成。
前端
request.js
使用axios请求
import axios from "axios"
const service = axios.create({
baseURL: "/api",
timeout: 50000
})
// before any request, use this config
service.interceptors.request.use(
config => {
//for future use
return config;
},
error => {
// 全局请求失败处理,当请求发送失败时,处理error
console.log(error)
}
)
export default service
data.js
# "@/utils/request" 和文件路径有关,不可照搬
import request from "@/utils/request"
export function verify(token, account) {
return request({
url: '/verify/',
method: 'post',
data: {
'token': token,
'account': account
}
})
}
vue.config.js 文件
module.exports = {
devServer: {
proxy: {
'/api': {
port: '3000',
target: 'http://localhost:8000',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
页面js
以vue界面为例(其实并无太多差异)
<script>
import {getPersonInfo, verify} from "@/api/data";
export default {
data() {
return {
user_id: '',
powerList: [],
right: 1,
index: '1',
activeIndex: '1',
}
},
beforeCreate() {
var token = sessionStorage.getItem("token");
var account = sessionStorage.getItem("account");
verify(token, account).then(res => {
if (res.code === 200) {
if (res.root === 2) {
var account = sessionStorage.getItem("account");
this.user_id = account;
} else {
var account = sessionStorage.getItem("Diraccount");
this.user_id = account;
}
getPersonInfo(this.user_id).then(res => {
var that = this;
if (res.code === 200) {
that.powerList = res.data;
this.initCharts();
}
});
} else {
this.$message("登录过期");
this.$router.replace('/login');
}
})
}
}
</script>
后端
FastApiProject
缺点在于无orm(Django有),应当结合具体情况进行使用。
main.py (启动,绑定请求地址和逻辑层函数)
from fastapi import FastAPI
from views import proRec
from models import RecItem
app = FastAPI()
security = HTTPBearer()
auth_handler = AuthHandler()
# oj 前十用户信息
@app.get("/topTenInfo/")
async def get_top_ten_info():
return top_ten_info()
# 用户推荐题目
@app.post("/rec/")
async def get_rec_info(
item: RecItem
):
return proRec(user_id=item.user_id)
即访问./rec/ 如果是post请求则与get_rec_info(自定义名称)函数绑定返回对应逻辑层(views.py)的函数。
item:RecItem 表示post请求中携带参数与RecItem(models.py)中定义一致
views层(逻辑层)— views.py
def proRec(user_id):
根据user_id进行操作
if len(res_list) != 0:
return {'data': res_list,
'code': 200,
'status': '数据获取成功!'}
else:
return {
'data': '',
'code': 201,
'status': '数据查询出错!'
}
model层(实体层)---- models.py
from pydantic import BaseModel
class RecItem(BaseModel):
user_id: str
class ACQueryItem(BaseModel):
user_id: str
start_date: str
end_date: str
page: int
num: int
确保与携带参数保持一致