• 五、python Django FBV视图[响应方式、文件上传下载、cookie]


    一、响应方式

    1.返回响应内容

    1.1 HttpResponse(普通数据)

    导入:from django.shortcuts import HttpResponse
    用法:return HttpResponse('12300')
    解释:表示返回数据,状态码200

    1.2 JsonResponse(Json数据)

    导入:from django.http.response import JsonResponse
    用法:return JsonResponse(data)
    解释:表示返回Json数据

    2.模板渲染

    2.1 render

    导入:from django.shortcuts import render
    用法:

        con = {'value': "这是jinja2"}
        return render(request, 'testWeb/index.html', locals()) #locals()能包含多个字典
    	# 区别:模板里面调用value{{ con.value }}
    
    • 1
    • 2
    • 3

      	con = {'value': "这是jinja2"}
        return render(request, 'testWeb/index.html', context=con)
        # 区别:模板里面调用value{{ value }}
    
    • 1
    • 2
    • 3

    原理:render调用HttpResponse

    3.跳转

    3.1 redirect

    导入:from django.shortcuts import redirect
    状态码:301表示永久重定向首页地址(搜索引擎在抓取新内容的同时也将旧的网址替换成重定向之后的网址),302表示临时重定向首页地址(搜索引擎保留旧网址不替换成重定向之后的网址)
    用法:

    1. return redirect("https://www.gaoh222.cn", permanent=True) # permanent=True表示301;permanent=Flase表示302
    2. return redirect("in:go", permanent=False) # in:go 名字跳转

    原理:redirect调用HttpResponsePermanentRedirect或者HttpResponseRedirect

    4.异常响应

    解释:django提供httpResponseNotFound(‘404’),HttpResponseServerError(‘500’),但常用render(requeset,'404.html',status=404)

    状态码:404表示网页不存在,403表示没有访问权限,405表示不允许使用该请求方式,500表示服务器内部错误

    用法:
    urls.py
    解释:发生该错误就会按照状态码根据下面的内容寻找视图

    handler404='index.views.page404' # 404错误时
    handler500='index.views.page500' # 500错误时
    
    • 1
    • 2

    views.py

    # exception 必需有
    def page404(request, exception):
    	render(request,'404.html',status=404)
    
    • 1
    • 2
    • 3

    二、文件上传下载

    1.1 FileResponse(文件下载)

    导入:from django.http import FileResponse
    用法:

    # 注意路径以manage.py为基准
    def download(request):
        try:
            file = open('testWeb/download/1.png','rb') # 注意路径以manage.py为基准
            data = FileResponse(file, as_attachment=True, filename='1.png')
            return data
        except:
            return HttpResponse("fail")
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    1.2 request.FILES(文件上传)

    注意:multipart/form-data必须有不然request.FILES获取不到信息
    用法:
    views.py

    1. file.size:文件大小
    2. file.name:文件名字
    3. file.content_type:文件类型
    4. 此功能按流方式写入文件,避免占用大量内存
    for chunk in file.chunks():
    	f.write(chunk)
    
    • 1
    • 2
    def go(request):
        con = {'value': "这是jinja2"}
        allowType=['image/jpeg','image/png']
        if request.method == "POST":
            file = request.FILES['myfile']
            if file:
                if file.size/1024/1024>2:
                    return HttpResponse('to big')
                elif file.content_type not in allowType:
                    return HttpResponse('angry')
                else:
                    f = open(os.path.join('testWeb/static', file.name), 'wb+') # os.path.join 连接两个以上的名字,适合动态
                    for chunk in file.chunks():
                        f.write(chunk)
                    f.close()
                    return HttpResponse('ok')
        else:
            return render(request, 'testWeb/index.html', context=con)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    index.html

    DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<title>Documenttitle>
    head>
    <body>
    	<form enctype="multipart/form-data" action="" method="post"> 
    	
    		<input type="hidden" value="{{ csrf_token }}">
    		<input type="file" name="myfile"><br>
    		<input type="submit" value="上传">
    	form>
    body>
    html>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    三、cookie

    1.获取cookie

    解释:request.COOKIES['名字']

    2.发送cookie

    2.1 未加密

    参数:

    1. max_age:设置有效时间(秒为单位)
    def cookie(request):
        k = HttpResponse('0')
        k.set_cookie('name', 'jack',max_age=60*60*24*30)
        return k
    
    • 1
    • 2
    • 3
    • 4

    2.2 加密

    解密:request.get_signed_cookie('namess', salt='yueyue')
    原理:对key值进行加密然后调用set_cookie,加密方式
    参数:

    1. salt:加密盐
    def cookie(request):
        print(request.COOKIES)
        print(request.get_signed_cookie('namess', salt='yueyue'))
        k = HttpResponse('0')
        k.set_signed_cookie('namess', 'data569', salt='yueyue', max_age=50000)
        return k
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    如何在 🤗 Space 上托管 Unity 游戏
    大数据仓库flink1.13.2的ODS层存储代码示例
    数据库知识点整合
    基于docker实现mysql的主从复制 详细步骤
    本地开发申请ssl证书并在宝塔上给网站配置ssl
    线程版服务器实现(pthread_server)
    TXT文本文件存储
    FPGA----VCU128的DDR4无法使用问题(全网唯一)
    jQuery学习:显示隐藏 --点击图片显示隐藏
    Python魔法方法
  • 原文地址:https://blog.csdn.net/weixin_46765649/article/details/125943869