Django学习记录4-HttpResponse对象
Django连接一个前端页
1.在项目目录下创建一个文件夹存放html文件(也可以在应用目录下)
编写html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Django视图层</title> </head> <body> <h2>Djando视图</h2> <ul> <!-- <li><a href="resp01">一个简单视图</a></li> --> <!-- 地址可以是直接写,也可以用下边方式反向解析名为aa的地址,在urls中设置 --> <li><a href="{% url 'aa' %}">一个简单视图</a></li> <li><a href="{% url 'json01' %}">json</a></li> <li><a href="{% url 'rescookie' %}">cookie</a></li> </ul> </body> </html>
2.编写好的html文件需要设置地址,在settings文件里设置:
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"templates")], #设置添加index.html地址,存放在项目目录下的templates 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
3.在views.py文件添加响应内容
from django.shortcuts import render from django.http import HttpResponse , JsonResponse # Create your views here. import hashlib def index(request): return render(request, "myapp/index.html")
#响应的内容为templates目录下myapp/index.html templates在之前已经声明 def resp01(request): return HttpResponse("<h3>视图响应</h3>") #HttpResponse可以响应html语言 def resp02(request): data = [ {"id" : 1, "name" : "zhangsan", "age" : 20}, {"id" : 2, "name" : "lisi", "age" : 21}, {"id" : 3, "name" : "wangwu", "age" : 20}, ] return JsonResponse({"data" : data})
#JsonResponse不能直接输出data,应转化为json格式 def resp03(requset): response = HttpResponse("cookie设置") rescookie = "flag_jdf34hfh9dfd3" m = hashlib.md5() m.update(rescookie.encode(encoding="UTF-8")) t = m.hexdigest() response.set_cookie("cookie", t)#向前端传递一个名为"cookid"内容为t的值 return response
#前端点击链接,当服务器回应时会为前端传递一个cookid值
编辑好views.py文件后需要在应用目录下添加urls.py文件,传递views里的index、resp01、resp02、resp03参数.
from django.urls import path , include from myapp import views urlpatterns = [ path("",views.index), path("resp01",views.resp01,name = "aa"),
#"aa"将resp01地址命名,在其他地方可以直接引用反向解析地址,当原地址发生变更时它也会
随之变化,可以增强代码灵活性。 path("resp02",views.resp02,name = "json01"), path("resp03",views.resp03,name = "rescookie"), ]
#当引用的是一个class时,格式如下
path('mine/', MyView.as_view(), name='my-view')
# 其中as_view()是接受请求并返回响应的可调用视图['get', 'post', 'put', 'patch', 'delete, 'options'.]