当前位置:   article > 正文

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

fastapi 接 ajax json jsonp

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/339200
推荐阅读
相关标签
  

闽ICP备14008679号