Django rest framework?是一套基于django框架編寫restful風(fēng)格API的組件
創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站建設(shè)、網(wǎng)站建設(shè)和四川主機(jī)托管的網(wǎng)絡(luò)公司,有著豐富的建站經(jīng)驗和案例。
就是將復(fù)雜的數(shù)據(jù)結(jié)構(gòu)json化,支持ORM和非ORM數(shù)據(jù)源的序列化
快速實現(xiàn)支持auth2和auth3的方式的權(quán)限驗證
擴(kuò)展了常規(guī)的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'),
]
插入數(shù)據(jù):
???~ 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"}%
查看數(shù)據(jù):
分享標(biāo)題:DjangoRESTframework
網(wǎng)頁路徑:http://jinyejixie.com/article22/jdoicc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、網(wǎng)站維護(hù)、網(wǎng)站設(shè)計公司、App開發(fā)、營銷型網(wǎng)站建設(shè)、App設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)