跳转至

视图

API 参考:Views

视图层是 SRF 的请求处理核心。GenericAPIView 负责动作分发、Schema 校验、权限、过滤与分页,几个 CRUD Mixin 组合成可直接使用的 ViewSet。机制说明与完整示例见 ViewSet 与 动作与装饰器。

from srf.views import BaseViewSet, GenericAPIView, ReadOnlyModelViewSet, action

动作分发

as_view(actions) 把 HTTP 方法映射到视图方法。通常由 SanicRouter.register() 自动构建映射;手动调用 app.add_route() 时才需要自己传入:

from sanic import Sanic

from srf.views import BaseViewSet

app = Sanic("demo")


class BookViewSet(BaseViewSet):
    queryset = Book.all()  # Tortoise QuerySet
    schema = BookSchema  # Pydantic 模型


app.add_route(
    BookViewSet.as_view({"get": "list", "post": "create"}),
    "/books",
)

actions 的键是小写 HTTP 方法,值是要调用的方法名。未在映射中出现的方法不会注册到路由;运行期取不到对应方法时抛出 405 Method Not Allowed。

PUT 与 PATCH

当前 put 和 patch 都映射到 update,且 update 按完整 Schema 校验请求体。两者语义上的区分(完整更新 / 部分更新)尚未实现。

视图基类

GenericAPIView 是所有视图的公共基类;另外三个组合类只是把 CRUD Mixin 预先拼好。

GenericAPIView

GenericAPIView(*args, **kwargs)

Bases: HTTPMethodView

Base class for all SRF views: schema validation, permissions, filtering and pagination.

Attributes:

Name Type Description
schema type[BaseModel] | None

Pydantic model class used to validate request data and serialize responses. Set it on the subclass or override get_schema().

queryset QuerySet | None

Tortoise QuerySet the view operates on. Set it on the subclass or override get_queryset().

filter_class list[type[BaseFilter]]

Filter classes applied in list(). Defaults to settings.DEFAULT_FILTERS when not declared on the class.

permission_classes Iterable[type[BasePermission]]

Permission classes checked before the handler runs. Defaults to settings.DEFAULT_PERMISSION_CLASSES.

pagination_class type[BasePagination]

Pagination class used by list(). Defaults to settings.PAGINATION_CLASS.

search_fields list[str] | dict[str, str]

Fields matched by SearchFilter via ?search= (icontains). Accepts a list of ORM field names or a dict of {alias: orm_field}.

filter_fields list[str] | dict[str, str]

Fields allowed for exact filtering by QueryParamFilter / JsonLogicFilter. Accepts a list or a dict of {param: orm_field}.

ordering_fields list[str] | dict[str, str]

Fields allowed for ordering via ?ordering=. Use -name for descending order.

get_schema
get_schema() -> type[BaseModel]

Return the Pydantic model class for this view action.

Override this method (or set class attribute schema) like DRF's get_serializer_class / serializer_class. Uses self.action and self.request set by as_view — do not pass request as a parameter.

get_queryset
get_queryset() -> QuerySetType

Prioritize using get_queryset, followed by queryset

filter_queryset
filter_queryset(queryset)

The filter class should be obtained first from view class or, if not, from settings

get_object async
get_object(pk)

Get an orm model instance.

normalize_pk
normalize_pk(pk, model: type[Model] | None = None)

Coerce the route parameter pk to the model's pk type before it reaches a query.

Sanic always hands <pk> over as str. Querying with the raw str only works by implicit conversion, and a non-integer pk against an int field raises ValueError deep inside Tortoise (a 500). Convert up front: a pk that cannot be parsed can never match a row, so respond 404.

check_permissions async
check_permissions(request: Request)

Check view-level permissions. Permission classes are used as callables on the class (no instantiation). Supports both sync and async has_permission().

check_object_permissions async
check_object_permissions(obj: Model)

Check object-level permissions. Permission classes are used as callables on the class (no instantiation). Supports both sync and async has_object_permission().

get_current_user
get_current_user(request: Request)

Retrieve the currently logged-in user

as_view classmethod
as_view(actions: dict[str, str] | None = None)

Construct a view function for registering with Sanic.

actions maps an HTTP method to a view method, for example `{"get": "list"}or{"get": "retrieve"}. Callers pass this map explicitly:SanicRouter.registerbuilds it, andadd_routecallers pass it themselves. Sanic's default route method is GET; that does not chooselistversusretrieve``.

三个组合类的差异:

类 提供的动作
BaseViewSet create / list / retrieve / update / destroy
ReadOnlyModelViewSet list / retrieve
CreateAndReadOnlyModelViewSet create / list / retrieve

BaseViewSet

BaseViewSet(*args, **kwargs)

Bases: GenericAPIView, ModelMixin

Full-featured ViewSet: all five CRUD actions plus schema validation, permissions, filtering and pagination from GenericAPIView.

ReadOnlyModelViewSet

ReadOnlyModelViewSet(*args, **kwargs)

Bases: GenericAPIView, ListModelMixin, RetrieveModelMixin

Read-only ViewSet exposing only list and retrieve.

CreateAndReadOnlyModelViewSet

CreateAndReadOnlyModelViewSet(*args, **kwargs)

Bases: GenericAPIView, CreateModelMixin, ListModelMixin, RetrieveModelMixin

ViewSet exposing create, list and retrieve — no update or delete.

CRUD Mixins

每个 Mixin 只提供一个动作,需要更细粒度的组合时可以直接继承。

CreateModelMixin

create async
create(request: Request, *args, **kwargs) -> HTTPResponse

Create an orm model instance.

perform_create async
perform_create(sch_model: BaseModel) -> TorModel

sch_model: instance of BaseModel

create 的行为:

  • 请求体不是 JSON 时返回 400。
  • 使用 schema 以 strict=True 校验输入,随后调用 perform_create()。
  • 输出使用同一个 Schema 序列化,返回 201。
  • 数据库唯一约束冲突(IntegrityError)转换为 409 TargetObjectAlreadyExist。

RetrieveModelMixin

retrieve async
retrieve(request: Request, pk, *args, **kwargs) -> JSONResponse

Get an orm model instance.

查询对象时先做主键类型归一化,再执行对象级权限检查;对象不存在返回 404。

UpdateModelMixin

update async
update(request: Request, pk, *args, **kwargs) -> JSONResponse

Update an orm model instance.

perform_update async
perform_update(sch_model: BaseModel, orm_model: Model) -> TorModel

sch_model: instance of BaseModel orm_model: instance of TorModel

perform_update() 只写入请求中显式提供的字段(exclude_unset=True),并跳过主键字段。

DestroyModelMixin

destroy async
destroy(request: Request, pk, *args, **kwargs) -> HTTPResponse

Delete an orm model instance.

perform_destroy async
perform_destroy(orm_model: Model) -> None

orm_model: instance of TorModel

删除成功后返回 204 No Content。

ListModelMixin

list async
list(request: Request, *args, **kwargs) -> JSONResponse

Get a list orm model instance.

list 的执行顺序是:get_queryset() → filter_queryset() → pagination_class.from_queryset() → paginate()。响应结构见 分页。

ModelMixin

Bases: CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin, ListModelMixin

Convenience bundle of all five CRUD mixins (create, retrieve, update, destroy, list).

动作装饰器

action 把 ViewSet 中的普通方法声明为一个独立接口,SanicRouter 会自动发现并注册。

action

action(*, detail: bool = False, methods: Sequence[str] = ('GET',), url_path: str | None = None, url_name: str | None = None, **kwargs) -> Callable

Mark a method as a viewset action.

:param methods: List of HTTP methods allowed for this action :param detail: If True, action requires a pk parameter. If False, action is on collection. :param url_path: Custom URL path for this action, default to be the name of the method :param url_name: Custom URL name for this action, default to be the name of the method

validate_request 用于装饰函数式视图(例如 srf.auth 中的 register、verify_email)。ViewSet 的请求校验由 as_view() 统一处理,不需要再叠加这个装饰器。

validate_request

validate_request(show_errors: bool = False)

导出清单

from srf.views import ... 可用以下名字:

from srf.views import (
    BaseViewSet,
    CreateAndReadOnlyModelViewSet,
    CreateModelMixin,
    DestroyModelMixin,
    GenericAPIView,
    ListModelMixin,
    ModelMixin,
    ReadOnlyModelViewSet,
    RetrieveModelMixin,
    UpdateModelMixin,
    action,
)

validate_request 不在导出清单中,需从 srf.views.decorators 导入。