django基础知识之Response对象
HttpResponse对象
- 在django.http模块中定义了HttpResponse对象的API
- HttpRequest对象由Django自动创建,HttpResponse对象由程序员创建
- 不调用模板,直接返回数据
#coding=utf-8
from django.http import HttpResponse
def index(request):
return HttpResponse('你好')
- 调用模板
from django.http import HttpResponse
from django.template import RequestContext, loader
def index(request):
t1 = loader.get_template('polls/index.html')
context = RequestContext(request, {'h1': 'hello'})
return HttpResponse(t1.render(context))
属性
- content:表示返回的内容,字符串类型
- charset:表示response采用的编码字符集,字符串类型
- status_code:响应的HTTP响应状态码
- content-type:指定输出的MIME类型
方法
- init :使用页内容实例化HttpResponse对象
- write(content):以文件的方式写
- flush():以文件的方式输出缓存区
- set_cookie(key, value='', max_age=None, expires=None):设置Cookie
- key、value都是字符串类型
- max_age是一个整数,表示在指定秒数后过期
- expires是一个datetime或timedelta对象,会话将在这个指定的日期/时间过期,注意datetime和timedelta值只有在使用PickleSerializer时才可序列化
- max_age与expires二选一
- 如果不指定过期时间,则两个星期后过期
from django.http import HttpResponse
from datetime import *
def index(request):
response = HttpResponse()
if request.COOKIES.has_key('h1'):
response.write('<h1>' + request.COOKIES['h1'] + '</h1>')
response.set_cookie('h1', '你好', 120)
# response.set_cookie('h1', '你好', None, datetime(2016, 10, 31))
return response
- delete_cookie(key):删除指定的key的Cookie,如果key不存在则什么也不发生
子类HttpResponseRedirect
- 重定向,服务器端跳转
- 构造函数的第一个参数用来指定重定向的地址
在views1.py中
from django.http import HttpResponse,HttpResponseRedirect
def index(request):
return HttpResponseRedirect('js/')
def index2(request,id):
return HttpResponse(id)
在应用的urls.py中增加一个url对象
url(r'^([0-9]+)/$', views1.index2, name='index2'),
- 请求地址栏如图:
- 请求结果的地址栏如图:
- 推荐使用反向解析
from django.core.urlresolvers import reverse
def index(request):
return HttpResponseRedirect(reverse('booktest:index2', args=(1,)))
子类JsonResponse
- 返回json数据,一般用于异步请求
- _init _(data)
- 帮助用户创建JSON编码的响应
- 参数data是字典对象
- JsonResponse的默认Content-Type为application/json
from django.http import JsonResponse
def index2(requeset):
return JsonResponse({'list': 'abc'})
简写函数
render
- render(request, template_name[, context])
- 结合一个给定的模板和一个给定的上下文字典,并返回一个渲染后的HttpResponse对象
- request:该request用于生成response
- template_name:要使用的模板的完整名称
- context:添加到模板上下文的一个字典,视图将在渲染模板之前调用它
from django.shortcuts import render
def index(request):
return render(request, 'booktest/index.html', {'h1': 'hello'})
重定向
- redirect(to)
- 为传递进来的参数返回HttpResponseRedirect
- to推荐使用反向解析
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
def index(request):
return redirect(reverse('booktest:index2'))
得到对象或返回404
- get_object_or_404(klass, args, *kwargs)
- 通过模型管理器或查询集调用get()方法,如果没找到对象,不引发模型的DoesNotExist异常,而是引发Http404异常
- klass:获取对象的模型类、Manager对象或QuerySet对象
- **kwargs:查询的参数,格式应该可以被get()和filter()接受
- 如果找到多个对象将引发MultipleObjectsReturned异常
from django.shortcuts import *
def detail(request, id):
try:
book = get_object_or_404(BookInfo, pk=id)
except BookInfo.MultipleObjectsReturned:
book = None
return render(request, 'booktest/detail.html', {'book': book})
将settings.py中的DEBUG改为False
将请求地址输入2和100查看效果
得到列表或返回404
- get_list_or_404(klass, args, *kwargs)
- klass:获取列表的一个Model、Manager或QuerySet实例
- **kwargs:查寻的参数,格式应该可以被get()和filter()接受
from django.shortcuts import *
def index(request):
# list = get_list_or_404(BookInfo, pk__lt=1)
list = get_list_or_404(BookInfo, pk__lt=6)
return render(request, 'booktest/index.html', {'list': list})
将settings.py中的DEBUG改为False
django基础知识之Response对象的更多相关文章
- django基础知识之QueryDict对象:
QueryDict对象 定义在django.http.QueryDict request对象的属性GET.POST都是QueryDict类型的对象 与python字典不同,QueryDict类型的对象 ...
- django基础知识之HttpReqeust对象:
HttpReqeust对象 服务器接收到http协议的请求后,会根据报文创建HttpRequest对象 视图函数的第一个参数是HttpRequest对象 在django.http模块中定义了HttpR ...
- Django使用request和response对象
当请求一张页面时,Django把请求的metadata数据包装成一个HttpRequest对象,然后Django加载合适的view方法,把这个HttpRequest 对象作为第一个参数传给view方法 ...
- Django框架基础知识08-表关联对象及多表查询
1.自定义主键字段的创建 AutoFiled(pirmary_key=True) # 一般不会自定义,int类型,自增长 一般不自定义主键. 2.order_by asc desc from djan ...
- 01 Django基础知识
相关概念 软件框架 一个公司是由公司中的各部部门来组成的,每一个部门拥有特定的职能,部门与部门之间通过相互的配合来完成让公司运转起来. 一个软件框架是由其中各个软件模块组成的,每一个模块都有特定的功能 ...
- django基础知识
一.django的安装 1. pip3 install django 2. 把安装路径加到环境变量里以便以后启动admin相关命令,在windows系统中---我的电脑---属性----高级系统设置- ...
- django基础知识之中间件:
中间件 是一个轻量级.底层的插件系统,可以介入Django的请求和响应处理过程,修改Django的输入或输出 激活:添加到Django配置文件中的MIDDLEWARE_CLASSES元组中 每个中间件 ...
- Django02 Django基础知识
一.内容回顾 1.web应用程序 2.HTTP协议 a.http协议特性 b.http请求格式 c.http响应格式 3.wsgiref模块 4.Django下载与简单应用 a.Django简介(MT ...
- django基础知识之布署:
布署 从uwsgi.nginx.静态文件三个方面处理 服务器介绍 服务器:私有服务器.公有服务器 私有服务器:公司自己购买.自己维护,只布署自己的应用,可供公司内部或外网访问 公有服务器:集成好运营环 ...
随机推荐
- CSS简单介绍及应用
CSS的简介 概述: Cascading Style Sheets, 层叠样式表. 作用: 用来美化页面的. 分类: 行内样式: //直接写在元素(html的标签)中的样式. 内部样式: //写在&l ...
- WebApi 通过身份票据进行认证授权的具体实现
写在前面: 如果webapi接口没有身份认证,那么所有知道接口url的用户都可以随意访问接口,从而查询或者修改数据库, 那么问题就来了,如果我们不想让所有人都调用我们的接口,那么就需要加上一层验证,只 ...
- 判断手机使用网络wifi 2G 3G
ConnectivityManager cManager = (ConnectivityManager) this .getSystemService(Context.CONNECTIVITY_SER ...
- c++之继承与派生
再来回顾下继承派生的语法. 继承方式显示有三种(public, protected, privatez),隐式默认private.所谓继承方式,是指派生类对基类成员的访问权限控制. 派生类构造函数定义 ...
- 【bzoj1479】[NOI2006]最大获利
1497: [NOI2006]最大获利 Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 4335 Solved: 2123[Submit][Status] ...
- file_get_content() 超时
set_time_limit 只能影响php 程序的超时时间. file_get_contents 读取的是URL的超时时间. 因此 set_limit_limit 对file_get_conte ...
- string基本字符系列容器(二)
string对象作为vector元素 string对象可以作为vector向量元素,这种用法类似字符串数组. #include<string> #include<vector> ...
- 【项目运行异常】BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking ...
- Cannot connect to the Docker datemon at tcp://0.0.0.0:2375 is the docker daemon runing?
一.系统环境: 在Windows 7 64位上,采用Vmware workstation 12安装了CenOS7.5 64位. 二.问题 在CentOS7.5里安装了Docker,启动docker服务 ...
- jQuery--全选、反选、取消
主要知识点: prop()--主要检查和设置checked attr()是针对所有属性,prop()是针对checked和selected等单一存在的,判断他们的true或者false. find() ...