DRF对Django请求响应做了技术升级 (2)

既然DRF能自动处理content type,那么也可以给URL指定具体的后缀格式,比如。具体添加步骤是,先给view增加1个可选参数format:

def snippet_list(request, format=None): def snippet_detail(request, pk, format=None):

再更新snippets/urls.py,添加format_suffix_patterns:

from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path('snippets/', views.snippet_list), path('snippets/<int:pk>', views.snippet_detail), ] urlpatterns = format_suffix_patterns(urlpatterns)

这并不是必须的,实际上也无需这么做。

测试API http :8000/snippets/ HTTP/1.1 200 OK ... [ { "id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly" }, { "id": 2, "title": "", "code": "print(\"hello, world\")\n", "linenos": false, "language": "python", "style": "friendly" } ]

跟之前的结果一样。再分别用form和json试试:

# POST using form data http --form POST :8000/snippets/ code="print(123)" { "id": 3, "title": "", "code": "print(123)", "linenos": false, "language": "python", "style": "friendly" } # POST using JSON http --json POST :8000/snippets/ code="print(456)" { "id": 4, "title": "", "code": "print(456)", "linenos": false, "language": "python", "style": "friendly" } API文档

DRF提供了可视化的API HTML文档,把API URL在浏览器中打开即可看到:

DRF对Django请求响应做了技术升级

东方说

最近测试开发和业务测试的话题频频出现在TesterHome论坛上,讨论激烈,我觉得从公司的角度来说,只会关注员工的产出有没有给公司带来价值,无论技术多厉害,不能创造价值终究是会优先被裁的。从个人的角度来说,只会业务测试的出路肯定是会越来越窄的,努力提高技术,辅助业务测试,同时提升效率,才是更好的发展方向。千万要谨慎选择只做纯测试工具,要依托于业务,让技术落地,在业务中发挥技术的价值,产生从业务到技术,从技术到业务的良好循环。当然,会技术是个大前提,对技术的学习不能停,比如Django REST framework。

参考资料:

https://www.django-rest-framework.org/tutorial/2-requests-and-responses/

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwgjyj.html