视图层
三板斧
"""
HttpResponse
返回字符串类型
render
返回html页面,并且可以传值
redirct
重定向
"""
JsonResponse
from django.http import JsonResponse
def ab_json(request):
user_dic = {
'username': 'jason',
'password': 123,
'hobby': '喝茶'
}
l = [11, 22, 333, 44, 555, 55, 66]
# json_str = json.dumps(user_dic, ensure_ascii=False)
# print(json_str)
# return HttpResponse(json_str)
# return JsonResponse(user_dic, json_dumps_params={'ensure_ascii': False})
return JsonResponse(l, safe=False)
def file(request):
if request.method == 'POST':
# print(request.POST) # 拿不到文件数据,只能获取普通的键值对数据
# print(request.FILES) # 获取文件数据
file_obj = request.FILES.get('file') # 文件对象
# print(file_obj.name)
with open(file_obj.name, 'wb') as f:
for line in file_obj:
f.write(line)
return render(request, 'fiel.html')
ps:
print(request.path) # /app01/file/
print(request.path_info) # /app01/file/
print(request.get_full_path()) # /app01/file/?username=lyh
FBV CBV
视图函数既可以是函数也可以是类
# CBV
#CBV路由
path('login/', views.Mylogin.as_view())
from django.views import View
class Mylogin(View):
def get(self, request):
return render(request, 'fiel.html')
def post(self, request):
return HttpResponse('Post')
"""
cbv可以根据请求方式的不同,匹配到不同的方法
"""