微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

python 之路,Django rest framework 初探

摘自 金角大王  https://www.cnblogs.com/alex3714/articles/7131523.html

Django rest framework介绍

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

安装

Requirements

REST framework requires the following:

  • Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
  • Django (1.8, 1.9, 1.10, 1.11)

The following packages are optional:

Installation

Install using pip, including any optional packages you want...

1
2
3
pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

...or clone the project from github.

1
git clone [email protected]:encode/django-rest-framework.git

Add 'rest_framework' to your INSTALLED_APPS setting.

1
2
3
4
INSTALLED_APPS = (
    ...
    'rest_framework',
)

If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file.

1
2
3
4
urlpatterns = [
    ...
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Note that the URL path can be whatever you want, but you must include 'rest_framework.urls' with the 'rest_framework'namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.

 

快速上手实例

Let's take a look at a quick example of using REST framework to build a simple model-backed API.

We'll create a read-write API for accessing @R_27_4045@ion on the users of our project.

Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK. Start off by adding the following to your settings.py module:

1
2
3
4
5
6
7
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'
    ]
}

Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS.

We're ready to create our API Now. Here's our project's root urls.py module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
 
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url''username''email''is_staff')
 
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
 
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
 
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

You can Now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.

 

Django视图中使用rest 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from rest_framework import serializers
from assets import models
 
 
 
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
 
from rest_framework import status
from rest_framework.response import Response
 
 
class EventLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.EventLog
        fields = ('id','user','name''event_type''detail''asset''date''memo')
 
 
 
 
 
@api_view(['GET''POST'])
def eventlog_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        eventlogs = models.EventLog.objects.all()
        serializer = EventLogSerializer(eventlogs, many=True)
        return Response(serializer.data)
 
    elif request.method == 'POST':
        print("request",request.data)
        serializer = EventLogSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
 
#@api_view(['GET', 'POST','PUT'])
@csrf_exempt
def eventlog_detail(request, pk):
    """
    Retrieve, update or delete a code eventlog.
    """
    try:
        eventlog_obj = models.EventLog.objects.get(pk=pk)
    except models.EventLog.DoesNotExist:
        return HttpResponse(status=404)
 
    if request.method == 'GET':
        serializer = EventLogSerializer(eventlog_obj)
        return JsonResponse(serializer.data)
 
    elif request.method == 'PUT':
        print(request)
        data = JSONParser().parse(request)
        serializer = EventLogSerializer(eventlog_obj, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)
 
    elif request.method == 'DELETE':
        eventlog_obj.delete()
        return HttpResponse(status=204)

  

更多请看 http://www.django-rest-framework.org/ 

Django rest framework介绍

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

安装

Requirements

REST framework requires the following:

  • Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
  • Django (1.8, 1.9, 1.10, 1.11)

The following packages are optional:

Installation

Install using pip, including any optional packages you want...

1
2
3
pip install djangorestframework
pip install markdown       # Markdown support for the browsable API.
pip install django-filter  # Filtering support

...or clone the project from github.

1
git clone [email protected]:encode/django-rest-framework.git

Add 'rest_framework' to your INSTALLED_APPS setting.

1
2
3
4
INSTALLED_APPS = (
    ...
    'rest_framework',
)

If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file.

1
2
3
4
urlpatterns = [
    ...
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Note that the URL path can be whatever you want, but you must include 'rest_framework.urls' with the 'rest_framework'namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.

 

快速上手实例

Let's take a look at a quick example of using REST framework to build a simple model-backed API.

We'll create a read-write API for accessing @R_27_4045@ion on the users of our project.

Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK. Start off by adding the following to your settings.py module:

1
2
3
4
5
6
7
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'
    ]
}

Don't forget to make sure you've also added rest_framework to your INSTALLED_APPS.

We're ready to create our API Now. Here's our project's root urls.py module:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
 
# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url''username''email''is_staff')
 
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
 
# Routers provide an easy way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
 
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

You can Now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.

 

Django视图中使用rest 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from rest_framework import serializers
from assets import models
 
 
 
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
 
from rest_framework import status
from rest_framework.response import Response
 
 
class EventLogSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.EventLog
        fields = ('id','user','name''event_type''detail''asset''date''memo')
 
 
 
 
 
@api_view(['GET''POST'])
def eventlog_list(request):
    """
    List all snippets, or create a new snippet.
    """
    if request.method == 'GET':
        eventlogs = models.EventLog.objects.all()
        serializer = EventLogSerializer(eventlogs, many=True)
        return Response(serializer.data)
 
    elif request.method == 'POST':
        print("request",request.data)
        serializer = EventLogSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
 
#@api_view(['GET', 'POST','PUT'])
@csrf_exempt
def eventlog_detail(request, pk):
    """
    Retrieve, update or delete a code eventlog.
    """
    try:
        eventlog_obj = models.EventLog.objects.get(pk=pk)
    except models.EventLog.DoesNotExist:
        return HttpResponse(status=404)
 
    if request.method == 'GET':
        serializer = EventLogSerializer(eventlog_obj)
        return JsonResponse(serializer.data)
 
    elif request.method == 'PUT':
        print(request)
        data = JSONParser().parse(request)
        serializer = EventLogSerializer(eventlog_obj, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data)
        return JsonResponse(serializer.errors, status=400)
 
    elif request.method == 'DELETE':
        eventlog_obj.delete()
        return HttpResponse(status=204)

  

更多请看 http://www.django-rest-framework.org/ 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐