App下載

Python Django搭建文件下載服務(wù)器的實(shí)現(xiàn)

漫步云海澗 2021-08-21 11:00:55 瀏覽數(shù) (3575)
反饋

在我們的認(rèn)知中,服務(wù)器一般都是發(fā)送請求響應(yīng)的東西。但其實(shí)還有另外一種文件下載服務(wù)器,他們只負(fù)責(zé)文件的下載。這樣的服務(wù)器使用Django也可以實(shí)現(xiàn),那么怎么使用Django搭建一個文件下載服務(wù)器呢。來看這篇文章,小編帶你了解。

環(huán)境

  • win10
  • Python:3.6.7
  • Django:2.2.7

運(yùn)行效果

在這里插入圖片描述

1、創(chuàng)建 Django 項(xiàng)目

# 創(chuàng)建Download項(xiàng)目
django-admin startproject Download
# 創(chuàng)建down_app app
python manage.py startapp down_app

在這里插入圖片描述

在這里插入圖片描述

2、修改配置文件:settings.py

Download/Download/settings.py

1.添加注冊APP:down_app

在這里插入圖片描述

2.設(shè)置模板文件路徑:templates

在這里插入圖片描述

3、編寫視圖函數(shù):views.py

Download/down_app/views.py

import os
from django.http import HttpResponse
from django.http import StreamingHttpResponse


def image_down(request):
    """
    下載圖片
    """
    img_name = request.GET.get("username") + ".png"  # 二維碼圖片名
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 項(xiàng)目根目錄
    file_path = os.path.join(base_dir, 'antirisk/CodeGenerate/image/code', img_name)  # 二維碼的絕對路徑

    if not os.path.isfile(file_path):  # 判斷下載文件是否存在
        return HttpResponse("Sorry but Not Found the File")

    def file_iterator(file_path, chunk_size=512):
        """
        文件生成器,防止文件過大,導(dǎo)致內(nèi)存溢出
        :param file_path: 文件絕對路徑
        :param chunk_size: 塊大小
        :return: 生成器
        """
        with open(file_path, mode='rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    try:
        # 設(shè)置響應(yīng)頭
        # StreamingHttpResponse將文件內(nèi)容進(jìn)行流式傳輸,數(shù)據(jù)量大可以用這個方法
        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下載文件,這樣可以實(shí)現(xiàn)任意格式的文件下載
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是當(dāng)用戶想把請求所得的內(nèi)容存為一個文件的時(shí)候提供一個默認(rèn)的文件名
        response['Content-Disposition'] = f'attachment;filename="1.png"'  # 文件名不可設(shè)置為中文
    except:
        return HttpResponse("Sorry but Not Found the File")

    return response

4、修改路由配置:urls.py

Download/Download/urls.py

from django.contrib import admin
from django.urls import path, re_path
from down_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index),
    re_path('download/)', views.image_down, name="download"),
]

5、創(chuàng)建并編寫:index.html

Download/templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="/download/" rel="external nofollow" >下載圖片</a>
</body>
</html>

運(yùn)行

# 運(yùn)行項(xiàng)目
python manage.py runserver

在這里插入圖片描述

# 訪問: http://127.0.0.1:8000/

在這里插入圖片描述

到此這篇Python Django搭建文件下載服務(wù)器的實(shí)現(xiàn)的文章就介紹到這了,更多Django學(xué)習(xí)內(nèi)容請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持W3Cschool!


0 人點(diǎn)贊