fastapi之根据model生成schema和router

摘要:
概述fastapi没有对应的admin,所以在需要配置后端的时候,会比较麻烦,每个接口都需要自己手动写。一个装饰器通过装饰器装饰model就可以自动注册路由,自动生成对应的标准方法,再根据更多的一些自定义配置,甚至不需要自己手动写schema,然后不需要自己单独写路由相关的东西。原理通过type动态生成对应的model。

概述

fastapi没有对应的admin,所以在需要配置后端的时候,会比较麻烦,每个接口都需要自己手动写。

但是很多时候我们可能需要一个比较标准的东西,比如…一个装饰器

通过装饰器装饰model就可以自动注册路由,自动生成对应的标准方法,再根据更多的一些自定义配置,甚至不需要自己手动写schema,然后不需要自己单独写路由相关的东西。(相当于给sqlalchemy的model增加django的model的部分功能)

原理

通过type动态生成对应的model。再自动注册到服务器

使用说明

使用方法如下:

#创建model的时候,get_basemodel装饰系统

@get_basemodel

class User(Base):

__tablename__='users'

id = Column(Integer, primary_key=True, index=True)

email = Column(String(64), unique=True, index=True,default="chise123@live.com")

hashed_password = Column(String(64))

is_active = Column(Boolean, default=True)

items = relationship("Item", back_populates="owner")

在main里面的router注册:

# user是model,app是写入系统,

User.__model__.write2route('/user',app,User,get_db = SessionLocal())

这是一个demo,做技术验证用,之后会逐步完善该功能,

装饰器代码

这里只是有一个list的方法(对应methods的get)

# -*- encoding: utf-8 -*-

"""

@File : test_selializers.py

@Time : 2020/4/1 1:03

@Author : chise

@Email : chise123@live.com

@Software: PyCharm

@info :尝试将model转为basemodel的类,实现操作

"""

from pydantic import BaseModel, Field

from typing import NewType

from sqlalchemy import Integer, Table

UserId = NewType('UserId', int)

# admin_basemodel = []

from fastapi import APIRouter

class RouterBaseModel(BaseModel):

"""这个类主要是给生成的schema增加操作"""

@staticmethod

def list(model, db): # 对应get方法

"""methods=get,读取列表"""

def res():

return db.query(model).all()

# print(model.__table__.select())

return res

def write2route(self, ul, route: APIRouter, model, get_db):

"""注册到路由"""

route.get(ul)(self.list(model, get_db))

class Config:

orm_mode = True

def get_basemodel(cls):

"""通过读取model的信息,创建schema"""

model_name = cls.__name__

# mappings为从model获取的相关配置

__mappings__ = {} # {'name':{'field':Field,'type':type,}}

for filed in cls.__table__.c:

filed_name = str(filed).split('.')[-1]

if filed.default:

default_value = filed.default

elif filed.nullable:

default_value = ...

else:

default_value = None

# 生成的结构: id:int=Field(...,)大概这样的结构

res_field = Field(default_value, description=filed.description) # Field参数

if isinstance(filed.type, Integer):

tp = NewType(filed_name, int)

else:

tp = NewType(filed_name, str)

__mappings__[filed_name] = {'tp': tp, 'Field': res_field}

res = type(model_name, (RouterBaseModel,), __mappings__)

# 将schema绑定到model

cls.__model__ = res()

return cls

实现效果

免责声明:文章转载自《fastapi之根据model生成schema和router》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇AutoCAD ObjectARX和RealDWG的基本数据操作myeclipse修改内存大小不足下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WebService的讲解 和 CXF 的初步使用

1. 复习准备 1.1. Schema约束 几个重要知识: namespace 相当于schema文件的id targetNamespace属性 用来指定schema文件的namespace的值 xmlns属性 引入一个约束, 它的值是一个schema文件的namespace值 schemaLocation属性 用来指定引入的schema文件的位置...

shiro框架 4种授权方式 说明

1. shiro的配置文件(applicationContext-shiro.xml)中使用filterChain过滤url的方式 详细配置看注释 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/bean...

SpringMVC加载配置Properties文件的几种方式

最近开发的项目使用了SpringMVC的框架,用下来感觉SpringMVC的代码实现的非常优雅,功能也非常强大, 网上介绍Controller参数绑定、URL映射的文章都很多了,写这篇博客主要总结一下SpringMVC加载配置Properties文件的几种方式 1.通过context:property-placeholde实现配置文件加载   1.1、在...

activiti 工作流

1. 工作流的概念 工作流(Workflow),就是“业务过程的部分或整体在计算机应用环境下的自动化”,它主要解决的是“使在多个参与者之间按照某种预定义的规则传递文档、信息或任务的过程自动进行,从而实现某个预期的业务目标,或者促使此目标的实现”。 工作流管理系统(Workflow Management System, WfMS)是一个软件系统,它完成工作量...

Dubbo系列(3)_官方Demo说明

一、本文目的     通过Dubbo的官方Demo介绍,学会搭建一个简单的Dubbo程序,包括服务端、客户端、接口等。 Demo地址:https://github.com/alibaba/dubbo/tree/master/dubbo-demo 二、Demo概况      1、Demo分为三个项目             a) dubbo-demo-...

使用zookeeper管理远程MyCat配置文件、MyCat监控、MyCat数据迁移(扩容)

一、使用zookeeper管理远程Mycat配置文件 环境准备: 虚拟机192.168.152.130: zookeeper,具体参考前面文章 搭建dubbo+zookeeper+dubboadmin分布式服务框架(windows平台下) 虚拟机192.168.152.128: 安装好Mycat,具体参考前面文章数据库分库分表中间件mycat的安装和myc...