This article introduces Detailed Django rest_framework implement RESTful API, Xiao Bian feel very good, now for everyone to share, but also to be a reference. Come and see, to follow the small series together
First, what is REST
Resources for REST is the most obvious feature, the resource is a way to look at the server, the server will be seen as a resource by a number of discrete components. Each resource is on a server named abstraction. Because the resource is an abstract concept, it can represent not only a file server file system, a database table, and so on specific things, how to be more abstract abstract design can be a resource, as long as the imagination allows and client application developers can understand.
And object-oriented design similar terms as the core resource is organized, the first concern is a noun. A resource may be identified by one or more URI. URI is both the name of the resource, but also the address of a resource on the Web. Customers interested in a resource-side application can interact with their resources by URI. A different set of operations for the same resource. Resources on the server is a named abstraction, the term resources is at the core to the organization, the first concern is a noun.
REST requirements must be performed various operations on resources through a unified interface. For each resource can only perform a limited set of operations. (Method 7 HTTP: GET / POST / PUT / DELETE / PATCH / HEAD / OPTIONS)
Second, what is RESTful
REST API framework in line with the design of the API.
The concept much to say, in particular by following a simple example to see how the Django framework is to achieve RESTful.
Three, rest_framework module
1. Use pip command to download: pip3 install djangorestframework
2. Create a Django project
3. Create a apitest APP
- d cd : \ Tool # to switch to the Tool directory
- python manage.py startapp apitest #创建apitest应用
目录结构:
4.打开settings.py,增加一段配置:
- INSTALLED_APPS = [
- 'django.contrib.admin',
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'apitest', #添加apitest app
- 'rest_framework', #添加rest_framework
- ]
- #增加一段REST_FRAMEWORK配置
- REST_FRAMEWORK = {
- # Use Django's standard `django.contrib.auth` permissions,
- # or allow read-only access for unauthenticated users.
- 'DEFAULT_PERMISSION_CLASSES': [
- 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
- ],
- 'DEFAULT_RENDERER_CLASSES': (
- 'rest_framework.renderers.JSONRenderer',
- ),
- 'DEFAULT_PARSER_CLASSES': (
- 'rest_framework.parsers.JSONParser',
- )
- }
5.在apitest目录下新建一个api.py,让我们来写一些测试代码:
- #coding=utf-8
- from rest_framework import permissions
- from rest_framework.response import Response
- from rest_framework.decorators import api_view, permission_classes
- from django.views.decorators.csrf import csrf_exempt
- @csrf_exempt
- @api_view(http_method_names=['post']) #只允许post
- @permission_classes((permissions.AllowAny,))
- def inventory(request):
- parameter = request.data
- id = parameter['data']
- if id == 1:
- data = 'There are three dogs'
- elif id == 2:
- data = 'There are two dogs'
- else:
- data = 'nothing'
- return Response({'data':data})
6.在urls.py添加刚刚创建的api路由:
- urlpatterns = [
- path('admin/', admin.site.urls),
- path('food/', api.inventory), #添加api中inventory路由
- ]
上面配置好了之后本地调试下,输入命令:python manage.py runserver 8000
好了,服务器端代码已经写完。我们可以通过约定好的名词food来获取或者更改资源。然后写个小脚本测试下上面的接口:
- import requests
- url= 'http://127.0.0.1:8000/food/'
- data = {'data':2}
- h=requests.post(url,json=data)
- print(h.text)
输出:
测试OK