Detailed Django rest_framework implement RESTful API

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

  1. d cd : \ Tool  # to switch to the Tool directory
  2. python manage.py startapp apitest #创建apitest应用

目录结构:

4.打开settings.py,增加一段配置:

  1. INSTALLED_APPS = [
  2. 'django.contrib.admin',
  3. 'django.contrib.auth',
  4. 'django.contrib.contenttypes',
  5. 'django.contrib.sessions',
  6. 'django.contrib.messages',
  7. 'django.contrib.staticfiles',
  8. 'apitest', #添加apitest app
  9. 'rest_framework', #添加rest_framework
  10. ]
  11.  
  12.  
  13. #增加一段REST_FRAMEWORK配置
  14. REST_FRAMEWORK = {
  15. # Use Django's standard `django.contrib.auth` permissions,
  16. # or allow read-only access for unauthenticated users.
  17. 'DEFAULT_PERMISSION_CLASSES': [
  18. 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
  19. ],
  20. 'DEFAULT_RENDERER_CLASSES': (
  21. 'rest_framework.renderers.JSONRenderer',
  22. ),
  23. 'DEFAULT_PARSER_CLASSES': (
  24. 'rest_framework.parsers.JSONParser',
  25. )
  26. }

5.在apitest目录下新建一个api.py,让我们来写一些测试代码:

  1. #coding=utf-8
  2. from rest_framework import permissions
  3. from rest_framework.response import Response
  4. from rest_framework.decorators import api_view, permission_classes
  5. from django.views.decorators.csrf import csrf_exempt
  6.  
  7. @csrf_exempt
  8. @api_view(http_method_names=['post']) #只允许post
  9. @permission_classes((permissions.AllowAny,))
  10. def inventory(request):
  11. parameter = request.data
  12. id = parameter['data']
  13. if id == 1:
  14. data = 'There are three dogs'
  15. elif id == 2:
  16. data = 'There are two dogs'
  17. else:
  18. data = 'nothing'
  19. return Response({'data':data})

6.在urls.py添加刚刚创建的api路由:

  1. urlpatterns = [
  2. path('admin/', admin.site.urls),
  3. path('food/', api.inventory), #添加api中inventory路由
  4. ]

上面配置好了之后本地调试下,输入命令:python manage.py runserver 8000

好了,服务器端代码已经写完。我们可以通过约定好的名词food来获取或者更改资源。然后写个小脚本测试下上面的接口:

  1. import requests
  2.  
  3. url= 'http://127.0.0.1:8000/food/'
  4. data = {'data':2}
  5. h=requests.post(url,json=data)
  6. print(h.text)

输出:

测试OK

Guess you like

Origin www.cnblogs.com/cheyunhua/p/11413456.html
Recommended