快用Django REST framework写写API吧

快用Django REST framework写写API吧,第1张

概述Django默认是前后端绑定的,提供了Template和Form,现在流行前后端分离项目,Python大佬坐不住了,于是便有了Django REST framework:https://github.

Django默认是前后端绑定的,提供了Template和Form,现在流行前后端分离项目,Python大佬坐不住了,于是便有了Django REST framework:https://github.com/tomchristie

官网:https://www.django-rest-framework.org/

Django REST framework(简称DRF)是个Python技术栈的后端框架,用来构建RESTful API。

RESTful API

REST,是指REpresentational State Transfer,有个精辟的解释什么是RESTful:

看URL就知道要什么看Method就知道干什么看Status Code就知道结果如何

良好的RESTful API设计的基本原则是:

返回JsON严禁乱用状态码处理好分页返回具体的实体数据而不是返回通用的JsON数据请求对象有默认值创建项目

接下来我们使用DRF创建一个简单的API,允许管理员查看和编辑用户和组。

先创建名为tutorial的project和名为quickstart的app:

# 创建项目目录mkdir tutorialcd tutorial# 创建Python虚拟环境python -m venv env# 激活虚拟环境env\Scripts\activate.bat  # Mac中使用`source env/bin/activate`# 在虚拟环境中安装Django和Django REST frameworkpip install djangopip install djangorestframework# 创建project,注意最后有个“.”,表示在当前目录创建django-admin startproject tutorial .cd tutorial# 创建appdjango-admin startapp quickstartcd ..

创建好的目录结构如下:

$ pwd<some path>/tutorial$ find .../manage.py./tutorial./tutorial/__init__.py./tutorial/quickstart./tutorial/quickstart/__init__.py./tutorial/quickstart/admin.py./tutorial/quickstart/apps.py./tutorial/quickstart/migrations./tutorial/quickstart/migrations/__init__.py./tutorial/quickstart/models.py./tutorial/quickstart/tests.py./tutorial/quickstart/vIEws.py./tutorial/settings.py./tutorial/urls.py./tutorial/wsgi.py

一般不会把app放到project里面,这里是为了避免命名冲突。

接着同步数据库:

python manage.py migrate

然后创建一个超级管理员,密码password123

python manage.py createsuperuser --email [email protected] --username admin
Serializers

序列化是指把数据库模型转换为JsON。新建模块tutorial/quickstart/serializers.py

from django.contrib.auth.models import User,Groupfrom rest_framework import serializersclass UserSerializer(serializers.HyperlinkedModelSerializer):    class Meta:        model = User        fIElds = ['url','username','email','groups']class GroupSerializer(serializers.HyperlinkedModelSerializer):    class Meta:        model = Group        fIElds = ['url','name']
VIEws

视图用来接受Web请求并且返回Web响应。打开tutorial/quickstart/vIEws.py,添加代码:

from django.contrib.auth.models import User,Groupfrom rest_framework import vIEwsetsfrom rest_framework import permissionsfrom tutorial.quickstart.serializers import UserSerializer,GroupSerializerclass UserVIEwSet(vIEwsets.ModelVIEwSet):    """    API endpoint that allows users to be vIEwed or edited.    """    queryset = User.objects.all().order_by('-date_joined')    serializer_class = UserSerializer    permission_classes = [permissions.IsAuthenticated]class GroupVIEwSet(vIEwsets.ModelVIEwSet):    """    API endpoint that allows groups to be vIEwed or edited.    """    queryset = Group.objects.all()    serializer_class = GroupSerializer    permission_classes = [permissions.IsAuthenticated]
URLs

配置路由,打开tutorial/urls.py,添加代码:

from django.urls import include,pathfrom rest_framework import routersfrom tutorial.quickstart import vIEwsrouter = routers.DefaultRouter()router.register(r'users',vIEws.UserVIEwSet)router.register(r'groups',vIEws.GroupVIEwSet)# Wire up our API using automatic URL routing.# Additionally,we include login URLs for the browsable API.urlpatterns = [    path('',include(router.urls)),path('API-auth/',include('rest_framework.urls',namespace='rest_framework'))]

因为这里用的不是vIEw而是vIEwsets,所以可以自动生成API的URLconf,只需要注册class即可。

也可以不用vIEwsets,用vIEw,再自定义API URL。

Pagination

分页用来控制每页返回多少数据,在tutorial/settings.py中添加:

REST_FRAMEWORK = {    'DEFAulT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination','PAGE_SIZE': 10}
Settings

tutorial/settings.py中,把'rest_framework'添加到INSTALLED_APPS

INSTALLED_APPS = [    ...    'rest_framework',]
测试API

启动项目:

python manage.py runserver

访问http://127.0.0.1:8000/users/,点击右上角用超管登录,即可看到:

东方说

本文是Django REST framework系列的开篇,内容参考的是官网的Tutorial。学了Django再看DRF,思路清晰多了,虽然我代码能力不强,但总是在追求规范和标准,难道是因为做测试的职业病么?

终于修复了从博客园复制粘贴到公众号代码块自动换行没有滚动条的问题,F12看了才知道有个样式被覆盖了,加上这句就搞定了:

#topics .postbody pre {    white-space: pre !important;}

参考资料:

https://www.django-rest-framework.org/tutorial/quickstart/

http://www.ruanyifeng.com/blog/2014/05/restful_api.html

总结

以上是内存溢出为你收集整理的快用Django REST framework写写API吧全部内容,希望文章能够帮你解决快用Django REST framework写写API吧所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1214222.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存