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