您好,登录后才能下订单哦!
Django rest framework 是一套基于django框架编写restful风格API的组件
就是将复杂的数据结构json化,支持ORM和非ORM数据源的序列化
快速实现支持auth2和auth3的方式的权限验证
扩展了常规的HttpResquest和TemplateResponse
INSTALLED_APPS= [
…….
'rest_framework',
'app',
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'restful',
'USER': 'root',
'PASSWORD': '123465',
'HOST': 'local.dev',
'PORT': '3306',
}
}
from django.conf .urls import url, include
urlpatterns = [
path('admin/', admin.site.urls),
path(r'^test/', include('app.urls')),
]
from django.dbimport models
# Create your models here.
class Restful(models.Model):
name= models.CharField(max_length=30)
passwd = models.CharField(max_length=10)
def__str__(self):
returnself.name
python manage.py makemigrations
python manage.py migrate
from rest_frameworkimport serializers
from .models import Restful
class RestfulSerializer(serializers.ModelSerializer):
classMeta:
model = Restful
fields = ("id", "name", "passwd")
from django.shortcutsimport render
# Create your views here.
from rest_framework import status, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Restful
from .serializer import RestfulSerializer
class RestfulView(APIView):
defget(self, request, format=None):
data = Restful.objects.all()
serializer = RestfulSerializer(data, many=True)
returnResponse(serializer.data)
defpost(self, request, format=None):
serializer = RestfulSerializer(data=request.data)
ifserializer.is_valid():
serializer.save()
returnResponse(serializer.data, status=status.HTTP_201_CREATED)
else:
returnResponse(serializer.data, status=status.HTTP_400_BAD_REQUEST)
from django.conf.urlsimport url
from . import views
urlpatterns = [
url(r'^api/$', views.RestfulView.as_view(), name='restful'),
]
插入数据:
➜ ~ curl -X POST http://localhost:8000/test/api/ -d "name=jiangby&passwd=123456"
{"id":1,"name":"jiangby","passwd":"123456"}%
➜ ~ curl -X POST http://localhost:8000/test/api/ -d "name=test&passwd=123456"
{"id":2,"name":"test","passwd":"123456"}%
查看数据:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。