当前位置 : 主页 > 软件教程 > 其它软件 >

什么是FastAPI异步框架?(全面了解)

来源:互联网 收集:自由互联 发布时间:2022-07-22
一:FastAPI框架 1.FastAPI是应该用于构建API的现代,快速(高性能)的 web 框架,使用Python 3.6+ 并基于标准的 Python 类型提示。 关键性: 快速: 可与NodeJS和Go并肩的极高性能(归功于Starlette和Py
一:FastAPI框架
1.FastAPI是应该用于构建API的现代,快速(高性能)的 web 框架,使用Python 3.6+ 并基于标准的 Python 类型提示。

关键性:

  • 快速: 可与NodeJS和Go并肩的极高性能(归功于Starlette和Pydantic)。最快的Python web框架之一。
  • 高效编码: 提高功能开发速度约200% 至 300%。
  • 更少的bug: 减少约 40% 的人为(开发者) 导致错误。
  • 智能: 极佳的编辑器支持。处处皆可自动补全,减少调式时间。
  • 简单: 设计的易于使用和学习,阅读文档的时间。
  • 简短: 使代码重复最小化。通过不同的参数声明实现丰富功能。bug更少。
  • 健壮: 生产可用级别的代码。还有自动生成的交互式文档。
  • 标准化: 基于(并完全兼容)API的相关开放标准: OpenAPI(以前被称为 Swagger)和 JSON Schema。

img

1.Starlette,Pydantic 与 FastAPI 的关系
  • Python 的类型提示 type hints
  • Pydantic 是一个基于 Python 类型提示来定义数据验证,序列化和文档(使用JSON模式)库
Pydantic : 前端给后端传数据/定义的数据类型,嵌套用什么格式嵌套
  • Starlette 是一种轻量级的 ASGI 框架/工具包,是构建高性能Asyncio 服务的理想选择。
  • 一个轻量级、低复杂度的 HTTP Web 框架。
  • WebSocket 支持。
  • 正在进行的后台任务。
  • 启动和关闭事件。
  • 测试客户端建立在requests.
  • CORS、GZip、静态文件、流响应。
  • 会话和 Cookie 支持。
  • 100% 的测试覆盖率。
  • 100% 类型注释代码库。
  • 很少有硬依赖。
  • asynciotrio后端兼容。
  • 与独立基准相比,整体表现出色。

image

2.ASGI 和 WSGI的区别
ASGI 协议
WSGI 协议

Uvicorn 与 uWSGI 为web服务器

image

二:Pydantic的基本用法(BaseModel) 1.Pydantic的基本用法
class User(BaseModel):
    id: int  # 没有默认值。就是必填字段
    name: str = "john Snow"  # 有默认值,就是选填字段
    signup_ts: Optional[datetime] = None  # 时间 "有默认值,选填字段"
    friends: List[int] = []  #  列表中元素是int类型或者可以直接转换成int类型

# 传值 类型= 字典
external_data = {
    "id": "123",
    "signup_ts": "2022-12-22 12:22",
    "friends": [1, 2, "3"]  # "3" 是可以int("3")的
}

user = User(**external_data)
print(user.id, user.friends)  # 实例化后调用属性
print(repr(user.signup_ts))
print(user.dict())

"
123 [1, 2, 3]
datetime.datetime(2022, 12, 22, 12, 22)
{'id': 123, 'name': 'john Snow', 'signup_ts': datetime.datetime(2022, 12, 22, 12, 22), 'friends': [1, 2, 3]}
"
2.效验失败处理
print("---效验失败处理---")
try:
    User(id=1, signup_ts=datetime.today(), friends=[1, 2, "not number"])
except ValidationError as e:
    print(e.json())

"
[
  {
    "loc": [
      "friends",
      2
    ],
    "msg": "value is not a valid integer",
    "type": "type_error.integer"
  }
]
"
3.模型类的属性和方法
print(user.dict())  # 转换成字典
print(user.json()) 
print(user.copy())  # 这里代表浅拷贝
print(User.parse_obj(obj=external_data))  # 解析
print(User.parse_raw('{"id": "123","signup_ts": "2022-12-22 12:22", "friends": [1, 2, 3]}'))

"
{'id': 123, 'name': 'john Snow', 'signup_ts': datetime.datetime(2022, 12, 22, 12, 22), 'friends': [1, 2, 3]}
{"id": 123, "name": "john Snow", "signup_ts": "2022-12-22T12:22:00", "friends": [1, 2, 3]}
id=123 name='john Snow' signup_ts=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
id=123 name='john Snow' signup_ts=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
id=123 name='john Snow' signup_ts=datetime.datetime(2022, 12, 22, 12, 22) friends=[1, 2, 3]
"
4.解析文件
path = Path('pydantic_tutorial.json')
path.write_text('{"id":"123", "signup_ts":"2020-12-22 12:22", "friends":[1, 2, "3"]}')
print(User.parse_file(path))

"
id=123 name='john Snow' signup_ts=datetime.datetime(2020, 12, 22, 12, 22) friends=[1, 2, 3]
"
5.解析(并打印出对应类型)
print(user.schema())
print(user.schema_json())
#
user_data = {"id": "error", "signup_ts": "2020-12-22 12 22", "friends": [1, 2, 3]}  # id必须是str
print(User.construct(**user_data))  # 不效验数据直接创建模型类,不建议在construct方法中传入未经验证的数据
#
print(User.__fields__.keys())  # 定义模型类的时候,所有字段都注明类型,字段顺序就不会乱。


"
{'title': 'User', 'type': 'object', 'properties': {'id': {'title': 'Id', 'type': 'integer'}, 'name': {'title': 'Name', 'default': 'john Snow', 'type': 'string'}, 'signup_ts': {'title': 'Signup Ts', 'type': 'string', 'format': 'date-time'}, 'friends': {'title': 'Friends', 'default': [], 'type': 'array', 'items': {'type': 'integer'}}}, 'required': ['id']}
{"title": "User", "type": "object", "properties": {"id": {"title": "Id", "type": "integer"}, "name": {"title": "Name", "default": "john Snow", "type": "string"}, "signup_ts": {"title": "Signup Ts", "type": "string", "format": "date-time"}, "friends": {"title": "Friends", "default": [], "type": "array", "items": {"type": "integer"}}}, "required": ["id"]}
name='john Snow' signup_ts='2020-12-22 12 22' friends=[1, 2, 3] id='error'
dict_keys(['id', 'name', 'signup_ts', 'friends'])
"
6.递归模型
class Sound(BaseModel):
    sound: str
class Dog(BaseModel):
    birthday: date
    weight: float = Optional[None]
    sound: List[Sound]  # 不同的狗有不同的叫声。递归模型(Recursive Model)就是指一个嵌套一个
dogs = Dog(birthday=date.today(), weight=6.66, sound=[{"sound": "wang wang ~"}, {"sound": "ying ying ~"}])
print(dogs.dict())


"
{'birthday': datetime.date(2022, 6, 9), 'sound': [{'sound': 'wang wang ~'}, {'sound': 'ying ying ~'}]}
"
7.ORM模型:从类实例创建符合ORM对象的模型
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

class CompanyOrm(Base):
    __tablename__ = 'companies'  # 表名
    id = Column(Integer, primary_key=True, nullable=False)
    public_key = Column(String(20), index=True, nullable=False, unique=True)
    name = Column(String(63), unique=True)
    domains = Column(ARRAY(String(255)))

class CompanyMode(BaseModel):
    id: int
    public_key: constr(max_length=20)   # constr = 限制
    name: constr(max_length=63)
    domains: List[constr(max_length=255)]

    class Config:  # 子类
        orm_mode = True

co_orm = CompanyOrm(
    id=123,
    public_key = 'foobar',
    name='Testing',
    domains=['example.com', 'imooc.com']
)
print(CompanyMode.from_orm(co_orm))


"
id=123 public_key='foobar' name='Testing' domains=['example.com', 'imooc.com']
"
上一篇:Python动态属性有什么用
下一篇:没有了
网友评论