Django学习——视图层HttpResponse、render、redirect本质、JsonResponse
2022-04-30 21:03
1506 查看
HttpResponse、render、redirect本质
django视图函数必须要返回一个HttpResponse对象 def render(request, template_name, context=None, content_type=None, status=None, using=None): """ Return a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status) class HttpResponse(HttpResponseBase): """ An HTTP response class with a string as content. This content can be read, appended to, or replaced. """ streaming = False def __init__(self, content=b'', *args, **kwargs): super().__init__(*args, **kwargs) # Content is a bytestring. See the `content` property methods. self.content = content def __repr__(self): return '<%(cls)s status_code=%(status_code)d%(content_type)s>' % { 'cls': self.__class__.__name__, 'status_code': self.status_code, 'content_type': self._content_type_for_repr, } def serialize(self): """Full HTTP message, including headers, as a bytestring.""" return self.serialize_headers() + b'\r\n\r\n' + self.content __bytes__ = serialize @property def content(self): return b''.join(self._container) @content.setter def content(self, value): # Consume iterators upon assignment to allow repeated iteration. if ( hasattr(value, '__iter__') and not isinstance(value, (bytes, memoryview, str)) ): content = b''.join(self.make_bytes(chunk) for chunk in value) if hasattr(value, 'close'): try: value.close() except Exception: pass else: content = self.make_bytes(value) # Create a list of properly encoded bytestrings to support write(). self._container = [content] def __iter__(self): return iter(self._container) def write(self, content): self._container.append(self.make_bytes(content)) def tell(self): return len(self.content) def getvalue(self): return self.content def writable(self): return True def writelines(self, lines): for line in lines: self.write(line) redirect内部是继承了HttpResponse类
JsonResponse
需求:给前端返回json格式数据 方式1:自己序列化 # res = json.dumps(d,ensure_ascii=False) # return HttpResponse(res) 方式2:JsonResponse import json from django.http import JsonResponse def func2(request): d = {'user':'jason好帅','password':123} return JsonResponse(d)
ps:额外参数补充
json_dumps_params={'ensure_ascii':False} # 看源码 safe=False # 看报错信息 # JsonResponse返回的也是HttpResponse对象
相关文章推荐
- Django中视图总结[urls匹配,HttpRequest对象,HttpResponse,render,redirect对象,对象序列化接受及案例]
- django views视图函数返回值 return redirect httpresponse总结
- Django_HttpResponse,render,redirect
- django学习——通过HttpResponseRedirect 和 reverse实现重定向
- django-HttpResponse,render,redirect
- Flask最强攻略 - 跟DragonFire学Flask - 第二篇 Flask 中的 Render Redirect HttpResponse
- [py]django url 参数/reverse和HttpResponseRedirect
- 《Django Web应用开发实战》学习笔记 8- 视图函数(FBV视图),render,redirect,自定义404|500 页面
- Django中的 JsonResponse 与 HttpResponse
- django学习日志(View视图)第四部分:Request对象和Response对象
- django 使用HttpResponse返回json数据为中文
- django的HttpResponseRedirect重定向 mysql保存文本的换行问题
- python web 学习笔记三--Django 数据库与网页的信息传递和render与redirect
- django 使用HttpResponse返回json数据为中文
- 8. Django学习笔记——视图及HttpRequest 和HttpResponse
- Django1.7b版本中HttpResponse中 移除了参数mimetype=’application/json’ 这样的写法
- from django.http import HttpResponseRedirect
- Django JsonResponse与HttpResponse重要区别
- 基于 Django1.10 文档的深入学习(14)—— Request and response objects 之 HttpResponse objects
- django render和HttpResponse