So called generics , Is to pass the data type as a parameter , That is, to determine the data type when we use it , This is a feature often used in object-oriented languages
With SQLAlchemy give an example
such as : We uniformly write an interface to save data to the database , Only will Database link
Table object
data
Just pass it in , The return is Instances of table objects
, In order to make IDE You can identify the return object , We can use generics
I need to use :
typing
Of TypeVar
and Type
TypeVar
Is a type variable , It is mainly used for parameters of generic types and generic function definitions , The first parameter is the name , bound
Parameter is used to specify that the type is bound
Subclass of value Type[C]
Is in the form of a covariate , indicate C
All subclasses of should Use And C
same Constructor signature And Class method signature , If we need to return generic types , Need to use
More ways to use , see : typing Use
Used pydantic
Specify the type of data to create
About
pydantic
General use of , see : Pydantic Use
from typing import TypeVar, Type
from sqlalchemy.orm import Session
from pydantic import BaseModel
from orm.models import Category
from orm.schemas import WriteCategoryModel
# Definition type
ModelT = TypeVar("ModelT")
DataT = TypeVar("DataT", bound=BaseModel) # bound Indicates that this class is BaseModel Subclasses of
"""
To save space , Table structures and models are not shown
"""
def create_category(session: Session, data: WriteCategoryModel) -> Type[Category]:
cate_obj = save_one_to_db(session=session, model_class=Category, data=data)
return cate_obj
def save_one_to_db(session: Session, model_class: ModelT, data: DataT) -> ModelT:
"""
Save a message to the database
:param session: SQLAlchemy Session
:param model_class: sqlalchemy Model class
:param data: pydantic Model object
:return: Corresponding sqlalchemy Object of model class
"""
try:
obj = model_class(**data.dict())
session.add(obj)
session.commit()
# Manual will data Refresh to database
session.refresh(obj)
return obj
except Exception as e:
# Don't forget to roll back when an error occurs
session.rollback()
raise e
In the use of pydantic when , You can also use generics
such as : stay FastAPI
The unified return format returned in is :
{
"status": true,
"msg": "success",
"data": ...
}
our data
It could be a list or an object , And the corresponding pydantic
The model is different , Then we can use generics
Code :
from typing import List, Optional, Generic, TypeVar
from fastapi import APIRouter, status, HTTPException
from pydantic import BaseModel
from pydantic.generics import GenericModel
router = APIRouter(prefix="/test", tags=[" Test generics "])
# For convenience , Defined here pydantic Model
DataT = TypeVar("DataT")
class GenericResponse(GenericModel, Generic[DataT]):
"""
General return data
"""
status: bool
msg: str
data: Optional[DataT] = None # May even data None
# Set up response_model_exclude_unset=True that will do
class BookModel(BaseModel):
id: int
name: str
# Pseudo data
fake_book_data = [
{"id": 1, "name": "book1"},
{"id": 2, "name": "book2"},
{"id": 3, "name": "book3"},
{"id": 4, "name": "book4"},
{"id": 5, "name": "book5"},
]
@router.get("/books", response_model=GenericResponse[List[BookModel]])
def get_books():
return {
"status": True,
"msg": " To be successful ",
"data": fake_book_data
}
@router.get("/books/{bid}", response_model=GenericResponse[BookModel])
def retrieve_book(bid: int):
for item in fake_book_data:
if item.get("id") == bid:
return {
"status": True,
"msg": " To be successful ",
"data": item
}
# non-existent
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=" The book does not exist ")
visit /docs
page , Successfully passed the test
One . The erasure of all evils I summed it up by myself [Java Summary of experience three ]Java On generics —— In this blog post, I mentioned Java The problem of generic erasure in , Consider the following code : import java.util.*; public clas ...
Preface typing Is in python 3.5 There are only modules Pre learning Python Type tips :https://www.cnblogs.com/poloyy/p/15145380.html Common type tips ...
Learn quickly python author : Bai Ningchao 2016 year 10 month 4 Japan 19:59:39 Abstract :python Language is not a new technology , Seven or eight years ago, there were many people studying , It's just not as popular as it is now . The reason why it's so popular right now , I think it must be more ...
Recently used python Develop some gadgets , Find out python It really conforms to my idea : Lightweight , Powerful , to open up . python Is a scripting language , Unlike java That requires a heavy compilation process . This makes python It is more light and convenient , Sure ...
Now let's play with file operation , This is in future work , It is also a very common function Python2.7 in , It can be used file() To open the file , And in the Python3 in , All use open(), Next, in the current directory , First create an empty file ...
The iterator pattern is a pattern that we often use, but it's not very efficient . Why pinch ? Because most languages help us implement the details , We can use it without paying attention to its implementation . No matter what . It's also a very common pattern . As the saying goes , There's nothing in the world ...
Plain text can only achieve some simple and limited functions . If you want to achieve automatic serialization , You can also use shelve Module and pickle Module to achieve . however , If you want to automatically achieve concurrent data access , And more standard , A more general database (databas ...
2016 year 7 month 23 Japan "Python Basics s14-Day1" Python What is it? ? Python( English pronunciation :/ˈpaɪθən/ American pronunciation :/ˈpaɪθɑːn/), It's an object-oriented . Literal translation ...
Continue to learn Python in , Recently read a book <Python Basic course > Virtual tea party project in , Find it interesting , I knocked it myself , Benefited greatly , At the same time, record . It's mainly asynchronous socket Service client and server modules asynco ...
Preface Now let's summarize C#4.0 Some of the changes in , It's the last thing in the book , This part will finally be updated . At the same time, I feel that reading it again for the second time also has a different harvest . It's snowing in Wuhan today , Tomorrow, Saturday , Everything is so beautiful . ha-ha ...
iOS Development UI piece —Quartz2D( Customize UIImageView Control ) One . Realize the idea Quartz2D The biggest use is to customize View( Customize UI Control ), When the system View When it can't meet our needs , Customize ...
One .DNS The type of server ①Primary DNS Server(Master) The master server of a domain holds the of the domain zone The configuration file , All configurations of this domain . All changes are made on this server , This essay is also about how to configure a ...
Let's have one in the controller first SelectList type , And then through ViewBag.List In the view .SelectList The type is ASP.NET MVC Specifically for list related HTML Auxiliary methods provide options for , for example ,Htm ...
Topic link :hdu 3954 Level up The main idea of the topic :N A hero ,M Level , The initial level is 1, Give the experience value required for each level ,Q operations , There are two operations ,W l r x: Express l~r Between the heroes, everyone killed x A monster :Q ...
import java.util.*; class Example2_5 { public static void main(String args[]) { int start=0,end,midd ...
Original title transmission gate The question : Give you a tree , Then there is a traversal order , You need to complete the traversal sequence , Then output the number of occurrences of each point in the traversal sequence . Their thinking : I wanted to find the problem of tree dissection , It turns out that one question can be written directly lca Of .... practice 1: Very simple ...
Arithmetic operator arithmetic operator: + - * / % % : Remainder , modulus . It takes the remainder of the division of the first operand and the second operand . The result of division is 0. 10 % 3 1 10 ...
Conclusions about Deep Learning with Python Last night, I start to learn the python for deep learn ...
Oracle Generate Guid select sys_guid() from dual Oracle Generate multiple Guid Oracle Generative band ''-" Of Guid , ) , ) || '-' || ...
How to be in Ubuntu 16.04 Install configuration on Redis Redis It's a key value store in memory , With its flexibility , Known for performance and extensive language support . In this guide , We will show you how to Ubuntu 16.04 Install and configure Re ...