赞
踩
1、fastapi快速服务器搭建
# -*- coding:utf-8 -*-
from typing import List,Set,Dict
from fastapi import FastAPI, Request, Form
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn
from pydantic import Json, BaseModel
from starlette.responses import RedirectResponse
app = FastAPI(debug=True)
app.mount("/static", StaticFiles(directory="static"), name = "static") # 挂载静态文件,指定目录
templates = Jinja2Templates(directory="templates") # 模板目录
@app.get("/data")
async def read_data(request:Request,data:str):
# data = '八戒你瘦了!'
return templates.TemplateResponse("index.html", {"request": request, "title": data,"imgurl":"/static/miss.png"})
# http://127.0.0.1:11510/data?data="八戒你瘦了!"
# @app.get("/data")
# async def read_data():
#
# return "八戒你瘦了!,hello word!"
@app.get("/")
async def read_data(request:Request):
# print(dt)
print(6666666)
return RedirectResponse("/data?data=八戒你瘦了!")
# 创建数据模型
class Item(BaseModel):
df: Dict
# js请求注意:js对象转json数据: JOSN.stringify();json数据转js对象: JSON.parse();
@app.post("/jsoned")
async def get_json(item:Item):
df = {"title":"八戒你瘦了!","lst":[1,2,3,4,5]}
# print(item.df)
print(item.dict())
return {"data":df}
# cmd启动
# uvicorn appMain:app --host localhost --port 3344 --reload
# if __name__ == '__main__':
# uvicorn.run(app, host = "localhost", port = 3344)
2、js页面发送jquery ajax post请求
df = {"df": {"dt1":[0,23,90.09]}};
console.log(df);
$.ajax({
type: "post",
url: "http://localhost:3344/jsoned",
async: true,
// headers:{"Content-Type":"application/json","accept":"application/json","name":"666"},
// dataType:"json",
data:JSON.stringify(df), //http 请求 记住要把数据转换为json格式数据
success: function (res) {
console.log('成功检测');
console.log(res);
console.log(res["data"]["lst"]);
},
error:function () {
alert("返回数据失败")
}
});
3、一个完整的fastapi 搭建的 后端服务框架
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。