溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

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

發(fā)布時(shí)間:2021-05-10 15:07:05 來(lái)源:億速云 閱讀:276 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹Python Django搭建文件下載服務(wù)器的實(shí)現(xiàn)shili ,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

環(huán)境

  • win10

  • Python:3.6.7

  • Django:2.2.7

運(yùn)行效果

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

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

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

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

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

Download/Download/settings.py

1.添加注冊(cè)APP:down_app

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

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

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

3、編寫(xiě)視圖函數(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)  # 二維碼的絕對(duì)路徑

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

    def file_iterator(file_path, chunk_size=512):
        """
        文件生成器,防止文件過(guò)大,導(dǎo)致內(nèi)存溢出
        :param file_path: 文件絕對(duì)路徑
        :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ù)量大可以用這個(gè)方法
        response = StreamingHttpResponse(file_iterator(file_path))
        # 以流的形式下載文件,這樣可以實(shí)現(xiàn)任意格式的文件下載
        response['Content-Type'] = 'application/octet-stream'
        # Content-Disposition就是當(dāng)用戶(hù)想把請(qǐng)求所得的內(nèi)容存為一個(gè)文件的時(shí)候提供一個(gè)默認(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)建并編寫(xiě):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

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

# 訪問(wèn): http://127.0.0.1:8000/

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

以上是“Python Django搭建文件下載服務(wù)器的實(shí)現(xiàn)shili ”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI