程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python uses generics

編輯:Python

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

General classes use

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 :

  1. 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

  2. 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

pydantic Use

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

python More articles on using generics

  1. 【Java Summary of experience four 】Java Under generics —— The erasure of all evils

    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 ...

  2. Python - typing modular —— TypeVar Generic

    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 ...

  3. 【Python Take your time 】 Learn quickly python

    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 ...

  4. Self issue python Version making ( One )

    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 ...

  5. Python Foundation - Operation of file

    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 ...

  6. [python Implement design patterns ]-5. Iterator pattern - Let's roll together

    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 ...

  7. 【 Learn step by step Python】14. Database support

    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 ...

  8. Python Basics s14-day1

    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 ...

  9. Python Easy chat tools - Based on asynchrony Socket signal communication

    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 ...

  10. [ Reading notes ]C# Learning notes 7 : C#4.0 Minor changes - Optional parameters , The variability of generics

    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 ...

Random recommendation

  1. iOS Development UI piece —Quartz2D( Customize UIImageView Control )

    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 ...

  2. Configure domain master DNS The server

    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 ...

  3. MVC In the view Html.DropDownList() The use of auxiliary methods

    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 ...

  4. hdu 3954 Level up( Line segment tree )

    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 ...

  5. java The application determines whether an integer entered by the user is in a known array .

    import java.util.*; class Example2_5 { public static void main(String args[]) { int start=0,end,midd ...

  6. 【BZOJ3631】【JLOI2014】 Squirrel's new home

    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 ...

  7. python the second day 3.1

    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 ...

  8. Conclusions about Deep Learning with Python

     Conclusions about Deep Learning with Python  Last night, I start to learn the python for deep learn ...

  9. Oracle Generate Guid;Oracle Generate multiple Guid;Oracle Generative band &#39;&#39;-&quot; Of Guid

    Oracle  Generate Guid select sys_guid() from dual Oracle  Generate multiple Guid Oracle  Generative band ''-" Of Guid , ) , ) || '-' || ...

  10. How to be in Ubuntu 16.04 Install configuration on Redis

    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 ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved