tuxlcsdn 2019-12-26
在Django框架中,我们可以通过视图函数返回响应对象来给客户端返回指定的数据。
接下来我将给大家简述一下如何利用响应对象给客户端返回指定数据。
1. 自定义响应对象
第一种方式:
from django.http import HttpResponse, JsonResponse# 自定义响应对象
def index(request):
# 第一种方式构建自定义响应对象
return HttpResponse(content=‘Page Is Run.....‘, content_type=‘text/html;charset=utf8‘,status=404)
第二种方式:
from django.http import HttpResponse, JsonResponse# 自定义响应对象
def index(request):
# # 第一种方式构建自定义响应对象
# return HttpResponse(content=‘Page Is Run.....‘, content_type=‘text/html;charset=utf8‘,status=404)
第二种方式构建自定义响应对象
resp = HttpResponse()
resp.content = ‘Page Not Found...‘
resp.status_code = 200
resp[‘laowang‘] = ‘This is Laowang...‘
return resp
2. 定义一个JSON接口
在Django框架中我们可以利用返回JSON类型的对象来实现一个接口。
import pymysql
import json
from django.http import JsonResponse
# 定义一个接口
def index(request):
db = pymysql.Connection(host=‘localhost‘,port=3306,database=‘school‘,user=‘root‘,passowrd=‘root‘,charset=‘utf8‘)
cur = db.cursor()
sql = ‘‘‘ select name,age from student‘‘‘
cur.execute(sql)
data = cur.fetchall()
cur.close()
db.close()
json_list = []
for key in data:
json_dict = {}
json_dict[key] = json_dict.get(key)
json_list.append(json_dict)
return JsonResponse(json_list)3. 重定向
将客户端发送的请求重定向到指定页面上。
重定向有三种方式来实现:
1. 直接重定向到外网网址:
def index(request):
return redirect(‘https://www.baidu.com‘)2. 重定向到站内路径:
from django.urls import reverse
def index(request):
# 不带参数的反向解析
return redirect(reverse(‘users:views‘))
# 带参数的反向解析
return redirect(reverse(‘users:views‘, args=(‘name‘,‘age‘)))