企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
rest_framework 官方网址http://www.django-rest-framework.org/ 备注:django=1.9.8 测试失败 django=1.11版本成功 **安装rest_framework ** `pip install djangorestframework` 环境必备库 ~~~ coreapi(1.32.0+) - 模式生成支持。 Markdown(2.1.0+) - Markdown支持可浏览的API。 django-filter(1.0.1+) - 过滤支持。 django-crispy-forms - 改进的HTML显示过滤。 django-guardian(1.1.1+) - 对象级权限支持。 ~~~ 如果没有,单独pip 安装 sttings文件增加app配置 `'rest_framework',` model文件 ~~~ # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class imgs(models.Model): tetle = models.CharField(max_length=100, verbose_name=u"名称") img = models.ImageField(upload_to="tt/%Y/%m", verbose_name=u"图片") url = models.URLField(verbose_name=u"地址") class Meta: verbose_name = u"图片测试" verbose_name_plural = verbose_name def __str__(self): return self.tetle ~~~ 创建serializers.py 相当于表单 ~~~ # _*_ coding=utf-8 _*_ __author__ = 'canmeng' #相当于表单 from rest_framework import serializers #from .models import imgs #第一种形式,自定义属性 class ImgSerializer(serializers.Serializer): tetle = serializers.CharField(required=True, max_length=100) url = serializers.CharField(required=True, max_length=200) img = serializers.CharField(required=True, max_length=200) #第二种形式,引入model # # class ImgSerModel(serializers.ModelSerializer): # class Meta: # model = imgs # fields = "__all__" 调用所有字段 # fields = ('tetle', 'img') ~~~ 创建view ~~~ # -*- coding: utf-8 -*- #api序列化 #from .serializers import ImgSerModel from .serializers import ImgSerializer from rest_framework.views import APIView from rest_framework.response import Response from .models import imgs class ImgsList(APIView): """ 图片列表 """ def get(self, request, format=None): ims = imgs.objects.all() ims_ser = ImgSerializer(ims, many=True) return Response(ims_ser.data) ~~~ 项目URL 配置 ~~~ from rest_framework.documentation import include_docs_urls from imgs.views import ImgsList urlpatterns = [ url(r'docs/', include_docs_urls(title="b")), url(r'api-auth/', include('rest_framework.urls')), url(r'tp/$', ImgsList.as_view(), name="tp") ] ~~~