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"}%
查看数据:
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
本文题目:DjangoRESTframework-创新互联
网站URL:http://myzitong.com/article/cssggs.html