国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

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

瀏覽:3日期:2022-07-28 14:44:42
環(huán)境 win10 Python:3.6.7 Django:2.2.7

運(yùn)行效果

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

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

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

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

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

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

Download/Download/settings.py

1.添加注冊APP:down_app

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

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

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

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

Download/down_app/views.py

import osfrom django.http import HttpResponsefrom django.http import StreamingHttpResponsedef 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 celse: 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)容存為一個文件的時候提供一個默認(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 adminfrom django.urls import path, re_pathfrom down_app import viewsurlpatterns = [ 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='http://www.intensediesel.com/download/' rel='external nofollow' >下載圖片</a></body></html>

運(yùn)行

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

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

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

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

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

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 宜君县| 东阳市| 海晏县| 白玉县| 宁国市| 合作市| 贞丰县| 江川县| 屏南县| 轮台县| 崇义县| 北流市| 西宁市| 岫岩| 丰镇市| 垫江县| 威远县| 桃园县| 精河县| 石河子市| 稷山县| 天门市| 五寨县| 右玉县| 岑溪市| 潞西市| 德格县| 五寨县| 柯坪县| 郧西县| 徐汇区| 桃园市| 友谊县| 墨江| 新巴尔虎右旗| 漳平市| 荥经县| 名山县| 黄冈市| 民县| 舒城县|