django rest框架的函数装饰器,用于指定和约束api参数。
django-rest-params的Python项目详细描述
django rest参数
函数decorator来指定和验证api调用的参数。 无效参数将自动返回有用的错误消息; 已验证的参数作为kwargs传递给包装的函数。
pip install django-rest-params==1.0.2
几个例子
指定参数类型,并检查它们是否在可接受的范围内:
fromdjango_rest_params.decoratorsimportparams@api_view(['GET'])@params(latitude=float,latitude__gte=-90.0,latitude__lte=90.0,longitude=float,longitude__gte=-180.0,longitude__lte=180.0)defget_something(request,latitude,longitude):# If latitude/longitude are missing or out of range, user will get an error message.# If we get here, we know they're validpass
使用默认值创建可选参数。django rest params也支持post params:
@api_view(['POST'])@params(offset=int,offset__default=0)defpaged_api_call(request,offset):# if offset isn't specified, default value is usedpass
django rest params与视图集和请求函数一起工作。
classShirtsViewSet(viewsets.GenericViewSet):@params(colors=('red','blue','green','yellow'),colors__many=True,colors__optional=True,colors__name='color_filter')defget_shirts(self,request,colors):# Handle API calls like these:# /shirts?color_filter=red __name lets you use a function param name different from the API param name# /shirts?color_filter=yellow,blue __many lets you pass multiple values# /shirts __optional will set colors to None if it isn't specified# /shirts?color_filter=black ERROR! This will return an error stating black is invalid, and listing the valid optionspass
选项
类型
指定参数的类型:
latitude=float
- 有效选项是:
- 内景
- 浮动
- bool(1/true视为true,0/false视为false;这不区分大小写)
- str/unicode
- tuple/list/set/frozenset(将被视为有效选项列表)
- django模型子类(在这种情况下,参数将被视为该模型的pk)
gt/lt/gte/lte
自动检查参数是否在特定范围内。对float、int或model pk有效,它们都进行数值比较。
latitude__gte=-90.0latitude__lte=90.0
长度lt/gt/lte/gte/eq
仅对str params有效。检查str的长度
description__length__lt=256country_code__length__eq=2
可选
latitude__optional=True# same as latitude__default=None
默认值为false;如果设置为true,则将检查此参数的有效性(例如,如果未通过gte检查,则仍将返回400)。 但如果未指定,则将作为none传递给包装函数。
默认值
sort_by=('messages_count','most_recent')sort_by__default='messages_count'
表示此参数是可选的。 如果未指定此参数,请为其指定默认值。
姓名
默认情况下,我们将查找与kwargs同名的param,例如
user_id=User# User is a Django model. Look for user_id param, fetch corresponding User, pass to wrapped fn as user_id
但有时在本地调用这样的参数“user”更有意义,因此您可以这样做:
user=User,user__name='user_id'# look for user_id, assign to user
许多
users=int# param 'users=1' is ok, 'users=1,2' is notusers__many=True# param 'users=1,2' will return tuple of (1, 2), 'users=1' will return (1)
允许用户(可选)将参数指定为csv(get)或array(json post) 如果many==true,则不管是否只有一个参数,参数都将作为元组返回
延迟
user__deferred=True
默认情况下,django rest params将检索这样的对象:
User.objects.only('id').get(id=user_id)# all fields except for 'id' are deferred
通常,这是比较可取的,因为我们通常不需要从数据库中获取整个对象,而且它比这样做要快得多。 通过将“延迟”设置为false,django rest params将对象检索调用更改为:
User.objects.get(id=user_id)# All fields are fetched
字段
category=Category# by default, do Category.get(id=category)category__field='name'# instead, do Category.get(name=category)
仅适用于Django型号。默认情况下,我们将参数视为id;相反,您可以将其视为其他内容,例如“name”
方法
传递此参数的有效方法。对于post/put请求,默认为“post”,对于所有其他请求,默认为“get”
user__method='GET'# GET onlyuser__method=('GET','POST')# allow either source
额外定制
您可以通过在Django设置模块中添加“django-RestyPARAMS”DICT来调整某些行为:
DJANGO_REST_PARAMS:{'TRUE_VALUES':('1','true'),# tuple of case-insensitive string values we'll accept as True for a param of type bool.'FALSE_VALUES':('0','false'),# string values that are considered false}
测试
运行(相当广泛的)单元测试:
make test
模拟类用于模拟django模型/管理器/django rest框架请求,因此这些测试实际上不需要在django应用程序中运行。