好吧,如果一定要RESTFUL的DJANGO

时间:2020-12-08 06:23:13

看看人家写的VIEWSET,

然后用REQUESTS测试一下。

from rest_framework import viewsets
from rest_framework.decorators import detail_route
from display.models import Alert
from serializers import UserSerializer, AlertSerializer
from django.contrib.auth.models import User
from rest_framework import permissions
from api.permissions import IsOwnerOrReadOnly

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)

class AlertViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.

    Additionally we also provide an extra `highlight` action.
    """
    queryset = Alert.objects.all()
    serializer_class = AlertSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
# coding=utf8
import urllib
import urllib2
import base64
import json
import requests

#GET
url = 'http://127.0.0.1:8000/api/alert/'
response = requests.get(url)
print "GET output:"
print response.text

#PUT

url = 'http://127.0.0.1:8000/api/alert/4/'
data = {'data_source':'TEST18 DB', 'alarm_level':8, 'owner':'admin',
        'alarm_topic':'出错啦', 'alarm_type':'DB'}
response = requests.put(url, data=data, auth=('admin','admin'))
print "PUT output:"
print response.text

#POST
url = 'http://127.0.0.1:8000/api/alert/'
data = {'data_source':'TEST DB', 'alarm_level':8, 'owner':'admin',
        'alarm_topic':'出错啦', 'alarm_type':'DB'}
response = requests.post(url, data=data, auth=('admin','admin'))

print "POST output:"
print response.text

#HEAD
url = 'http://127.0.0.1:8000/api/alert/9/'
response = requests.head(url)
print "HEAD output:"
print response.text

#OPTIONS
url = 'http://127.0.0.1:8000/api/alert/9/'
response = requests.options(url)
print "OPTIONS output:"
print response.text

'''
#DELETE
url = 'http://127.0.0.1:8000/api/alert/8/'
response = requests.delete(url, auth=('admin','admin'))
print "DELETE output:"
print response.text

'''

来个图爽爽

好吧,如果一定要RESTFUL的DJANGO