5.3.通过drf的apiview实现api
drf的优势
The Web browsable API is a huge usability win for your developers.
Authentication policies including packages for OAuth1a and OAuth2.
Serialization that supports both ORM and non-ORM data sources.
Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
Extensive documentation, and great community support.
Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
goods/serializer.py
from rest_framework import serializers
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=100)
market_price = serializers.IntegerField(default=0.0)
goods/views.py
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import Goods
from goods.serializer import GoodsSerializer
class GoodsListView(APIView):
"""
获取商品列表
"""
def get(self, request, format=None):
goods = Goods.objects.all()[:10]
serializer = GoodsSerializer(goods, many=True)
return Response(serializer.data)
goods/urls.py
from django.urls import path
from goods.views import GoodsListView
urlpatterns = [
path('', GoodsListView.as_view(), name='goods_list'),
]
mo_shop/urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework.documentation import include_docs_urls
urlpatterns = [
...
path('goods/', include('goods.urls')),
]
Last updated
Was this helpful?