实现一个 restful接口
https://zhuanlan.zhihu.com/p/157999491
@app.get("/items/{item_id}")
async def get_item(item_id):
return {"item_id": item_id}
# http://127.0.0.1:5555/items/1
if __name__ == "__main__":
uvicorn.run("fastapi_demo:app", host="0.0.0.0", po
https://blog.csdn.net/qq_33154865/article/details/116334539
验证请求数据
1、直接在请求url对应的函数的参数里验证
2、通过 BaseModel 定义模型验证
实现方式:函数的参数后 用 冒号 + 验证类型 实现;
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
from typing import Optional
@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
return {"item_id": item_id, "q": q}
class RequestItem(BaseModel):
id = 3
biz_ext: str
work_name: str
work_type: str
url: str
platform: str
extra_info: str
@app.post("/ezrealer/myproject/add-users")
async def add_users(userid:int,request_items:List[RequestItem]):
fastapi 的返回
fastapi 项目结构
1、sql_app包
└── sql_app
├── __init__.py
├── crud.py
├── database.py
├── main.py
├── models.py
└── schemas.py
database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:123456@127.0.0.1:3306/test"
# echo=True表示引擎将用repr()函数记录所有语句及其参数列表到日志
engine = create_engine(
SQLALCHEMY_DATABASE_URL, encoding='utf8', echo=True
)
# SQLAlchemy中,CRUD是通过会话进行管理的,所以需要先创建会话,
# 每一个SessionLocal实例就是一个数据库session
# flush指发送到数据库语句到数据库,但数据库不一定执行写入磁盘
# commit是指提交事务,将变更保存到数据库文件中
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 创建基本映射类
Base = declarative_base()
models.py
from sqlalchemy import Boolean, Column, Integer, String
from database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String(32), unique=True, index=True)
hashed_password = Column(String(32))
is_active = Column(Boolean, default=True)
schemas.py
from pydantic import BaseModel
class UserBase(BaseModel):
email: str
class UserCreate(UserBase):
"""
请求模型验证:
email:
password:
"""
password: str
class User(UserBase):
"""
响应模型:
id:
email:
is_active
并且设置orm_mode与之兼容
"""
id: int
is_active: bool
class Config:
orm_mode = True
curd.py
from sqlalchemy.orm import Session
import models, schemas
# 通过id查询用户
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
# 新建用户
def db_create_user(db: Session, user: schemas.UserCreate):
fake_hashed_password = user.password + "notreallyhashed"
db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
db.add(db_user)
db.commit() # 提交保存到数据库中
db.refresh(db_user) # 刷新
return db_user
fastapi 中使用 mysql
1、没做 MVC, 把各个模块都写到一起
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.responses import JSONResponse, Response
from fastapi import status
from typing import List
import uvicorn
from sqlalchemy import Boolean, Column, Integer, String,DateTime
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import datetime
password = '123456'
SQLALCHEMY_DATABASE_URI:str = f'mysql+pymysql://root:{password}@127.0.0.1:3306/dbname'
engine = create_engine(SQLALCHEMY_DATABASE_URI,pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False,autoflush=False,bind=engine)
session = SessionLocal()
Base = declarative_base()
class User(Base):
__tablename__ = "tbl_user"
id = Column(Integer,primary_key=True,index=True,autoincrement=True)
username= Column(String(500))
Base.metadata.create_all(bind=engine)
app = FastAPI()
def resp_200() -> Response:
return JSONResponse(
status_code=status.HTTP_200_OK,
content={
'code': 200,
'message': "success",
}
)
@app.post("/ezrealer/myproject/add-users")
async def add_users(request_items:List[RequestItem]):
exist_users = session.query(User).with_entities(User.username).all()
user = User()
user.name = "ez"
session.add(user) # 添加到session
session.commit() # 提交到数据库
exist_worknames.add(download_task.work_name)
session.close()
return resp_200()
if __name__ == "__main__":
uvicorn.run("api_add_users:app", host="0.0.0.0", port=8080,reload=False, debug=False)
restful命名规范
http://restful.p2hp.com/
使用名词来表示资源
使用正斜杠(/)表示层次关系
不要在URI中使用尾部正斜杠(/)
使用连字符( - )来提高URI的可读性
不要使用下划线(_)
在URI中使用小写字母
不要使用文件扩展名
切勿在URI中使用CRUD函数名称
使用查询组件过滤URI集合