Opinionated set of utilities on top of FastAPI
See GitHub Project Roadmap.
To install just Contrib (without mongodb, pytz, ujson):
$ pip install fastapi_contrib
To install contrib with mongodb support:
$ pip install fastapi_contrib[mongo]
To install contrib with ujson support:
$ pip install fastapi_contrib[ujson]
To install contrib with pytz support:
$ pip install fastapi_contrib[pytz]
To install contrib with opentracing & Jaeger tracer:
$ pip install fastapi_contrib[jaegertracing]
To install everything:
$ pip install fastapi_contrib[all]
To use Limit-Offset pagination:
from fastapi import FastAPI
from fastapi_contrib.pagination import Pagination
from fastapi_contrib.serializers.common import ModelSerializer
from yourapp.models import SomeModel
app = FastAPI()
class SomeSerializer(ModelSerializer):
class Meta:
model = SomeModel
@app.get("/")
async def list(pagination: Pagination = Depends()):
filter_kwargs = {}
return await pagination.paginate(
serializer_class=SomeSerializer, **filter_kwargs
)
Subclass this pagination to define custom default & maximum values for offset & limit:
class CustomPagination(Pagination):
default_offset = 90
default_limit = 1
max_offset = 100
max_limit = 2000
To use State Request ID Middleware:
from fastapi import FastAPI
from fastapi_contrib.common.middlewares import StateRequestIDMiddleware
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(StateRequestIDMiddleware)
To use Authentication Middleware:
from fastapi import FastAPI
from fastapi_contrib.auth.backends import AuthBackend
from fastapi_contrib.auth.middlewares import AuthenticationMiddleware
app = FastAPI()
@app.on_event('startup')
async def startup():
app.add_middleware(AuthenticationMiddleware, backend=AuthBackend())
Define & use custom permissions based on FastAPI Dependency framework:
from fastapi import FastAPI
from fastapi_contrib.permissions import BasePermission, PermissionsDependency
class TeapotUserAgentPermission(BasePermission):
def has_required_permissions(self, request: Request) -> bool:
return request.headers.get('User-Agent') == "Teapot v1.0"
app = FastAPI()
@app.get(
"/teapot/",
dependencies=[Depends(
PermissionsDependency([TeapotUserAgentPermission]))]
)
async def teapot() -> dict:
return {"teapot": True}
Setup uniform exception-handling:
from fastapi import FastAPI
from fastapi_contrib.exception_handlers import setup_exception_handlers
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_exception_handlers(app)
If you want to correctly handle scenario when request is an empty body (IMPORTANT: non-multipart):
from fastapi import FastAPI
from fastapi_contrib.routes import ValidationErrorLoggingRoute
app = FastAPI()
app.router.route_class = ValidationErrorLoggingRoute
Or if you use multiple routes for handling different namespaces (IMPORTANT: non-multipart):
from fastapi import APIRouter, FastAPI
from fastapi_contrib.routes import ValidationErrorLoggingRoute
app = FastAPI()
my_router = APIRouter(route_class=ValidationErrorLoggingRoute)
To correctly show slashes in fields with URLs + ascii locking:
from fastapi import FastAPI
from fastapi_contrib.common.responses import UJSONResponse
app = FastAPI()
@app.get("/", response_class=UJSONResponse)
async def root():
return {"a": "b"}
Or specify it as default response class for the whole app (FastAPI >= 0.39.0):
from fastapi import FastAPI
from fastapi_contrib.common.responses import UJSONResponse
app = FastAPI(default_response_class=UJSONResponse)
To setup Jaeger tracer and enable Middleware that captures every request in opentracing span:
from fastapi import FastAPI
from fastapi_contrib.tracing.middlewares import OpentracingMiddleware
from fastapi_contrib.tracing.utils import setup_opentracing
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_opentracing(app)
app.add_middleware(OpentracingMiddleware)
To setup mongodb connection at startup and never worry about it again:
from fastapi import FastAPI
from fastapi_contrib.db.utils import setup_mongodb
app = FastAPI()
@app.on_event('startup')
async def startup():
setup_mongodb(app)
Use models to map data to MongoDB:
from fastapi_contrib.db.models import MongoDBModel
class MyModel(MongoDBModel):
additional_field1: str
optional_field2: int = 42
class Meta:
collection = "mymodel_collection"
mymodel = MyModel(additional_field1="value")
mymodel.save()
assert mymodel.additional_field1 == "value"
assert mymodel.optional_field2 == 42
assert isinstance(mymodel.id, int)
Or use TimeStamped model with creation datetime:
from fastapi_contrib.db.models import MongoDBTimeStampedModel
class MyTimeStampedModel(MongoDBTimeStampedModel):
class Meta:
collection = "timestamped_collection"
mymodel = MyTimeStampedModel()
mymodel.save()
assert isinstance(mymodel.id, int)
assert isinstance(mymodel.created, datetime)
Use serializers and their response models to correctly show Schemas and convert from JSON/dict to models and back:
from fastapi import FastAPI
from fastapi_contrib.db.models import MongoDBModel
from fastapi_contrib.serializers import openapi
from fastapi_contrib.serializers.common import Serializer
from yourapp.models import SomeModel
app = FastAPI()
class SomeModel(MongoDBModel):
field1: str
@openapi.patch
class SomeSerializer(Serializer):
read_only1: str = "const"
write_only2: int
not_visible: str = "42"
class Meta:
model = SomeModel
exclude = {"not_visible"}
write_only_fields = {"write_only2"}
read_only_fields = {"read_only1"}
@app.get("/", response_model=SomeSerializer.response_model)
async def root(serializer: SomeSerializer):
model_instance = await serializer.save()
return model_instance.dict()
POST-ing to this route following JSON:
{"read_only1": "a", "write_only2": 123, "field1": "b"}
Should return following response:
{"id": 1, "field1": "b", "read_only1": "const"}
Suppose we have this directory structure:
-- project_root/
-- apps/
-- app1/
-- models.py (with MongoDBModel inside with indices declared)
-- app2/
-- models.py (with MongoDBModel inside with indices declared)
Based on this, your name of the folder with all the apps would be "apps". This is the default name for fastapi_contrib package to pick up your structure automatically. You can change that by setting ENV variable CONTRIB_APPS_FOLDER_NAME (by the way, all the setting of this package are overridable via ENV vars with CONTRIB_ prefix before them).
You also need to tell fastapi_contrib which apps to look into for your models. This is controlled by CONTRIB_APPS ENV variable, which is list of str names of the apps with models. In the example above, this would be CONTRIB_APPS=["app1","app2"].
Just use create_indexes function after setting up mongodb:
from fastapi import FastAPI
from fastapi_contrib.db.utils import setup_mongodb, create_indexes
app = FastAPI()
@app.on_event("startup")
async def startup():
setup_mongodb(app)
await create_indexes()
This will scan all the specified CONTRIB_APPS in the CONTRIB_APPS_FOLDER_NAME for models, that are subclassed from either MongoDBModel or MongoDBTimeStampedModel and create indices for any of them that has Meta class with indexes attribute:
models.py:
import pymongo
from fastapi_contrib.db.models import MongoDBTimeStampedModel
class MyModel(MongoDBTimeStampedModel):
class Meta:
collection = "mymodel"
indexes = [
pymongo.IndexModel(...),
pymongo.IndexModel(...),
]
This would not create duplicate indices because it relies on pymongo and motor to do all the job.
This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.
opencv calib3d——主要包含相机标定和立体视觉等功能,例如物体位姿估计、三维重建、摄像头标定等。 core——核心功能模块,主要包含opencv库的基础结构和基本操作,例如opencv基本数据结构、绘图函数、数组操作相关函数、动态数据结构等。 dnn——深度学习模块,主要包括构建神经网络、加载序列化网络模型等。 features2d——功能主要为处理图像特征点,例如特征检测、描述与匹配
由于在学习图像识别中的特征点检测中,需要用到Surf和Sift算法,但是这两个算法在OpenCV 3.1.0的Release版本中并不存在,因为他们是存放在opencv_contrib目录下面的未稳定功能模块,所以如果我们想要使用这个目录的功能,就需要自己重新进行OpenCV的编译。 1.下载OpenCV安装包:https://sourceforge.net/projects/opencvlibr
创建数据库连接 from fastapi import FastAPI from tortoise.contrib.fastapi import register_tortoise from app.config import config class GetDB(object): def _get_orm_base_conf(self, apps: dict) -> dict:
概述 fastapi是一个很优秀的框架,但是缺少一个合适的orm,官方代码里面使用的是sqlalchemy,异步也是使用的这个。但是我这边看到有tortoise-orm这个异步orm框架,不知道效率如何,这里先学习,之后做一个性能测试比较一下。 整个框架非常接近django,如果我没写的地方,要么是和django差不多,要么是没这功能。 fastapi引入 在main.py文件里面引入如下代码:
使用FastAPI对YOLO模型进行http封装 前言 在实际生产中,深度学习模型往往需要部署在服务器中,前端通过接口来调用模型推理过程,并获得返回值。 FastAPI是一种快速、高性能的Web框架。本文中使用FastAPI对目标检测模型进行了http封装,前端只需要将图片转为base64传入,生成json格式的检测结果返回。 一、模型推理过程 检测部分使用的opencv dnn调用darknet
Tortoise-orm的使用 该数据模型参照Django的数据模型,因此使用上与Django的数据模型高度相似。 !!! 注意,tortoise-orm是异步框架。 官方文档: https://tortoise-orm.readthedocs.io/en/latest/index.html 安装tortoise pip install tortoise 安装数据模型迁移工具 pip ins
更改sqlite为mysql from tortoise import Tortoise import asyncio async def init(): user = 'root' password = '123456' db_name = 'test' await Tortoise.init( #指定mysql信息 db_url=
1、在服务器下载python并安装,注意勾选"Add Python to environment variables"选项自动配置环境 2、在pycharm下方控制台终端(Terminal)中输入 pip3 freeze > requirements.txt 导出依赖文件requirements.txt,位于根目录下 2、将所有py文件和requirements.txt文件复制粘贴到服务器上(最好