fastapi地址参数里输入name


from fastapi import FastAPI,Request
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import uvicorn 
app = FastAPI()

templates = Jinja2Templates(directory="templates")
@app.get('/hello/{name}', response_class=HTMLResponse)#这里的参数名不能写错,会报错,如,responses=HTMLResponse,报错TypeError: 'type' object is not a mapping
def hello(request:Request,name:str ):#建议将参数名小写,以符合Python的命名规范。
    #return templates.TemplateResponse('hello.html',request=request,name=name)
    return templates.TemplateResponse('hello.html',{'request': request,"name":name})
    
 
if __name__ == "__main__":  
     
    uvicorn.run(  
    app='fastapiHello:app',   
    host="127.0.0.1",   
    port=8000, reload=True  
    )



hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hello</title>
</head>
<body>
    <h1>hello{{name}},goodluck!</h1>
    
</body>
</html>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
FastAPI使用pydantic库来定义数据模型,其中包含各种类型的数据字段和其约束条件,如最小值、最大值、正则表达式等。在FastAPI中,我们可以使用这些字段作为API函数的参数,并在运行时自动验证输入数据是否符合模型定义。 例如,下面是一个示例数据模型: ```python from typing import List from pydantic import BaseModel class User(BaseModel): id: int name: str age: int email: str friends: List[str] = [] ``` 在上面的示例中,我们定义了一个User类,它继承自BaseModel类,并包含了id、name、age、email和friends这些字段。id和age是整数类型,name和email是字符串类型,friends是一个字符串列表类型。我们还为friends字段指定了一个默认值,即空列表。 现在,我们可以在FastAPIAPI函数中使用这个User类作为参数,并使用其字段来验证输入数据。例如: ```python from fastapi import FastAPI from typing import List from pydantic import BaseModel app = FastAPI() class User(BaseModel): id: int name: str age: int email: str friends: List[str] = [] @app.post("/users/") async def create_user(user: User): # Do something with the user data return {"message": "User created successfully"} ``` 在上面的示例中,我们使用User类作为API函数create_user的参数,并将其命为user。当请求到达该API函数时,FastAPI会自动将请求体中的JSON数据转换成User对象,并验证其字段是否符合模型定义。如果有任何字段与模型不匹配,FastAPI将返回一个400 Bad Request响应。 在总结中,FastAPI使用pydantic库来定义数据模型,并在API函数中使用这些模型作为参数。在运行时,FastAPI会自动验证输入数据是否符合模型定义,并返回错误响应,以便我们可以快速找到问题并修复它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值