标签:建模 snippet max status 返回 ash register title .com
Python (3.6.2)
Django (1.11.5)
djangorestframework (3.6.4)
mkdir drf-test
cd drf-test
django-admin.py startproject drfTest
cd drfTest/
python manage.py startapp api
编辑 drtTest/setting.py 文件,在 INSTALLED_APPS 添加新应用。
INSTALLED_APPS = (
...
‘rest_framework‘,
‘api.apps.ApiConfig‘,
)
打开 drtTest/models.py 文件,创建一个简单 Product 模型,字段包括 created、name、describe、price、isDelete。
class Product(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=100, default=‘‘)
describe = models.CharField(max_length=500, default=‘‘)
price = models.FloatField()
isDelete = models.BooleanField(default=False)
class Meta:
ordering = (‘created‘,)
模型迁移,并同步数据库。
python manage.py makemigrations api
python manage.py migrate
序列化器可以把模型转换成需要返回的 json、xml 类型数据。在 api 文件下创建 serializers.py 文件。
from rest_framework import serializers
from snippets.models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = (‘id‘, ‘created‘, ‘name‘, ‘describe‘, ‘price‘, ‘isDelete‘)
创建 api/urls.py 文件,用 Router 自动处理 url 和 view 的连接。
from django.conf.urls import url, include
from api import views
# api url 配置
urlpatterns = [
]
在 drtTest/urls.py 中链接 api 应用程序的 url。
from django.conf.urls import url, include
from api import views
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^‘, include(‘api.urls‘)),
]
编写视图有很多种方式,下面使用比较简单的两种:
from rest_framework.views import APIView
from django.http import JsonResponse
# Create your views here.
class GetMessageView(APIView):
# get 请求
def get(self, request):
# 获取参数数据
get = request.GET
# 获取参数 a
a = get.get(‘a‘)
print(a)
# 返回信息
d = {
‘status‘: 1,
‘message‘: ‘success‘,
}
return JsonResponse(d)
api/urls.py 中配置 url
urlpatterns = [
url(r‘^test/$‘, views.GetMessageView.as_view()),
]
终端输入命令,开启服务。
python manage.py runserver
打开浏览器访问 http://127.0.0.1:8000/test/?a=100 接口返回
{"status": 1, "message": "success"}
终端输出
100
[15/Sep/2017 02:39:55] "GET /test/?a=100 HTTP/1.1" 200 35
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import detail_route, list_route
from api.serializers import ProductSerializer
from api.models import Product
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
@detail_route()
def changeName(self, request, *args, **kwargs):
get = request.GET
product = self.get_object()
product.name = get.get(‘newName‘)
product.save()
return Response(product.name)
@list_route()
def filterProducts(self, request):
products = Product.objects.filter(id__in=range(3))
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
api/urls.py 配置 url,使用 Router 自动处理 url 和 view 的连接。
from rest_framework.routers import DefaultRouter
from api.views import ProductViewSet
router = DefaultRouter()
router.register(r‘product‘, views.ProductViewSet)
# api url 配置
urlpatterns = [
url(r‘^‘, include(router.urls)),
url(r‘^test/$‘, views.GetMessageView.as_view()),
]
终端输入命令,开启服务。
python manage.py runserver
测试
获取产品列表: http://127.0.0.1:8000/product,没有的话在页面底部添加几条
通过产品 id 获取单个产品: http://127.0.0.1:8000/product/2/
修改产品名称: http://127.0.0.1:8000/product/2/changeName/?newName=qwer
获取 id 为 0-3 的产品: http://127.0.0.1:8000/product/filterProducts/
标签:建模 snippet max status 返回 ash register title .com
原文地址:https://www.cnblogs.com/caodneg7/p/9966029.html