189 8069 5689

DjangoRESTframework

第1章 简介

Django rest framework 是一套基于django框架编写restful风格API的组件

创新互联是一家专注于成都网站建设、网站建设和四川主机托管的网络公司,有着丰富的建站经验和案例。

第2章 简单了解下都有哪些特点

2.1serializers(序列化)

就是将复杂的数据结构json化,支持ORM和非ORM数据源的序列化

2.2authentication(身份认证)

快速实现支持auth2和auth3的方式的权限验证

2.3request and response(请求与响应)

扩展了常规的HttpResquest和TemplateResponse

2.4viewset and routers(视图和路由)

第3章 开始一个简单的项目

3.1创建好Django项目后,修改settings文件

INSTALLED_APPS= [
    …….
    'rest_framework',
    'app',
]


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.MySQL',
        'NAME': 'restful',
        'USER': 'root',
        'PASSWORD': '123465',
        'HOST': 'local.dev',
        'PORT': '3306',
    }
}

 

3.2配置urls文件

from django.conf .urls import url, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path(r'^test/', include('app.urls')),
]

3.3编写model层:

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

3.4初始化数据库

python manage.py makemigrations

python manage.py migrate

3.5编写序列化模块:

from rest_frameworkimport serializers
from .models import Restful

class RestfulSerializer(serializers.ModelSerializer):
    classMeta:
        model = Restful
        fields = ("id", "name", "passwd")

3.6编写视图views.py

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)

3.7编写app路由urls.py:

from django.conf.urlsimport url
from import views

urlpatterns = [
    url(r'^api/$', views.RestfulView.as_view(), name='restful'),
]

3.8进行测试:

插入数据:

➜  ~ 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"}%

查看数据:

Django REST framework


本文名称:DjangoRESTframework
网站链接:http://cdxtjz.cn/article/jdoicc.html

其他资讯