在 Dango REST 框架中使用类型注解来验证/反序列化请求参数。
Use this project instead: drf-typed.
It includes everything this project does, plus it includes typed features for serializers and helpful type stubs.
This project extends Django Rest Framework to allow use of Python's type annotations for automatically validating and casting view parameters. This pattern makes for code that is easier to read and write. View inputs are individually declared, not buried inside all-encompassing request objects. Meanwhile, you get even more out of type annotations: they can replace repetitive validation/sanitization code.
More features:
min_value/max_value for numbersemail, uuid and ipv4/6; use Python's native Enum for "choices" validationQuick example:
from rest_typed_views import typed_api_view
@typed_api_view(["GET"])
def get_users(registered_on: date = None, groups: List[int] = None, is_staff: bool = None):
print(registered_on, groups, is_staff)GET /users/registered/?registered_on=2019-03-03&groups=4,5&is_staff=yes
Status Code: 200
date(2019, 3, 3) [4, 5] TrueGET /users/?registered_on=9999&groups=admin&is_staff=maybe
:no_entry_sign: Status Code: 400 ValidationError raised
{
"registered_on": "'9999' is not a valid date",
"groups": "'admin' is not a valid integer",
"is_staff": "'maybe' is not a valid boolean"
}pip install drf-typed-viewsYou can add type annotation-enabled features to either ViewSet methods or function-based views using the typed_action and typed_api_view decorators. They take the exact same arguments as Django REST's api_view and action decorators.
For many cases, you can rely on implicit behavior for how different parts of the request (URL path variables, query parameters, body) map to the parameters of a view function/method.
The value of a view parameter will come from...
Unless a default value is given, the parameter is required and a ValidationError will be raised if not set.
urlpatterns = [
url(r"^(?P[\w+])/restaurants/", search_restaurants)
]
from rest_typed_views import typed_api_view
# Example request: /chicago/restaurants?delivery=yes
@typed_api_view(["GET"])
def search_restaurants(city: str, rating: float = None, offers_delivery: bool = None):
restaurants = Restaurant.objects.filter(city=city)
if rating is not None:
restaurants = restaurants.filter(rating__gte=rating)
if offers_delivery is not None:
restaurants = restaurants.filter(delivery=offers_delivery)In this example, city is required and must be its string. Its value comes from the URL path variable with the same name. The other parameters, rating and offers_delivery, are not part of the path parameters and are assumed to be query parameters. They both have a default value, so they are optional.
…In this example, city will again be populated using the URL path variable. The booking parameter is annotated using a supported complex schema class (Pydantic), so it's assumed to come from the request body, which will be read in as JSON, used to hydrate the Pydantic BookingSchema and then validated. If validation fails a ValidationError will be raised.
For more advanced use cases, you can explicitly declare how each parameter's value is sourced from the request -- from the query parameters, path, body or headers -- as well as define additional validation rules. You import a class named after the request element that is expected to hold the value and assign it to the parameter's default.
from rest_typed_views import typed_api_view, Query, Path
@typed_api_view(["GET"])
def list_documents(year: date = Path(), title: str = Query(default=None)):
# ORM logic here...In this example, year is required and must come from the URL path and title is an optional query parameter because the default is set. This is similar to Django REST's serializer fields: passing a default implies that the filed is not required.
from rest_typed_views import typed_api_view, Header
@typed_api_view(["GET"])
def get_cache_header(cache: str = Header()):
# ORM logic here...In this example, cache is required and must come from the headers.
You can use the request element class (Query, Path, Body, Header) to set additional validation constraints. You'll find that these keywords are consistent with Django REST's serializer fields.
from rest_typed_views import typed_api_view, Query, Path
@typed_api_view(["GET"])
def search_restaurants(
year: date = Path(),
rating: int = Query(default=None, min_value=1, max_value=5)
):
# ORM logic here...
@typed_api_view(["GET"])
def get_document(id: str = Path(format="uuid")):
# ORM logic here...
@typed_api_view(["GET"])
def search_users(
email: str = Query(default=None, format="email"),
ip_address: str = Query(default=None, format="ip"),
):
# ORM logic here...View a full list of supported types and additional validation rules.
Similar to how source is used in Django REST to control field mappings during serialization, you can use it to specify the exact path to the request data.
from pydantic import BaseModel
from rest_typed_views import typed_api_view, Query, Path
class Document(BaseModel):
title: str
body: str
"""
POST
{
"strict": false,
"data": {
"title": "A Dark and Stormy Night",
"body": "Once upon a time"
}
}
"""
@typed_api_view(["POST"])
def create_document(
strict_mode: bool = Body(source="strict"),
item: Document = Body(source="data")
):
# ORM logic here...You can also use dot-notation to source data multiple levels deep in the JSON payload.
For the basic case of list validation - validating types within a comma-delimited string - declare the type to get automatic validation/coercion:
from rest_typed_views import typed_api_view, Query
@typed_api_view(["GET"])
def search_movies(item_ids: List[int] = [])):
print(item_ids)
# GET /movies?items_ids=41,64,3
# [41, 64, 3]But you can also specify min_length and max_length, as well as the delimiter and specify additional rules for the child items -- think Django REST's ListField.
Import the generic Param class and use it to set the rules for the child elements:
from rest_typed_views import typed_api_view, Query, Param
@typed_api_view(["GET"])
def search_outcomes(
scores: List[int] = Query(delimiter="|", child=Param(min_value=0, max_value=100))
):
# ORM logic ...
@typed_api_view(["GET"])
def search_message(
recipients: List[str] = Query(min_length=1, max_length=10, child=Param(format="email"))
):
# ORM logic ...You probably won't need to access the request object directly, as this package will provide its relevant properties as view arguments. However, you can include it as a parameter annotated with its type and it will be injected:
from rest_framework.request import Request
from rest_typed_views import typed_api_view
@typed_api_view(["GET"])
def search_documens(request: Request, q: str = None):
# ORM logic ...Often, it's useful to validate a combination of query parameters - for instance, a start_date shouldn't come after an end_date. You can use complex schema object (Pydantic or Marshmallow) for this scenario. In the example below, Query(source="*") is instructing an instance of SearchParamsSchema to be populated/validated using all of the query parameters together: request.query_params.dict().
from marshmallow import Schema, fields, validates_schema, ValidationError
from rest_typed_views import typed_api_view
class SearchParamsSchema(Schema):
start_date = fields.Date()
end_date = fields.Date()
@validates_schema
def validate_numbers(self, data, **kwargs):
if data["start_date"] >= data["end_date"]:
raise ValidationError("end_date must come after start_date")
@typed_api_view(["GET"])
def search_documens(search_params: SearchParamsSchema = Query(source="*")):
# ORM logic ...You can apply some very basic access control by applying some validation rules to a view parameter sourced from the CurrentUser request element class. In the example below, a ValidationError will be raised if the request.user is not a member of either super_users or admins.
from my_pydantic_schemas import BookingSchema
from rest_typed_views import typed_api_view, CurrentUser
@typed_api_view(["POST"])
def create_booking(
booking: BookingSchema,
user: User = CurrentUser(member_of_any=["super_users", "admins"])
):
# Do something with the request.userRead more about the Current User request element class.
As an alternative to Django REST's serializers, you can annotate views with Pydantic models or Marshmallow schemas to have their parameters automat
暂无开放 Issues,或尚未同步最近议题。