ajax python接口,python fastapi ajax post get json 数据交互 错误:422 (Unprocessable Entity)

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 搭建的 后端服务框架

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值