测开之路四十八:Django之重定向与cookie

时间:2022-12-10 13:13:34

 

基础配置与上一篇一致

 

404错误

定义一个error页面

测开之路四十八:Django之重定向与cookie

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>错误页</title>
</head>
<body>
<h1>哎呀,出错啦!</h1>
</body>
</html>

 

追加一个404的视图

测开之路四十八:Django之重定向与cookie

访问,由于开了debug模式,所以Django会捕获异常并抛出来,所以关闭debug模式再访问

测开之路四十八:Django之重定向与cookie

 

把debug注释掉,并追加可访问的host:ALLOWED_HOSTS=['*'],

测开之路四十八:Django之重定向与cookie

import os
import sys
from django.shortcuts import render
from django.conf.urls import url
from django.conf import settings
from django.core.management import execute_from_command_line

BASE_DIR = os.path.dirname(__file__) # 定义当前工程目录为basedir

# 设置框架配置
settings.configure(
# DEBUG=True,
ALLOWED_HOSTS=['*'],
SECRET_KEY='aaa', # 用于加密的字符串
ROOT_URLCONF=__name__, # 此配置为在当前文件里面找url映射的配置
MIDDLEWARE_CLASSES=(
'django.middleware.commom.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
),
STATIC_URL='/static/', # 定义静态文件的存放目录,和flask一致
STATICFILES_DIRS=(os.path.join(BASE_DIR, 'static'),), # 静态文件目录,指向BASE_DIR/static(括号里的逗号不能省)
INSTALLED_APPS=('django.contrib.staticfiles',), # Django使用静态文件需要安装即在配置中录入此信息(括号里的逗号不能省)
# 模板的配置
TEMPLATES=[{
# 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Django自带的模板引擎
'BACKEND': 'django.template.backends.jinja2.Jinja2', # Jinja2的模板引擎
'APP_DIRS': True, # APP_DIRS为True则默认app下的templates目录,否则使用下一行DIRS声明的目录
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'OPTIONS': {}}]
)

# 实现访问返回访问请求中的参数
def hello(request, user):
# return HttpResponse(user)
context = {
'user': user,
'hobbit': ['看书', '写代码']
}
return render(request, 'hello.html', context)

# 出现404 page_not_found的时候,返回error.html
def page_not_found(request, exception, template_name= 'error.html'):
return render(request, template_name)
handler404 = page_not_found

再访问

测开之路四十八:Django之重定向与cookie

 

 

重定向

需要导入库(以上配置不变,把debug打开)

 测开之路四十八:Django之重定向与cookie

from django.http import HttpResponseRedirect
def redirect(request):
return HttpResponseRedirect('/hello/这是重定向/?message=error')

# 通过正则匹配url,做视图映射
urlpatterns = (
# url( r'^test/$', test),
url(r'^hello/(?P<user>\w+)/$', hello),
url(r'^redirect$', redirect),
# url(r'^$', index)
)

访问redirect的时候会被重定向

测开之路四十八:Django之重定向与cookie

 

cookie

以之前的test视图为例

测开之路四十八:Django之重定向与cookie

from django.http  import JsonResponse
def test(request):
print(dir(request))
data = {
'path': request.path,
'method': request.method,
'scheme': request.scheme,
'host': request.get_host(),
'port': request.get_port(),
'cookies': request.COOKIES,
'get': request.GET,
'post': request.POST,
}
# return JsonResponse(data)
response = JsonResponse(data)
response.set_cookie('django', 'djangoCookie')
return response

# 通过正则匹配url,做视图映射
urlpatterns = (
url( r'^test/$', test),
url(r'^hello/(?P<user>\w+)/$', hello),
url(r'^redirect$', redirect),
# url(r'^$', index)
)

 访问

测开之路四十八:Django之重定向与cookie

 

使用cookie

get('django', 'NoCookie'):如果Django有cookie,就用Django的,如果没有,就用NoCookie

测开之路四十八:Django之重定向与cookie

def hello(request, user):
# return HttpResponse(user)
context = {
'user': user,
'hobbit': ['看书', '写代码'],
'cookie': request.COOKIES.get('django', 'NoCookie')
}
return render(request, 'hello.html', context)

打印cookie

测开之路四十八:Django之重定向与cookie

<html>
<head>
<link rel="stylesheet" href="/static/hello.css">
<title>django with jinja</title>
</head>
<body>
<h2>这是测试</h2>
<p>我是用户:{{ user }}</p>
{% for h in hobbit %}
<p>爱好是:{{ h }}</p>
{% endfor %}
{{ cookie }}
</body>
</html>

访问test/生成cookie

测开之路四十八:Django之重定向与cookie

再访问/hello/xxx/,会把Django对应的cookie值打印出来

测开之路四十八:Django之重定向与cookie

清除cookie再访问,会打印NoCookie

测开之路四十八:Django之重定向与cookie