测开之路四十八:Django之重定向与cookie
基础配置与上一篇一致
404错误
定义一个error页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>错误页</title>
</head>
<body>
<h1>哎呀,出错啦!</h1>
</body>
</html>
追加一个404的视图

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

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

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
再访问

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

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的时候会被重定向

cookie
以之前的test视图为例

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)
)
访问

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

def hello(request, user):
# return HttpResponse(user)
context = {
'user': user,
'hobbit': ['看书', '写代码'],
'cookie': request.COOKIES.get('django', 'NoCookie')
}
return render(request, 'hello.html', context)
打印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

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

清除cookie再访问,会打印NoCookie

测开之路四十八:Django之重定向与cookie的更多相关文章
- 测开之路四十九:用Django实现扑克牌游戏
用Django实现和之前flask一样的扑克牌游戏 项目结构 html <!DOCTYPE html><html lang="en"><head> ...
- 测开之路四十五:Django之最小程序
安装Django库 Django最小程序 import sysfrom django.conf.urls import urlfrom django.conf import settingsfrom ...
- 测开之路四十七:Django之请求静态资源与模板
框架必要的配置 import sysfrom django.conf.urls import urlfrom django.conf import settingsfrom django.http i ...
- 测开之路七十八:shell之函数和参数
函数 function function_name(){ statement1 Statement2 .... statementn} function_name $var1 ...
- 测开之路四十二:常用的jquery事件
$(‘selector’).click() 触发点击事件$(‘selector’).click(function) 添加点击事件$(‘selector’).dbclick() 触发双击事件$(‘sel ...
- 测开之路四十:jQuery基本用法
从cdn引入jQuery库:https://www.bootcdn.cn/,搜索jQuery 在html里面(使用之前计算器的脚本),把复制的标签粘贴到引入js标签的前面:<script src ...
- 测开之路三十八:css布局之定位
常用的布局方式: static:静态定位(默认),什么都不用管,元素会按照默认顺序排列,排不下是会默认换行relative:相对定位(同一层),相对于某一个元素进行定位fixed:绝对定位,指定位置a ...
- 测开之路二十八:Flask基础之静态资源
Flask默认的存放静态资源的目录名为static 在工程下创建一个文件夹(与脚本同级) 如果想命名为其他名字,则在声明app的时候要初始化,如: 准备一张图片放在static下,返回的内容加上img ...
- 测开之路七十四:python处理kafka
kafka-python地址:https://github.com/dpkp/kafka-python 安装kafka-python:pip install kafka-python 接收消息 fro ...
随机推荐
- Maven系列学习(一)Maven基本知识
Maven 简介 1.Maven主要是基于Java平台的项目构建,依赖管理和项目信息 2.Maven是优秀的构建工具,跨平台,消除构建的重复,抽象了一个完整的构建生命周期模型,标准化构建过程 3.管理 ...
- C# 栈=>随时读取栈中最小值
//原理:利用两个栈,一个记录最小值,一个记录数据. using System; using System.Collections.Generic; using System.Linq; using ...
- deb包转换为rpm包格式
在Debian系列中安装软件包可以使用apt或者dpkg安装deb包,但是在CentOs, Redhat等则只能安装RPM包,如果希望在Redhat或者CentOS下也安装Deb包的话是不可行的, 但 ...
- 物流运输(最短路+dp)
这道题是相当的火,但是在tyher的讲解下我一遍就AC了!!! Part 1 理解题目 从第一天到最后一天,总会有一些点莫名其妙地走不了,所以导致我们不能按照上一次的最短路一直运输得到最少费用,而需要 ...
- K3 cloud选单时候必须把必录的数据录完以后才可以选单
解决办法:在bos中把选单按钮的提交时候校验打勾
- c#模板化生成接口
最近打算做这样一个事情,一个桌面系统项目既可以一体化部署,作为一个软件一个进程部署,也可以把业务服务化部署. 那一般意味着我们要完全写2套东西,一套是直接UI调用业务,一套是Ui调用RPC.这样比较多 ...
- YARN的job提交流程
1.客户端向ResourceManagement 提交 运行的请求 (hadoop jar xxxx.jar) 2.ResourceManager进行检查,没有问题的时候,向客户端返回一个共享资源的路 ...
- redis 命令大全
全局命令: 1.查看所有键:keys * 2.键总数:dbsize 3.检查键是否存在:exists key 4.删除键:del key [key ...] 5.键过期:expire key seco ...
- 在Ubuntu上安装LAMP(Apache、Mysql、Php)
原文地址:https://howtoubuntu.org/how-to-install-lamp-on-ubuntu Ubuntu有很多工具可以帮助我们一键配置LAMP环境,比如tasksel,但这些 ...
- pwn的一些技巧与总结
原文地址:https://github.com/Naetw/CTF-pwn-tips 目录 溢出 在gdb中寻找字符串 二进制服务 找到libc中特定函数的偏移地址 Find '/bin/sh' or ...