App下載

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

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

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

環(huán)境

  • win10
  • Python:3.6.7
  • Django:2.2.7

運行效果

在這里插入圖片描述

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

# 創(chuàng)建Download項目
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.設置模板文件路徑: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__)))  # 項目根目錄
    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):
        """
        文件生成器,防止文件過大,導致內存溢出
        :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:
        # 設置響應頭
        # StreamingHttpResponse將文件內容進行流式傳輸,數(shù)據量大可以用這個方法
        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下載文件,這樣可以實現(xiàn)任意格式的文件下載
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是當用戶想把請求所得的內容存為一個文件的時候提供一個默認的文件名
        response['Content-Disposition'] = f'attachment;filename="1.png"'  # 文件名不可設置為中文
    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>

運行

# 運行項目
python manage.py runserver

在這里插入圖片描述

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

在這里插入圖片描述

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


0 人點贊