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

1、fastapi快速服务器搭建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#  -*- 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请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 搭建的 后端服务框架

      https://github.com/wuzaipei/alg_interface_fastapi_project

posted @   算法浪客  阅读(8371)  评论(2编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
历史上的今天:
2019-04-25 5类常见的推荐算法
点击右上角即可分享
微信分享提示