【问题标题】:method put in fastapi not working/ 405 method not allowed放入 fastapi 的方法不起作用/不允许 405 方法
【发布时间】:2021-02-14 23:24:01
【问题描述】:

我在使用 Fastapi、Jinja2 put 方法时遇到问题。 我的任务是保存表单,这里是 html 文件中的 ajax

    function submitForm() {
        var url = 'http://localhost:8000';
        let id = document.getElementById("person-id").value;
        var data = {id: id};
        fetch(url, {
          method: 'PUT',
          body: JSON.stringify(data),
          headers:{
            'Content-Type': 'application/json'
          }
        }).then(res => res.json())
        .then(response => console.log('Success:', JSON.stringify(response)))
        .catch(error => console.log('Error:', error));

这里py方法更新

@router.put("/{id}",  response_class=Response)
async def update(request: Request, id: str, req: UpdateModel = Body(...)):
   updated = await update(id, req.dict())
   return templates.TemplateResponse('index.html', context={'request': request})

更新不起作用,控制台只是显示

不允许使用 405 方法 T

【问题讨论】:

  • 您的url 变量只是指向http://localhost:8000。它需要指向http://localhost:8000/{id}
  • @im_baby 只允许 405 方法,除此之外没有错误。我的意思是 uvicorn 在其他部分起作用
  • @im_baby 是的,因为这是放的,当我检查Referer时:我得到了这个值localhost:8000/id
  • 在 Postman 中尝试一下,看看结果如何。当你 PUT 到 http://localhost:8000 时,你得到 405,当你 PUT 到 http://localhost:8000/{id} 时,你得到 200

标签: python jinja2 fastapi


【解决方案1】:

1。创建一个简单的后端

1.1 创建test.py


from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI
import uvicorn
import datetime

from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()

origins = ["*"]
 
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"message": "Hello World", "datetime": datetime.datetime.now(), "test": 'this is a test'}


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


@app.put("/items/{item_id}")
async def create_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}


if __name__ == '__main__':
    uvicorn.run(app='test:app', reload=True, debug=True)


1.2运行test.py文件

python test.py

2。前部

2.1 创建index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>test</h1>
    <script>
        const person = {
            name: 'apple',
            description: 'this is a test',
            price:200,
            tax: 400123598
        }

        fetch('http://127.0.0.1:8000/items/40', {
            method: 'PUT',
            body: JSON.stringify(person)
        }).then(function(respones) {
            return respones.json();
        }).then(function(data) {
            console.log(data);
        })
    </script>

</body>

</html>


2.2 使用chrome浏览器打开index.html查看chrome的Console

【讨论】:

    猜你喜欢
    • 2021-12-09
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多