三板斧 HttpResponse , render , redirect
- HttpResponse >>> 返回字符串类型
- render >>> 返回HTML页面,并且在返回给浏览器之前还可以给HTML传值
- redirect >>> 重定向
# 视图函数必须要返回一个HttpResponse对象 正确 研究三者的源码即可得处结论
The view app01.views.index didn't return an HttpResponse object. It returned None instead.
# render简单内部原理
from django.template import Template,Context
res = Template('<h1>{{ user }}</h1>')
con = Context({'user':{'username':'jason','password':123}})
ret = res.render(con)
print(ret)
return HttpResponse(ret)
JsonResponse对象
json格式的数据有什么用?
前后端数据交互需要使用到json作为过度。实现跨语言传输数据。
前端序列化
前端 | python |
---|---|
JSON.stringify() | json.dumps() |
JSON.parse() | json.loads() |
import json
from django.http import JsonResponse
def ab_json(request):
user_dict = {'username': 'junjie', 'age': 18, 'hobby': 'silk','describe':'黑丝白丝我都爱'}
json_str = json.dumps(user_dict, ensure_ascii=False)
return JsonResponse(json_str)
# 浏览器输出:
{"username": "junjie", "age": 18, "hobby": "silk", "describe": "黑丝白丝我都爱"}
使用JasonResponse对象方法
以下JasonResponse源代码:
class JsonResponse(HttpResponse):
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super(JsonResponse, self).__init__(content=data, **kwargs)
data = json.dumps(data, cls=encoder, **json_dumps_params)
# 注意:**json_dumps_params,** 即打散字典键值对,以'username'='junjie'的形式,所以{'ensure_ascii':False},能够成立
def ab_json(request):
user_dict = {'username': 'junjie', 'age': 18, 'hobby': 'silk','describe':'黑丝白丝我都爱'}
return JsonResponse(user_dict,json_dumps_params={'ensure_ascii':False})
# 浏览器输出:
{"username": "junjie", "age": 18, "hobby": "silk", "describe": "黑丝白丝我都爱"}
# 研究其他形式是否可以序列化:
from django.http import JsonResponse
def ab_json(request):
l = [11,22,33,44,55]
return JsonResponse(l)
from django.http import JsonResponse
def ab_json(request):
l = [11,22,33,44,55]
return JsonResponse(l,safe=False)
# 默认只能序列化字典 序列化其他需要加safe参数
form表单上传文件及后端如何操作
form表单上传文件类型的数据
- method必须指定成post
- enctype必须换成formdata
<form action="" method="post" enctype="multipart/form-data">
<p>username:<input type="text" name="username"></p>
<p>file: <input type="file" name="file"></p>
<input type="submit">
</form>
def upload_img(request):
if request.method == 'POST':
print(request.POST)
"""
输出:
<QueryDict: {'username': ['junjie']}> <class 'django.http.request.QueryDict'>
"""
return render(request,'uploadimg.html')
获取文件对象以及浏览器上传图片。
def upload_img(request):
if request.method == 'POST':
print(request.FILES) # 获取文件数据
"""
<MultiValueDict: {'file': [<InMemoryUploadedFile: 认真了.png (image/png)>]}>
"""
img_obj = request.FILES.get('file') # 文件对象
print(img_obj) # 输出:认真了.png
print(img_obj.name) # 输出:认真了.png
with open(img_obj.name,'wb') as f:
for line in img_obj.chunks(): #
f.write(line)
return render(request, 'uploadimg.html')
request对象方法
对象方法 | 描述 |
---|---|
request.method | 返回请求方式( GET/POST ) |
request.POST | 获取键值对形式的普通文件 |
request.GET | 返回一个GET请求 |
request.FILES | 读取文件数据 |
request.body | 原生的浏览器发过来的二进制数据 |
request.path | 获取路由 |
request.path_info | 获取路由 |
request_get_full_path() | 获取路由和?后面参数 |