标签:cbv ber name 字符串 ade cfile 基于 sel cap
-如果请求地址是/user,路由中配置成‘/user/‘,匹配不上,中间件会自动在后面加 / 再去匹配,能匹配成功,重定向到/user/,加了 / 还匹配不上,就报错 -django.middleware.common.CommonMiddleware
pip3 install djangorestframework
注册app
INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘app01.apps.App01Config‘,
# rest_framework就是一个app
‘rest_framework‘
]
由于restful_framework使用的CBV的方式,所以路由如下:
#drf 实现的api
url(r‘^users/‘, views.DrfText.as_view()),
#需要类
from rest_framework.views import APIView
#类继承APIView ,用于自动生成
from rest_framework.response import Response
#rest_framework 自定义返回对象的方法
#自定义的声明类
#基本CBV相同
class DrfTest(APIView):
def get(self, request, *args, **kwargs):
# request是封装之后的request了,原来的request是request._request
print(type(request._request))
print(type(request))
# 问:当前request对象并没有这些属性,但是能打印出来,为什么?
# getattr
print(request.method)
print(request.POST)
print(request.GET)
# 就相当于:
print(request.query_params)
print(request._request.GET)
response = {‘status‘: 100, ‘errors‘: None}
response[‘users‘] = user_list
# 用drf的Response,可以通过请求客户端来判断返回数据格式是什么样的
return Response(response)
# return JsonResponse(response)
?
def post(self, request, *args, **kwargs):
# post 提交的数据,urlencode,formdate,json格式,都能从data中取出来
name = request.data.get(‘name‘)
# request.FILES
print(name)
return HttpResponse(‘ok‘)
发送到请求方法的返回值,只能是符合json语法的字符串,对象是无法发送到前端的。所以需要将对象进行序列化
from django.db import models
?
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=32)
price = models.IntegerField()
pub_date = models.DateField()
publish = models.ForeignKey("Publish")
authors = models.ManyToManyField("Author")
?
def __str__(self):
return self.title
?
def test(self):
return self.title+str(self.price)
?
?
class Publish(models.Model):
name = models.CharField(max_length=32)
email = models.EmailField()
?
def __str__(self):
return self.name
?
?
?
class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
#
def __str__(self):
return self.name
?
from rest_framework import serializers
class BookSerializers(serializers.Serializer):
#id 是依据数据表中的字段名称,不可以随意变更
id = serializers.CharField()
#当需要变更字段名称的话,设定source =‘字段名‘
name = serializers.CharField(source=‘title‘)
price = serializers.CharField()
#也可以通过models的对应的数据类中定义属性方法,自定义数据
xxx = serializers.CharField(source=‘test‘)
publish = serializers.CharField()
#也可以自定义字段,使用方法自动生成,SerializerMethodField(),才能使用
publish_dic = serializers.SerializerMethodField()
#方法名为 get_自定义字段名
def get_publish_dic(self,obj):
return {‘id‘:obj.publish.pk,‘name‘:obj.publish.name}
from app01 import models
from app01.Myser import BookSerializers
class Books(APIView):
def get(self,request,*args,**kwargs):
response = {‘status‘:100,‘errors‘:None}
book_list = models.Book.objects.all()
print(book_list)
bookser= BookSerializers(book_list,many=True)
response[‘books‘] = bookser.data
return Response(response)
?
?
class Book(APIView):
def get(self,request,id):
response = {‘status‘: 100, ‘errors‘: None}
book = models.Book.objects.filter(pk=id).first()
bookser = BookSerializers(book,many=False)
response[‘book‘] = bookser.data
return Response(response)
标签:cbv ber name 字符串 ade cfile 基于 sel cap
原文地址:https://www.cnblogs.com/msj513/p/10405787.html