视图
API 参考:Views¶
视图层是 SRF 的请求处理核心。GenericAPIView 负责动作分发、Schema 校验、权限、过滤与分页,几个 CRUD Mixin 组合成可直接使用的 ViewSet。机制说明与完整示例见 ViewSet 与 动作与装饰器。
动作分发¶
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 ¶
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 |
queryset |
QuerySet | None
|
Tortoise QuerySet the view operates on. Set it on the subclass or
override |
filter_class |
list[type[BaseFilter]]
|
Filter classes applied in |
permission_classes |
Iterable[type[BasePermission]]
|
Permission classes checked before the handler runs. Defaults
to |
pagination_class |
type[BasePagination]
|
Pagination class used by |
search_fields |
list[str] | dict[str, str]
|
Fields matched by |
filter_fields |
list[str] | dict[str, str]
|
Fields allowed for exact filtering by |
ordering_fields |
list[str] | dict[str, str]
|
Fields allowed for ordering via |
get_schema ¶
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.
filter_queryset ¶
The filter class should be obtained first from view class or, if not, from settings
normalize_pk ¶
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 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-level permissions. Permission classes are used as callables on the class (no instantiation). Supports both sync and async has_object_permission().
as_view
classmethod
¶
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 ¶
Bases: GenericAPIView, ModelMixin
Full-featured ViewSet: all five CRUD actions plus schema validation,
permissions, filtering and pagination from GenericAPIView.
ReadOnlyModelViewSet ¶
Bases: GenericAPIView, ListModelMixin, RetrieveModelMixin
Read-only ViewSet exposing only list and retrieve.
CreateAndReadOnlyModelViewSet ¶
Bases: GenericAPIView, CreateModelMixin, ListModelMixin, RetrieveModelMixin
ViewSet exposing create, list and retrieve — no update or delete.
CRUD Mixins¶
每个 Mixin 只提供一个动作,需要更细粒度的组合时可以直接继承。
CreateModelMixin ¶
create 的行为:
- 请求体不是 JSON 时返回
400。 - 使用
schema以strict=True校验输入,随后调用perform_create()。 - 输出使用同一个 Schema 序列化,返回
201。 - 数据库唯一约束冲突(
IntegrityError)转换为409 TargetObjectAlreadyExist。
查询对象时先做主键类型归一化,再执行对象级权限检查;对象不存在返回 404。
UpdateModelMixin ¶
perform_update() 只写入请求中显式提供的字段(exclude_unset=True),并跳过主键字段。
DestroyModelMixin ¶
删除成功后返回 204 No Content。
ListModelMixin ¶
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() 统一处理,不需要再叠加这个装饰器。
导出清单¶
from srf.views import ... 可用以下名字:
from srf.views import (
BaseViewSet,
CreateAndReadOnlyModelViewSet,
CreateModelMixin,
DestroyModelMixin,
GenericAPIView,
ListModelMixin,
ModelMixin,
ReadOnlyModelViewSet,
RetrieveModelMixin,
UpdateModelMixin,
action,
)
validate_request 不在导出清单中,需从 srf.views.decorators 导入。