Django框架HttpResponse对象用法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了Django框架HttpResponse对象用法。分享给大家供大家参考,具体如下:

1.HttpResponse

可通过HttpResponse构造响应对象:

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

响应头可以直接将HttpResponse对象当做字典进行响应头键值对的设置:

response = HttpResponse()
response['itcast'] = 'Python' # 自定义响应头Itcast, 值为Python

Django提供了一系列HttpResponse的子类,可以快速设置状态码:

HttpResponseRedirect 301
HttpResponsePermanentRedirect 302
HttpResponseNotModified 304
HttpResponseBadRequest 400
HttpResponseNotFound 404
HttpResponseForbidden 403
HttpResponseNotAllowed 405
HttpResponseGone 410
HttpResponseServerError 500

2.JsonResponse

JsonResponse来构造响应对象的作用:

(1)帮助我们将数据转换为json字符串

(2)设置响应头Content-Type为application/json

用法:

return JsonResponse(dict,safe) (safe默认为True,保证可以将对象转为json,如果为非字典对象,则报错,可设置为False传递非字典对象)

例:

def response(request):
 return JsonResponse({'city': 'beijing', 'subject': 'python'})

3.redirect重定向

return redirect(路径)

4.reverse反解析

reverse可根据路由名称返回路由路径。

用法:

reverse(路由名称)

如果未指明命名空间,路由名称:

namespace:reverse(name)

如果指明命名空间,路由名称:

namespace:reverse(namespace:name)

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

相关文章

Python编程实现二分法和牛顿迭代法求平方根代码

Python编程实现二分法和牛顿迭代法求平方根代码

求一个数的平方根函数sqrt(int num) ,在大多数语言中都提供实现。那么要求一个数的平方根,是怎么实现的呢? 实际上求平方根的算法方法主要有两种:二分法(binary searc...

Python实现压缩文件夹与解压缩zip文件的方法

本文实例讲述了Python实现压缩文件夹与解压缩zip文件的方法。分享给大家供大家参考,具体如下: 直接上代码 #coding=utf-8 #甄码农python代码 #使用zipfi...

Python Xml文件添加字节属性的方法

实例如下所示: from xml.etree.cElementTree import ElementTree,Element import xlrd import re def re...

Python实现二分查找算法实例

本文实例讲述了Python实现二分查找算法的方法。分享给大家供大家参考。具体实现方法如下: #!/usr/bin/env python import sys def search2...

Python实现监控程序执行时间并将其写入日志的方法

本文实例讲述了Python实现监控程序执行时间并将其写入日志的方法。分享给大家供大家参考。具体实现方法如下: # /usr/bin/python # -*- coding:utf-8...