重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
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"}%
查看数据: