首页 / GO / Django中的response
Django中的response
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Django中的response,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2463字,纯文字阅读大概需要4分钟。
内容图文
render_to_response
render_to_response('index.html', locals(),context_instance=RequestContext(request))
参数顺序:(template_name, dictionary=None, context_instance=None)
在django模板系统中,有两种封装模板变量的类,一个是django.template.Context,这是最常用的,我们在使用render_to_response方法的时候传入的第二个dictionary参数,就会被这个Context类封装一次,然后传到模板当中。
另一个是django.template.RequestContext,它和Context类相比有两个不同之处。
第一个不同的是,在生成一个RequestContext变量的时候,需要传入一个HttpRequest对象作为它的第一个参数。
其次,它会增加一些自动注入模板的变量,这些变量由settings中的TEMPLATE_CONTEXT_PROCESSORS中声明的方法返回,TEMPLATE_CONTEXT_PROCESSORS中的方法都接收一个HttpRequest对象,最终return一个dict。这个dictionary里面的元素就会成为RequestContext中自动注入模板的变量。比如django.contrib.auth.context_processors.auth就会返回user、messages、perms变量
# in django/contrib/auth/context_processors.py
def auth(request):
""" ignore doc string """
def get_user():
....
return {
'user': SimpleLazyObject(get_user),
'messages': messages.get_messages(request),
'perms': lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
}
有时候会用到dictionary=locals()这种操作,这是将当前域的所有局部变量都赋给dictionary
Response与HttpResponse的区别
-
HttpResponse
# django/http/response.py # HttpResponse的初始化 class HttpResponseBase(six.Iterator): def __init__(self, content_type=None, status=None, reason=None, charset=None): class HttpResponse(HttpResponseBase): def __init__(self, content=b'', *args, **kwargs): super(HttpResponse, self).__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content
- HttpResponse对象由Django创建,常用于函数式视图
- super()常用于调用父类的方法。
python super(HttpResponse, self).__init__(*args, **kwargs)
即调用HttpResponse父类HttpResponseBase的__init__方法 - 因此,HttpResponse生成格式为HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)
- 注意如果前端需要json数据类型,而data是一个字典,则需要手动把data转为json格式。HttpResponse(json.dumps(data))
-
Response
# rest_framework/response.py # Response的初始化 class Response(SimpleTemplateResponse): def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None):
- Response对象是Django REST framework框架封装的对象
- Response会自动将传入data的数据转为json,无需手动转换。甚至可以直接Response(data=serializer.data)
- 一般在DRF框架中类的视图中使用Response对象,类的视图要继承APIView
-
如果要在函数式视图使用Response,需要加上@api_view装饰器,如
from rest_framework.decorators import api_view @api_view(['GET', 'POST', ]) def articles(request, format=None): data= {'articles': Article.objects.all() } return Response(data, template_name='articles.html')
如果不加装饰器的话,会报错:“.accepted_renderer not set on Response”
原文:https://www.cnblogs.com/luozx207/p/10968572.html
内容总结
以上是互联网集市为您收集整理的Django中的response全部内容,希望文章能够帮你解决Django中的response所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。