您好,登錄后才能下訂單哦!
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"}%
查看數據:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。