• python-20220928


    python中删除文件

    os.remove()  # 删除文件
    
    os.unlink()  # 删除文件。它是remove()方法的Unix名称。
    
    shutil.rmtree()  # 删除目录及其下面所有内容。 
    # 作者:每天学习编程的日常 https://www.bilibili.com/read/cv11487671/ 出处:bilibili
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    python uuid

    import uuid
    uuid.uuid1([node[, clock_seq]])  #: 基于时间戳
    uuid.uuid3(namespace, name) #: 基于名字的MD5散列值
    uuid.uuid4() #: 基于随机数
    uuid.uuid5(namespace, name) #: 基于名字的SHA-1散列值
    
    • 1
    • 2
    • 3
    • 4
    • 5

    zipfile模块

    http://www.zzvips.com/article/170625.html

    django 的上传、下载文件操作

    【https://blog.csdn.net/zhanghs1989/article/details/123924347】

    网页上传:

    
    DOCTYPE html>
    
    <head>
        <meta charset="UTF-8">
        <title>upload filetitle>
    head>
    <script>
    function file_size(that){
        console.log('ss');
        document.getElementById("button_file").disabled=true;    // 不允许点击
        document.getElementById('file_size').innerHTML = "";
        if (that.files.length == 0) {
            return
        }
        var selected_file = that.files[0];
    
        // 换算单位
        var file_size = selected_file.size;
        var unit = 'K';
        var num = file_size;
        if(num > 1024 * 1024 * 1024){
            unit = 'G'
            num = num / (1024 * 1024 * 1024)
        }
        else if(num > 1024 * 1024){
            unit = 'M'
            num = num / (1024 * 1024)
        }
        else if(num > 1024){           // G
            unit = 'K'
            num = num / 1024
        }
        document.getElementById("file_size").innerHTML = '文件大小:'+ num.toFixed(2)  + unit
    
        if(file_size >= 1024 * 1024 * 50){        // 50M
            alert('文件大小大于50MB,请重新选择文件!!')
            return
         }
    
        document.getElementById("button_file").disabled=false
        document.getElementById("button_file").style.pointerEvents="auto";
    }
    script>
    <body>
        <form method="post" action="" enctype="multipart/form-data">
            {% csrf_token %}
           <h2> 上传文件h2>        
            <br/>
           <input type="file" name="zip_file" accept=".zip" onchange="file_size(this)" style="border: 1px solid rgb(118, 118, 118); ">
            <span id="file_size" >span>
           <input type="submit" value="上传文件" style="" id="button_file" disabled="disabled"/>
        form>
    body>
    
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56

    接收上传:

    import threading
    CACHE_DIR = '/tmp/tmp_pack'  # 上传文件和压缩文件的临时目录
    MAX_FILE_SIZE = 50 * 1024 * 1024  # 上传文件大小限制的上限
    MAX_FILE_SIZE_MSG = '50MB'  # 上传文件大小限制的上限名称
    
    num = 0
    lock = threading.Lock()
    
    
    def upload_file(request):
        # 请求方法为POST时,进行处理;
        if request.method == "POST":
            # 获取上传的文件,如果没有文件,则默认为None;
            zip_file= request.FILES.get("zip_file", None)
    
            if zip_fileNone:
                return HttpResponse("未选择任何文件!")
            else:
                # 确保缓存目录存在 
                print("收到新文件:{}".format(zip_file))
                if not os.path.exists(CACHE_DIR):
                    os.makedirs(CACHE_DIR)
    
                # 以及缓存文件名
                prefix = uuid.uuid4()
                file_name = '{}_{}'.format(prefix, zip_file.name)
                file_name = os.path.join(CACHE_DIR, file_name)
    
                # 打开特定的文件进行二进制的写操作;
                total_size = 0
                with open(file_name, 'wb+') as f:
                    # 分块写入文件;
                    for chunk in zip_file.chunks():
                        total_size += len(chunk)
                        if total_size > MAX_FILE_SIZE:
                            f.close()
                            return HttpResponse(f'文件大小超过{MAX_FILE_SIZE_MSG}.')
                        f.write(chunk)
                print('total_size', total_size)
                print("".rjust(60, '-'))
    
                global num
    
                if lock.locked():
                    return HttpResponse(f"任务{num}正在打包中,请稍后再试!")
    
                lock.acquire()
                num += 1
    
                # 处理压缩包并返回最终的userdata.bin
                userdata_bin, is_ok, err_msg = pack.pack_data(file_name, CACHE_DIR, prefix)
    
                lock.release()
    
                print('userdata_bin, is_ok:', userdata_bin, is_ok)
                if is_ok:
                    return download_file(request, userdata_bin)
                else:
                    return HttpResponse(err_msg)
        else:
            return render(request, 'upload.html')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61

    下载:

    def download_file(request, file_path):
        def file_iterator(the_file, chunk_size=512):
            with open(the_file, 'rb') as f:
                while True:
                    c = f.read(chunk_size)
    
                    if c:
                        yield c
                    else:
                        break
    
        response = StreamingHttpResponse(file_iterator(file_path))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format('userdata.bin')
        return response
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    静态资源文件使用包括2部分:
    1、基础配置参数 settings.py
    启用staticfiles,静态资源url地址static,配置静态文件的文件存放位置

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    STATIC_URL = 'static/'  
    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'statics'),
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2、页面使用

            {% load static %}
            <img src="{% static 'img/tree-design.png' %}" alt="My image">
    
    • 1
    • 2

    python 多线程锁

    import threading
    num = 0
    lock = threading.Lock()
    
    def upload_file(request):
        global num
    
        if lock.locked():
            return HttpResponse(f"任务{num}正在打包中,请稍后再试!")
    
        lock.acquire()
        num += 1
    
        # 处理压缩包并返回最终的userdata.bin
        # pack data
    
        lock.release()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Django中在相同域中使用iframe

    settings.py中设置:

    X_FRAME_OPTIONS = 'SAMEORIGIN'
    
    • 1
  • 相关阅读:
    Mallox勒索病毒:最新变种malloxx袭击了您的计算机?
    MySQL安装validate_password_policy插件
    RepVGG网络学习记录
    【Redis(4)】Redis主从复制模式配置示例
    基于Java毕业设计养老机构系统源码+系统+mysql+lw文档+部署软件
    二、代码块的加载顺序
    105. 从前序与中序遍历序列构造二叉树
    conda 的一些指令(jupyter notebook 在虚拟环境pytorch)
    计算机网络第4章-通用转发和SDN
    Linux常见操作命令(1)
  • 原文地址:https://blog.csdn.net/mlz_2/article/details/127094692