微小的decorator函数,使在~100 loc中使用django构建api更加容易

django-api-decorators的Python项目详细描述


django api装饰器

PyPI versionreleasescommits
dmdw

小的decorator函数使在~100 loc中使用django构建api变得更容易(比本自述文件短!)

目录

i.Installation
二。Usage
三、How it Works
四、Related Libraries
Backstory

安装

pip install django-api-decorators

预计您已经安装了django

兼容性

这最初用于Python2.7的旧Django1.5代码库。

应该与django 1.x-2.x和python 2.7-3.x一起使用

  • 可能也适用于django 0.95-0.99,没有检查任何早期版本的发行说明
  • 2to3表明没有什么可更改的,因此应该与python 3.x兼容
  • 尚未确认这是否适用于早期版本的python。

如果您有兼容性问题或已确认版本的兼容性,请提交PR或提交问题。


用法

@method_exclusive,每个docstring:Checks if request.method is equal to method, if not, returns a 405 not allowed response。示例:

fromdjango_api_decoratorsimportmethod_exlusive@method_exclusive('GET')defget_latest_public_posts(request):...

@require_auth,每个文档字符串:Checks if the request was made by an authenticated user, and if not, returns a 401 unauthorized response。示例:

fromdjango_api_decoratorsimportmethod_exclusive,require_auth@method_exclusive('GET')@require_authdefget_favorites(request):favs=request.user.favorites.all()...

可以对用户添加更多的授权检查,例如针对特定的用户类型, 在装饰器的顶部建造。例如:

fromfunctoolsimportwrapsfromdjango.httpimportHttpResponsefromdjango_api_decoratorsimportrequire_authdeftenant_exclusive(func):"""    Checks if the authenticated user is a tenant, and if not, returns a    401 unauthorized response    """@wraps(func)@require_authdeffunc_wrapper(request,*args,**kwargs):ifnotrequest.user.is_tenant():returnHttpResponse(status=401)returnfunc(request,*args,**kwargs)returnfunc_wrapper

@clean_form,每个docstring:Cleans the data in the POST or GET params using the form_class specified. Responds with a 400 bad request if the form is invalid with the errors specified in the form as JSON. Adds the cleaned data as a kwarg (cd) to the decorated function。示例:

fromdjango.shortcutsimportget_object_or_404fromdjango_api_decoratorsimportmethod_exclusive,clean_form,require_authfromposts.modelsimportPostfromposts.formsimportAddFavForm@method_exclusive('POST')@clean_form(AddFavForm)@require_authdefadd_fav(request,cd):post=get_object_or_404(Post,pk=cd['post_id'])request.user.favorites.add(post)...

@clean_forms,每个docstring:Cleans the data in the POST or GET params using the form_class specified. Responds with a 400 bad request if any of the forms are invalid with the errors specified in the form as JSON. Adds the cleaned data as a kwarg (cd_list) to the decorated function。示例:

fromdjango_api_decoratorsimportmethod_exclusive,clean_forms,require_authfromposts.modelsimportPostfromposts.formsimportCreatePostForm@method_exclusive('POST')@clean_forms(CreatePostForm,'posts')@require_authdefbulk_create_posts(request,cd_list):post_list=[]fordataincd_list:post_list.append(Post(user=request.user,cotent=data['content']))Post.objects.bulk_create(post_list)...

工作原理

所有的decorator当前只对request对象执行一个检查,如果请求无效,则提前返回,否则让下一个函数执行。其中一些函数在调用下一个函数时添加关键字参数,以便可以在其中使用解释过的数据(就像使用已清理的表单词典一样,这些词典是作为关键字kwargcd添加的)。

我鼓励您阅读源代码,因为它比本自述文件短:)

相关库

  • django-serializable-model
    • Django classes to make your models, managers, and querysets serializable, with built-in support for related objects in ~100 LoC

背景

这个库是在我开发Yorango的即席api并从mpa转换到spa时构建的。我不想为每个请求重复大量的身份验证、授权和验证代码,而是希望更多地使用装饰器或中间件来完成它。decorators将允许我们对无效请求使用正确的http状态代码进行早期返回。因此,请求代码变得更容易推理,保证它只在authz/authn/etc之后执行,并且更不容易出现意外错误,例如,由于忘记授权检查而导致的安全问题。@method_exclusive@require_auth和一些更多的特定于项目的装饰器就是出于这些需求而诞生的。

验证有点困难,因为我们在MPA中有许多现有的{a13},希望重用API中已经存在的类和验证代码,而不是重写,并且希望保持相同的习惯风格。Django REST Framework has the concept of "Validators",但它明显不同于django的标准Form接口,需要您购买drf的其他部分才能使用,比如序列化器。@clean_form就是为了满足这些需求而诞生的。后来@clean_forms被用来解决在一个api请求中有多个相同表单的情况(例如,用于批量创建),这与Django ^{}的工作方式有些相似,但要简单得多,并且需要的前端和后端代码耦合更少。

这些方法都在生产中得到了很好的结果,一些api方法只有一个decorator,而另一些方法有三个或更多decorator,例如:

@method_exclusive('POST')@clean_form(CreateBillsForm)@clean_forms(BillForm,'bills')@landlord_saas_exclusive@authorize_action(Listing,'listing_id')defcreate_bills(request,cd,cd_list,listing):...# bulk_create the new list of Billsbill_list=[]fordataincd_list:bill_list.append(Bill(listing=listing,price=data['price'],due_date=data['due_date'],))Bill.objects.bulk_create(bill_list)...

我一直想提取并开源这个以及其他各种有用的实用程序库,我在yorango做了,最后得到了机会!

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java Springboot数据JPA findByDate()   java是否可以有多个顶级树节点?   javahibernatehql。子查询中的多个   使用Twilio验证java Keyclope电话号码   java重写对象的toString()表示返回意外的符号   java Android最多每15分钟调用一个方法,否则使用保存的数据   在java swing中突出显示jeditorpane中的一些单词   java将时间戳转换为UTC时区   由于main中存在ArrayIndexOutOfBoundsException,导致java编译错误   java如何通过requestscope获取对象内部对象的值?   java访问安卓代码内的网站并检索生成的图像   java这种日期格式的模式是什么?   java解析包含超链接的xml字符串