用django构建api的简单助手库。
djapi的Python项目详细描述
用django构建api的简单助手库。 不是为了实现rest。
需求:Python2.7+和Django1.8+。安装:
$ pip install djapi
设置
大多数库不需要配置,但如果要使用令牌身份验证:
INSTALLED_APPS+=['djapi.authtoken']DJAPI_AUTH=['djapi.authtoken.use_token']# Or add default django auth for e.g. debugging purposesDJAPI_AUTH=['djapi.authtoken.use_token','djapi.auth.use_contribauth']
用法
importdjapiasapiposts_qs=api.queryset(Post).filter(visible=True) \ .values_but('visible','modified_on') \ .values_add(category='category__title') \ .map_types(Image,lambdaimg:img.url)@api.catch(Post.DoesNotExist,status=404)defpost(request,pk):returnapi.json(posts_qs.get(pk=pk))defposts_list(request):returnapi.json(api.paginate(request,posts_qs,per_page=20))@api.auth_required@api.user_passes_test(lambdauser:user.is_staff)@api.validate(PostForm)defposts_create(request,post):post.created_by=request.userpost.save()returnapi.json(201,created=post.pk)posts=api.route(get=posts_list,post=posts_create)