python 异步框架FastAPI demo
python 异步框架FastAPI demo
时间不够,先上demo,回头补上该牛叉框架的详解,真香系列,flask不想再用了
model.py
from sqlalchemy import Column,String,Boolean,ForeignKey,Integer,DateTime,Date,Float
from sqlalchemy.orm import relationship
from sqlalchemy.sql.elements import _interpret_as_column_or_from
from sqlalchemy.sql.sqltypes import Interval
from Tools.database import Base
class BuildInfo(Base):
__tablename__ = "build_info"
ID = Column(Integer,primary_key=True)
product_id = Column(Integer)
product_name = Column(String)
version = Column(String)
number = Column(Integer)
build_no = Column(String)
time = Column(DateTime)
date = Column(Date)
duration = Column(Integer)
average_duration = Column(Integer)
esti_duration = Column(Integer)
building = Column(Integer)
result = Column(String)
description = Column(String)
fail_reason = Column(String)
week = Column(Integer)
artificial_week = Column(Integer)
is_valid_build = Column(Integer)
success_average_duration = Column(Integer)
class TestResult(Base):
__tablename__ = "test_result"
id = Column(Integer,primary_key=True)
build_id = Column(Integer)
result = Column(String)
duration = Column(Integer)
total_tc = Column(Integer)
passed_tc = Column(Integer)
failed_tc = Column(Integer)
blocked_tc = Column(Integer)
passing_rate = Column(String)
failure_reason = Column(String)
start_time = Column(DateTime)
start_date = Column(Date)
log_date = Column(DateTime)
total_UT = Column(Integer)
passed_UT = Column(Integer)
failed_UT = Column(Integer)
passing_rate_UT = Column(String)
total_Sign = Column(Integer)
passed_Sign = Column(Integer)
failed_Sign = Column(Integer)
passing_rate_Sign = Column(String)
mod_time = Column(DateTime)
class NewFeature(Base):
__tablename__ = "code_coverage"
id = Column(Integer,primary_key = True)
build_id = Column(Integer)
rate_product = Column(Float)
rate_newfeature = Column(Float)
log_date = Column(DateTime)
product_id = Column(Integer)
class Products(Base):
__tablename__ = "products"
id = Column(Integer,primary_key = True)
product_name = Column(String)
version = Column(String)
class CIDuration(Base):
__tablename__ = "final_result"
build_id = Column(Integer, primary_key=True)
product_name = Column(String)
product_id = Column(Integer)
version = Column(String)
number = Column(Integer)
build_no = Column(String)
result = Column(String)
fail_reason = Column(String)
success_mark = Column(Integer)
fail_mark = Column(Integer)
success_accu = Column(Integer)
fail_accu = Column(Integer)
rate = Column(Float)
goal_rate = Column(Float)
artificial_week_rate = Column(Float)
artificial_each_week_rate = Column(Float)
id = Column(Integer)
duration = Column(Float)
average_duration = Column(Float)
over_release_arti_week = Column(Integer)
duration_split = Column(Float)
schemas.py
from pydantic import BaseModel,Field
from Entity.model import *
from typing import Optional
from datetime import date,datetime
from enum import Enum
class BuildInfo(BaseModel):
ID: int
product_id: int
product_name: str
version: str
number: int
build_no: str
duration: int
average_duration: int
esti_duration: int
building: int
result: str
description: Optional[str] = None
fail_reason: str
week: int
artificial_week: int
is_valid_build: int
success_average_duration: int
class Config:
orm_mode=True
class SelectItem(BaseModel):
ID: int
class TestResultInfo(BaseModel):
id: int
build_id: int
result: str
duration: Optional[int]
total_tc: Optional[int]
passed_tc: Optional[int]
failed_tc: Optional[int]
blocked_tc: Optional[int]
passing_rate: Optional[str]
failure_reason: Optional[str]
start_time: Optional[datetime]
start_date: Optional[date]
log_date: Optional[datetime]
total_UT: Optional[int]
passed_UT: Optional[int]
failed_UT: Optional[int]
passing_rate_UT: Optional[str]
total_Sign: Optional[int]
passed_Sign: Optional[int]
failed_Sign: Optional[int]
passing_rate_Sign: Optional[str]
mod_time: Optional[datetime]
class Config:
orm_mode=True
class Products(str , Enum):
CCW = "CCW"
CFP = "CFP"
CompareTool = "CompareTool"
FTAC = "FTAC"
FTAE = "FTAE"
FTGW = "FTGW"
FTLinx = "FTlinx"
FTSP = "FTSP"
FTUpdater = "Ftupdater"
FTView_SE_ME= "FTView_SE_ME"
FTVP = "FTVP"
OPCUA = "OPCUA"
PVc = "PVc"
config.py
HOST = '****'
PORT = 3306
USER = '****'
PWD = '***'
DATABASE = '***'
CHARSET = 'utf8'
datebase.py
from sqlalchemy import create_engine
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker,session
from sqlalchemy.ext.declarative import declarative_base
from Tools import config
engine = create_engine(f"mysql+pymysql://{config.USER}:{config.PWD}@{config.HOST}/{config.DATABASE}",echo=True, pool_pre_ping = True , pool_recycle=3600)
sessionLocal = sessionmaker(bind=engine,autocommit=False,autoflush=False)
Base = declarative_base()
def get_db():
db=sessionLocal()
try:
yield db
finally:
db.close()
query.py
import enum
from sqlalchemy.orm.session import Session
from Schemas.schemas import Products
from sqlalchemy.orm import session
from sqlalchemy import and_
from Entity import model
def get_all(db: session,models,filter):
return db.query(models).filter(filter).all()
def filter(db: session,id: int):
return db.query(model.BuildInfo).filter(model.BuildInfo.ID==id).all()
def duration(db: session,item: Products):
# Build duration
value= formatFTView(item)
build_duration_sql = '''select round(avg(c.duration_split),2) from products a, build_info b, final_result c
where a.id = b.product_id and b.id = c.build_id
and a.product_name = '{}'
and c.result = 'SUCCESS'
and date_format(b.time, '%Y%m') = date_format(curdate(), '%Y%m')'''.format(value)
build_duration = db.execute(build_duration_sql).fetchall()
if build_duration:
return build_duration[0][0]
return 0
def seccessrate(db: session,item: Products):
value= formatFTView(item)
monthlyrate=f"""
select IFNULL(round(suc.successtotal/total.monthtotal*100,0),0) as rate from ( select count(*) as monthtotal from build_info a, final_result b
where a.id = b.build_id
and a.product_name = '{value}'
and date_format(a.time, '%Y%m') = date_format(curdate(), '%Y%m')) total,
(select count(*) as successtotal from build_info a, final_result b
where a.id = b.build_id
and a.product_name = '{value}'
and date_format(a.time, '%Y%m') = date_format(curdate(), '%Y%m')
and b.result = 'SUCCESS')suc
"""
successrate = db.execute(monthlyrate).fetchall()
if successrate:
return successrate[0][0]
return 0
def unitestrate(db: Session, item: Products):
value= formatFTView(item)
unitest=f"""select ifnull(round(rate.cover_rate_feature*100,0),round(rate.cover_rate_product*100,0)) from (
select cover_rate_product, cover_rate_feature, case_number from unit_test a, build_info b
where a.build_id = b.id and b.product_name = '{value}' order by a.id desc limit 1)rate"""
unitest = db.execute(unitest).fetchall()
if unitest:
return unitest[0][0]
return 0
def formatFTView(item: Products):
value= "FTView SE/ME" if item.value=="FTView_SE_ME" else item.value
return value
main.py
from Schemas.schemas import Products
from typing import List
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session
from Entity import model
from Schemas import schemas
from Tools import query
from Tools.database import get_db
from sqlalchemy import and_
import uvicorn
app = FastAPI(title="Project Health",version="1.0")
@app.get("/users/",response_model=List[schemas.BuildInfo])
async def read_users(db: Session = Depends(get_db)):
users = query.get_all(db,model.BuildInfo,model.BuildInfo.version=="6.20.00")
return users
@app.post("/items/")
async def read_users(item: schemas.SelectItem,db: Session = Depends(get_db)):
users = query.filter(db,item.ID)
return users
@app.get("/ciduration/{product}")
async def duration(product: Products,db: Session = Depends(get_db)):
durations = query.duration(db,product)
value= query.formatFTView(product)
return {<!-- -->"product_name":value,"duration":durations}
@app.get("/cisuccseerate/{product}")
async def cisuccseerate(product: Products,db: Session = Depends(get_db)):
successrate = query.seccessrate(db,product)
value= query.formatFTView(product)
return {<!-- -->"product_name":value,"rate":successrate}
@app.get("/unitestrate/{product}")
async def unitestrate(product: Products,db: Session = Depends(get_db)):
unitest = query.unitestrate(db,product)
value= query.formatFTView(product)
return {<!-- -->"product_name":value,"rate":unitest}
if __name__=="__main__":
uvicorn.run(app,host="127.0.0.1",port=8080)