首页 > 其他分享 >【4.0】Fastapi简单使用

【4.0】Fastapi简单使用

时间:2023-10-01 15:48:35浏览次数:47  
标签:info city return 4.0 Fastapi app str 简单 Optional

【一】Fastapi引入

【1】构建基础的fastapi项目

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

# 创建 fastapi 对象
app = FastAPI()


# 定义模型表
class CityInfo(BaseModel):
    # 省份
    province: str
    # 城市
    country: str
    # 是否被感染 , Optional[bool] 与 bool 的区别是 可以不传,默认为 null
    is_affected: Optional[bool] = None


# 定义路由 ---- 访问根路径返回指定内容
@app.get('/')
def hellow_world():
    return {'hello': "world"}


# city : 路径参数
# /city/{city}?name=dream : ?name=dream 查询参数
@app.get('/city/{city}')
def result(city: str, query_string: Optional[str] = None):
    '''

    :param city: 城市 -- 路径参数
    :param query_string: 请求参数 -- str 类型 默认可以为 None
    :return:
    '''
    return {'city': city, 'query_string': query_string}

【2】启动项目

  • 基本启动命令
uvicorn 文件名:app名
# 启动项目命令 :uvicorn 01hello_world:app
  • Debug启动
uvicorn 文件名:app名 --reload
# 带Debug模式启动命令 : uvicorn 01hello_world:app --reload
  • 注意所在的文件路径
(venv) PS E:\fastapiProjects\projects\part3> uvicorn 01hello_world:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [23976] using statreload
INFO:     Started server process [18320]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

【3】访问项目

  • http://127.0.0.1:8000
    • 可以看到正是上面我们所写的返回值

image-20230929144822376

  • http://127.0.0.1:8000/city/city
    • 访问带参数的路径,我们可以看到其中的一个参数已经被接受到了

image-20230929145011646

  • http://127.0.0.1:8000/city/city?query_string=dream
    • 携带我们的路径参数,我们也可以看到参数传递成功

image-20230929145103528

【4】访问路由返回数据

(1)定义路由及视图

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

# 创建 fastapi 对象
app = FastAPI()


# 定义模型表
class CityInfo(BaseModel):
    # 省份
    province: str
    # 城市
    country: str
    # 是否被感染 , Optional[bool] 与 bool 的区别是 可以不传,默认为 null
    is_affected: Optional[bool] = None

# 定义返回数据
@app.put('/city/{city}')
def result(city: str, city_info: CityInfo):
    '''

    :param city:  城市 -- 路径参数
    :param city_info:  携带的数据 必须符合上面定义的模型类
    :return:
    '''

    return {'city': city, 'province': city_info.province, 'country': city_info.country,
            'is_affected': city_info.is_affected}

(2)携带参数

  • 可以使用postman/apifox

image-20230929150140529

  • 也可以使用fastapi自带的 Swagger 接口工具

    • http://127.0.0.1:8000/docs

    image-20230929150237553

    • 携带参数,发起请求

    image-20230929150406676

    • 获取响应信息

    image-20230929150434507

【5】同步请求变异步请求

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

# 创建 fastapi 对象
app = FastAPI()


# 定义模型表
class CityInfo(BaseModel):
    # 省份
    province: str
    # 城市
    country: str
    # 是否被感染 , Optional[bool] 与 bool 的区别是 可以不传,默认为 null
    is_affected: Optional[bool] = None


# 定义路由 ---- 访问根路径返回指定内容
@app.get('/')
async def hellow_world():
    return {'hello': "world"}


# city : 路径参数
# /city/{city}?name=dream : ?name=dream 查询参数
@app.get('/city/{city}')
async def result(city: str, query_string: Optional[str] = None):
    '''

    :param city: 城市 -- 路径参数
    :param query_string: 请求参数 -- str 类型 默认可以为 None
    :return:
    '''
    return {'city': city, 'query_string': query_string}


# 定义返回数据
@app.put('/city/{city}')
async def result(city: str, city_info: CityInfo):
    '''

    :param city:  城市 -- 路径参数
    :param city_info:  携带的数据 必须符合上面定义的模型类
    :return:
    '''

    return {'city': city, 'province': city_info.province, 'country': city_info.country,
            'is_affected': city_info.is_affected}

【二】Fastapi的API交互文档docs

【1】接口地址

  • http://127.0.0.1:8000/docs

【2】总览

image-20230929150908349

【3】标头

image-20230929151009894

【4】无参请求

  • Curl 表示在Linux系统上如何发送请求
  • Response 可以自定义响应详细信息
  • Example Value 可以自己写一个请求的示例,这样前端可以直接使用我们的示例进行测试

image-20230929151203974

image-20230929151243467

image-20230929151330085

【5】有参请求

image-20230929151548846

image-20230929151707141

【6】有参PUT请求见上面

【三】Fastapi的API交互文档redoc

【1】接口地址

  • http://127.0.0.1:8000/redoc

【2】页面展示

image-20230929152052644

【3】说明

  • redoc只能查看我们接口相关的信息,但是无法进行交互时发送请求

标签:info,city,return,4.0,Fastapi,app,str,简单,Optional
From: https://www.cnblogs.com/dream-ze/p/17738890.html

相关文章

  • 【3.0】Fastapi环境搭建及初步使用
    【一】环境准备【1】第三方包requirements.txtaiofiles==0.6.0atomicwrites==1.4.0attrs==20.3.0bcrypt==3.2.0certifi==2020.12.5cffi==1.14.4chardet==4.0.0click==7.1.2colorama==0.4.4cryptography==3.3.1dnspython==2.0.0ecdsa==0.14.1email-validator==1.1......
  • 【9.0】Fastapi表单数据处理
    【一】表单参数【1】定义视图fromfastapiimportAPIRouter,status,FormfrompydanticimportBaseModel,EmailStrfromtypingimportOptional,Union,Listapp04=APIRouter()###表单数据处理@app04.post("/login/")asyncdeflogin(#username用户名......
  • 【8.0】Fastapi响应模型
    【一】自定义响应模型【1】定义视图函数fromfastapiimportAPIRouterfrompydanticimportBaseModel,EmailStrfromtypingimportOptionalapp04=APIRouter()###响应模型#定义基本类classUserBase(BaseModel):#定义字段username:用户名类型为str:......
  • 【6.0】Fastapi请求体参数及混合参数
    【一】说明项目接上小结【二】请求体和字段fromfastapiimportAPIRouter,Path,QueryfrompydanticimportBaseModel,Fieldapp03=APIRouter()##请求体字段classCityInfo(BaseModel):#给name字段添加注解#...:表示必填字段#example:表示......
  • 【14.0】中间件、跨域资源共享、后台任务、测试用例
    【一】中间件【1】中间件介绍FastAPI中间件是在处理请求和响应的过程中介入的组件,允许你在请求到达处理函数之前或响应离开处理函数之后执行一些逻辑。中间件在FastAPI中起到非常灵活的作用,可以用于日志记录、身份验证、异常处理等。【2】中间件的工作原理(1)注册中间件......
  • 【13.0】Fastapi中的Jinja2模板渲染前端页面
    【一】创建Jinja2引擎#必须模块fromfastapiimportRequest#必须模块fromfastapi.templatingimportJinja2Templates#创建子路由application=APIRouter()#创建前端页面配置templates=Jinja2Templates(directory='./coronavirus/templates')#初始化数据库......
  • 【12.0】Fastapi中的数据库SQLAlchemy ORM 操作
    【一】大型项目结构树coronavirus ├─static #静态文件 ├─templates #前端页面 ├─__init__.py #初始化文件 ├─database.py #数据库操作 ├─models.py #数据库表模型类 ├─schemas.py #响应体模型类 ├─curd.py #视图函数 └─main.py #......
  • 【11.0】Fastapi的OAuth2.0的授权模式
    【一】OAuth2.0的授权模式授权码授权模式(AuthorizationCodeGrant)隐式授权模式(ImplicitGrant)密码授权模式(ResourceOwnerPasswordCredentialsGrant)客户端凭证授权模式(ClientCredentialsGrant)【二】密码授权模式【1】FastAPI的OAuth2PasswordBearer说明......
  • FastAPI学习-26 并发 async / await
    前言有关路径操作函数的asyncdef语法以及异步代码、并发和并行的一些背景知识async和await关键字如果你正在使用第三方库,它们会告诉你使用await关键字来调用它们,就像这样:results=awaitsome_library()然后,通过asyncdef声明你的路径操作函数:@app.get('/')asy......
  • JDBCTemplate 的简单使用
    什么是JDBCTemplateSpring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作使用JDBCTemplate1.在xml文件中配置 JdbcTemplate 对象,注入 DataSource(即数据库、数据源)<context:component-scanbase-package="transaction"/><beanid="dataSource"......