首页 > 其他分享 >FastAPI CRUD Router

FastAPI CRUD Router

时间:2022-11-02 22:33:34浏览次数:65  
标签:get FastAPI route router CRUD fastapi Router id

FastAPI CRUD Router

https://github.com/awtkns/fastapi-crudrouter

fastapi提供基础的制作API能力

对于简单的业务来说,对于表仅仅需要 CRUD 接口,不需要其他额外的数据逻辑,

对于这种情况,我们希望能够快速提供对指定表格的 CRUD 能力。

此库应运而生。

 

懒人专享

快速制作业务原型

Tired of rewriting generic CRUD routes? Need to rapidly prototype a feature for a presentation or a hackathon? Thankfully, fastapi-crudrouter has your back. As an extension to the APIRouter included with FastAPI, the FastAPI CRUDRouter will automatically generate and document your CRUD routes for you, all you have to do is pass your model and maybe your database connection.

FastAPI-CRUDRouter is lighting fast, well tested, and production ready.

 

Basic Code

非常神奇便利

只需要提供Pydantic schema生成一个CRUD router即可。

 

Below is a simple example of what the CRUDRouter can do. In just ten lines of code, you can generate all the crud routes you need for any model. A full list of the routes generated can be found here.

from pydantic import BaseModel
from fastapi import FastAPI
from fastapi_crudrouter import MemoryCRUDRouter as CRUDRouter

class Potato(BaseModel):
    id: int
    color: str
    mass: float

app = FastAPI()
app.include_router(CRUDRouter(schema=Potato))

 

默认生成的API

https://fastapi-crudrouter.awtkns.com/routing

 增删改查面面俱到。

Default Routes

By default, the CRUDRouter will generate the six routes below for you.

RouteMethodDescription
/ GET Get all the resources
/ POST Create a new resource
/ DELETE Delete all the resources
/{item_id} GET Get an existing resource matching the given item_id
/{item_id} PUT Update an existing resource matching the given item_id
/{item_id} DELETE Delete an existing resource matching the given item_id

 

选择默认支持的API

如果有的接口不需要,可以关闭。

Disabling Routes

Routes can be disabled from generating with a key word argument (kwarg) when creating your CRUDRouter. The valid kwargs are shown below.

ArgumentDefaultDescription
get_all_route True Setting this to false will prevent the get all route from generating
get_one_route True Setting this to false will prevent the get one route from generating
delete_all_route True Setting this to false will prevent the delete all route from generating
delete_one_route True Setting this to false will prevent the delete one route from generating
create_route True Setting this to false will prevent the create route from generating
update_route True Setting this to false will prevent the update route from generating

 

router = MemoryCRUDRouter(schema=MyModel, delete_all_route=False)

 

定制接口

如果有的接口不满足要求,例如需要在创建条目后, 触发后台业务,

可以重载接口,定制业务逻辑。

 

Below is an example where we are overriding the routes /potato/{item_id} and /potato while using the MemoryCRUDRouter.

 

from pydantic import BaseModel
from fastapi import FastAPI
from fastapi_crudrouter import MemoryCRUDRouter as CRUDRouter

class Potato(BaseModel):
    id: int
    color: str
    mass: float

app = FastAPI()
router = CRUDRouter(schema=Potato)

@router.get('')
def overloaded_get_all():
    return 'My overloaded route that returns all the items'

@router.get('/{item_id}')
def overloaded_get_one():
    return 'My overloaded route that returns one item'

app.include_router(router)

 

Dependencies

https://fastapi-crudrouter.awtkns.com/dependencies

接口需要鉴权,则定义依赖可以实现。

 

All the CRUDRouters included with fastapi_crudrouter support FastAPI dependency injection.

 

from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from fastapi_crudrouter import MemoryCRUDRouter

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="auth/token")

def token_auth(token: str=Depends(oauth2_scheme)):
    if not token:
        raise HTTPException(401, "Invalid token")

router = MemoryCRUDRouter(schema=MySchema, dependencies=[Depends(token_auth)])
app.include_router(router)

 

Custom Dependencies Per Route

也可以对具体接口定义依赖。

CRUDRouter(
    # ...
    get_all_route=[Depends(get_all_route_dep), ...],
    get_one_route=[Depends(get_one_route_dep), ...],
    create_route=[Depends(create_route_dep), ...],
    update_route=[Depends(update_route_dep), ...],
    delete_one_route=[Depends(user), ...],
    delete_all_route=[Depends(user), ...],
)

 

标签:get,FastAPI,route,router,CRUD,fastapi,Router,id
From: https://www.cnblogs.com/lightsong/p/16852304.html

相关文章

  • 经常被问到的react-router实现原理详解
    在单页面应用如日中天发展的过程中,备受关注的少了前端路由。而且还经常会被xxx面试官问到,什么是前端路由,它的原理的是什么,它是怎么实现,跳转不刷新页面的...一大堆为什么,......
  • Vue-router与路由
    Vuex的使用1.vue的插件,增强了vue的功能-在vue中实现集中式状态(数据)管理的一个vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方......
  • 今日内容 Vuex 和Vue-router的使用
    Vuex的使用作用vue的插件,增强了vue的功能  在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信......
  • vuex的使用,vue-router的使用,路由守卫
    vuex的使用Vue-router的使用基本使用路由的跳转路由跳转携带参数路由嵌套路由守卫vuex的使用vuex是vue的一个插件,大大提升了vue的功能在Vu......
  • 解决vue-router@3重复添加路由导致的控制台警告
    vue项目的权限限制功能,有一种实现方案是这样的进入项目只设置没有权限要求的路由向后台提供当前用户的权限后台根据用户权限,返回该用户可以用的路由信息将路由......
  • Vue3 Router
    1.定义404路由当URL地址上的路径不能匹配到对应的路由时,可设置404路由界面。router/index.js//router/index.jsimport{createRouter,createWebHashHistory}fr......
  • Vue router简单配置入门案例
    { 注意驼峰命名法,不然会报错  }   1.在Views文件夹下创建Vue路由文件,例如:<template></template> <script></script> template:表示html结构区域,scri......
  • 3.CRUD(增删改查)
    3.CRUD(增删改查)1.namespacenamespace即“命名空间”,也称“名称空间”。是许多编程语言使用的一种代码组织的形式,通过命名空间来分类,区别不同的代码功能,避免不同的代码片......
  • react router6使用
    1.BrowserRouter说明:用于包裹整个应用。importReactfrom"react";importReactDOMfrom"react-dom";import{BrowserRouter}from"react-router-dom";ReactDO......
  • VueRouter 实现登录后跳转到之前相要访问的页面的简单示例
    简介该功能主要用于判定用户权限,在用户无权限时重定向至登录页,并在用户完成登录后,再定向至用户之前想要访问的路由;或者用户在任意路由点击登录时,登录成功后返回当前路由。......