使用Django开发REST 接口
from datetime import datetime
import json
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.views.generic import View
from .models import BookInfo
# Create your views here.
# http://127.0.0.1:8000/sixstart/weather/changsha/2020/
def weather(request,city,year):
# 天气视图函数
print(city)
print(year)
return HttpResponse("%s 在%s年的天气。" % (city,year))
#return HttpResponse("天气真好")
# http://127.0.0.1:8000/sixstart/q/?a=12&b=654&c=987
def chaxun(request):
# 查询参数
print(request.META['CONTENT_TYPE'])
print(request.GET.get('a')) # get去?问号后面的参数
print(request.GET.get('b')) # get去?问号后面的参数
print(request.GET.get('c')) # get去?问号后面的参数
print(request.GET.getlist('a'))
return HttpResponse("OK")
def get_body(request):
# post请求体
# body请求
a = request.POST.get("a")
b = request.POST.get("b")
alist = request.POST.get('a')
print(a)
print(b)
print(alist)
return HttpResponse("OK")
# 非表单数据
# 接受json格式
def get_body_json(request):
# get 方法没有请求体,可以是post put
# postman 请求 row 参数为json格式
json_str = request.body
req_dict = json.loads(json_str)
print(req_dict['a'])
print(req_dict['b'])
return HttpResponse("OK")
# HttpResponse
'''
视图在接收请求并处理后,必须返回HttpResponse对象或子对象。
HttpRequest对象由Django创建,HttpResponse对象由开发人员创建。
'''
def index(request):
return HttpResponse(content="响应体",content_type='text/html;charset=utf-8',status=200)
#可以通过HttpResponse对象中的set_cookie方法来设置cookie。
# HttpResponse.set_cookie(cookie名, value=cookie值, max_age=cookie有效期)
def demo_cookie(request):
response = HttpResponse("ok")
response.set_cookie('sixstar1','python1') # 临时cookie
response.set_cookie('sixstar2','python2',max_age=3600) # 有效期一小时
return response
def get_cookie(request):
cookie1 = request.COOKIES.get('sixstar1')
return HttpResponse(content=cookie1)
# 类视图
class DemoClass(View):
# get 请求
def get(self,request):
return render(request,'regist.html')
# 处理 post请求
def post(self,request):
return HttpResponse("这里实现逻辑处理")
class BooksApiView(View):
# 对图书的查询和增加
def get(self,request):
# 查询所有图书
queryset = BookInfo.objects.all()
book_list=[]
for book in queryset:
book_list.append({
'id':book.id,
'btitle':book.btitle,
'bpub_date':book.bpub_date,
})
return JsonResponse({'data':book_list})
def post(self,request):
# 新增图书
json_str = request.body
book_dict = json.loads(json_str)
print(book_dict)
book = BookInfo.objects.create(
btitle=book_dict.get('btitle'),
bpub_date = datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
)
return JsonResponse({
'id': book.id,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
},status=201)
class BookAPIView(View):
# 查询单个数据
def get(self,request,pk):
# 获取单个图书信息
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=400)
return JsonResponse({
'id': book.id,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
})
# 修改数据
def put(self,request,pk):
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
json_str = request.body
book_dict = json.loads(json_str)
book.btitle = book_dict.get('btitle')
book.bpub_date = datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
book.save()
return JsonResponse({
'id': book.id,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
})
# 删除
def delete(self,request,pk):
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
book.delete()
return JsonResponse({"recode":0,"msg":"删除成功"})
re_path(r'^book_list/$',views.BooksApiView.as_view())
get
{
"data": [
{
"id": 1,
"btitle": "射雕英雄传",
"bpub_date": "1980-05-01"
},
{
"id": 2,
"btitle": "天龙八部",
"bpub_date": "1986-07-24"
},
{
"id": 3,
"btitle": "笑傲江湖",
"bpub_date": "1995-12-24"
},
{
"id": 4,
"btitle": "雪山飞狐",
"bpub_date": "1987-11-11"
}
]
}