婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > 90行Python代碼開發(fā)個人云盤應用

90行Python代碼開發(fā)個人云盤應用

熱門標簽:上海機器人外呼系統(tǒng)哪家好 地圖制圖標注位置改變是移位嗎 地圖標注微信發(fā)送位置不顯示 蓋州市地圖標注 南京銷售外呼系統(tǒng)軟件 浙江電銷卡外呼系統(tǒng)好用嗎 地圖標注的意義點 房產(chǎn)電銷外呼系統(tǒng) 315電話機器人廣告

本文示例代碼已上傳至我的Github倉庫https://github.com/CNFeffery/DataScienceStudyNotes

1 簡介

在今天的教程中,我們將介紹如何在Dash中高效地開發(fā)web應用中非常重要的「文件上傳」及「下載」功能。

2 在Dash中實現(xiàn)文件上傳與下載

2.1 在Dash中配合dash-uploader實現(xiàn)文件上傳

其實在自帶的dash_core_components中就封裝了基于html5原生API的dcc.Upload()組件,可以實現(xiàn)簡單的文件上傳功能,但說實話,非常的「不好用」,其主要缺點有:

  • 「文件大小有限制,150M到200M左右即出現(xiàn)瓶頸」
  • 「策略是先將用戶上傳的文件存放在瀏覽器內(nèi)存,再通過base64形式傳遞到服務端再次解碼,非常低效」
  • 「整個上傳過程無法配合準確的進度條」

正是因為Dash自帶的上傳部件如此不堪,所以一些優(yōu)秀的第三方拓展涌現(xiàn)出來,其中最好用的要數(shù)dash-uploader,它解決了上面提到的dcc.Upload()的所有短板。通過pip install dash-uploader進行安裝之后,就可以直接在Dash應用中使用了。

我們先從極簡的一個例子出發(fā),看一看在Dash中使用dash-uploader的正確姿勢:

app1.py

import dash
import dash_uploader as du
import dash_bootstrap_components as dbc
import dash_html_components as html

app = dash.Dash(__name__)

# 配置上傳文件夾
du.configure_upload(app, folder='temp')

app.layout = html.Div(
    dbc.Container(
        du.Upload()
    )
)

if __name__ == '__main__':
    app.run_server(debug=True)

可以看到,僅僅十幾行代碼,我們就配合dash-uploader實現(xiàn)了簡單的文件上傳功能,其中涉及到dash-uploader兩個必不可少的部分:

2.1.1 利用du.configure_upload()進行配置

要在Dash中正常使用dash-uploader,我們首先需要利用du.configure_upload()進行相關配置,其主要參數(shù)有:

「app」,即對應已經(jīng)實例化的Dash對象;

「folder」,用于設置上傳的文件所保存的根目錄,可以是相對路徑,也可以是絕對路徑;

「use_upload_id」,bool型,默認為True,這時被用戶上傳的文件不會直接置于「folder」參數(shù)指定目錄,而是會存放于du.Upload()部件的upload_id對應的子文件夾之下;設置為False時則會直接存放在根目錄,當然沒有特殊需求還是不要設置為False。

通過du.configure_upload()我們就完成了基本的配置。

2.1.2 利用du.Upload()創(chuàng)建上傳部件

接下來我們就可以使用到du.Upload()來創(chuàng)建在瀏覽器中渲染供用戶使用的上傳部件了,它跟常規(guī)的Dash部件一樣具有「id」參數(shù),也有一些其他的豐富的參數(shù)供開發(fā)者充分自由地自定義功能和樣式:

「text」,字符型,用于設置上傳部件內(nèi)顯示的文字;

「text_completed」,字符型,用于設置上傳完成后顯示的文字內(nèi)容前綴;

「cancel_button」,bool型,用于設置是否在上傳過程中顯示“取消”按鈕;

「pause_button」,bool型,用于設置是否在上傳過程中顯示“暫停”按鈕;

「filetypes」,用于限制用戶上傳文件的格式范圍,譬如['zip', 'rar', '7zp']就限制用戶只能上傳這三種格式的文件。默認為None即無限制;

「max_file_size」,int型,單位MB,用于限制單次上傳的大小上限,默認為1024即1GB;

「default_style」,類似常規(guī)Dash部件的style參數(shù),用于傳入css鍵值對,對部件的樣式進行自定義;

「upload_id」,用于設置部件的唯一id信息作為du.configure_upload()中所設置的緩存根目錄的下級子目錄,用于存放上傳的文件,默認為None,會在Dash應用啟動時自動生成一個隨機值;

「max_files」,int型,用于設置一次上傳最多可包含的文件數(shù)量,默認為1,也推薦設置為1,因為目前對于多文件上傳仍有「進度條異常」、「上傳結束顯示異常」等bug,所以不推薦設置大于1。

知曉了這些參數(shù)的作用之后,我們就可以創(chuàng)建出更符合自己需求的上傳部件:

app2.py

import dash
import dash_uploader as du
import dash_bootstrap_components as dbc
import dash_html_components as html

app = dash.Dash(__name__)

# 配置上傳文件夾
du.configure_upload(app, folder='temp')

app.layout = html.Div(
    dbc.Container(
        du.Upload(
            id='uploader',
            text='點擊或拖動文件到此進行上傳!',
            text_completed='已完成上傳文件:',
            cancel_button=True,
            pause_button=True,
            filetypes=['md', 'mp4'],
            default_style={
                'background-color': '#fafafa',
                'font-weight': 'bold'
            },
            upload_id='我的上傳'
        )
    )
)

if __name__ == '__main__':
    app.run_server(debug=True)

但像前面的例子那樣直接在定義app.layout時就傳入實際的du.Upload()部件,會產(chǎn)生一個問題——應用啟動后,任何訪問應用的用戶都對應一樣的upload_id,這顯然不是我們期望的,因為不同用戶的上傳文件會混在一起。

因此可以參考下面例子的方式,在每位用戶訪問時再渲染隨機id的上傳部件,從而確保唯一性:

app3.py

import dash
import dash_uploader as du
import dash_bootstrap_components as dbc
import dash_html_components as html

import uuid

app = dash.Dash(__name__)

# 配置上傳文件夾
du.configure_upload(app, folder='temp')

def render_random_id_uploader():

    return du.Upload(
            id='uploader',
            text='點擊或拖動文件到此進行上傳!',
            text_completed='已完成上傳文件:',
            cancel_button=True,
            pause_button=True,
            filetypes=['md', 'mp4'],
            default_style={
                'background-color': '#fafafa',
                'font-weight': 'bold'
            },
            upload_id=uuid.uuid1()
        )

def render_layout():

    return html.Div(
    dbc.Container(
        render_random_id_uploader()
    )
)

app.layout = render_layout

if __name__ == '__main__':
    app.run_server(debug=True)

可以看到,每次訪問時由于upload_id不同,因此不同的會話擁有了不同的子目錄。

2.1.3 配合du.Upload()進行回調(diào)

在du.Upload()中額外還有isCompleted與fileNames兩個屬性,前者用于判斷當前文件是否上傳完成,后者則對應此次上傳的文件名稱,參考下面這個簡單的例子:

app4.py

import dash
import dash_uploader as du
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State

app = dash.Dash(__name__)

# 配置上傳文件夾
du.configure_upload(app, folder='temp')

app.layout = html.Div(
    dbc.Container(
        [
            du.Upload(id='uploader'),
            html.H5('上傳中或還未上傳文件!', id='upload_status')
        ]
    )
)


@app.callback(
    Output('upload_status', 'children'),
    Input('uploader', 'isCompleted'),
    State('uploader', 'fileNames')
)
def show_upload_status(isCompleted, fileNames):
    if isCompleted:
        return '已完成上傳:'+fileNames[0]

    return dash.no_update


if __name__ == '__main__':
    app.run_server(debug=True, port=8051)

2.2 配合flask進行文件下載

相較于文件上傳,在Dash中進行文件的下載就簡單得多,因為我們可以配合flask的send_from_directory以及html.A()部件來為指定的服務器端文件創(chuàng)建下載鏈接,譬如下面的簡單示例就打通了文件的上傳與下載:

app5.py

from flask import send_from_directory
import dash
import dash_uploader as du
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
import os

app = dash.Dash(__name__)

du.configure_upload(app, 'temp', use_upload_id=False)

app.layout = html.Div(
    dbc.Container(
        [
            du.Upload(id='upload'),
            html.Div(
                id='download-files'
            )
        ]
    )
)

@app.server.route('/download/file>')
def download(file):

    return send_from_directory('temp', file)

@app.callback(
    Output('download-files', 'children'),
    Input('upload', 'isCompleted')
)
def render_download_url(isCompleted):

    if isCompleted:
        return html.Ul(
            [
                html.Li(html.A(f'/{file}', href=f'/download/{file}', target='_blank'))
                for file in os.listdir('temp')
            ]
        )

    return dash.no_update

if __name__ == '__main__':
    app.run_server(debug=True)

3 用Dash編寫簡易個人網(wǎng)盤應用

在學習了今天的案例之后,我們就掌握了如何在Dash中開發(fā)文件上傳及下載功能,下面我們按照慣例,結合今天的主要內(nèi)容,來編寫一個實際的案例;

今天我們要編寫的是一個簡單的個人網(wǎng)盤應用,我們可以通過瀏覽器訪問它,進行文件的上傳、下載以及刪除:

import dash
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import dash_uploader as du
import os
from flask import send_from_directory
import time

app = dash.Dash(__name__, suppress_callback_exceptions=True)

du.configure_upload(app, 'NetDisk', use_upload_id=False)

app.layout = html.Div(
    dbc.Container(
        [
            html.H3('簡易的個人云盤應用'),
            html.Hr(),
            html.P('文件上傳區(qū):'),
            du.Upload(id='upload',
                      text='點擊或拖動文件到此進行上傳!',
                      text_completed='已完成上傳文件:',
                      max_files=1000),
            html.Hr(),
            dbc.Row(
                [
                    dbc.Button('刪除選中的文件', id='delete-btn', outline=True),
                    dbc.Button('打包下載選中的文件', id='download-btn', outline=True)
                ]
            ),
            html.Hr(),
            dbc.Spinner(
                dbc.Checklist(
                    id='file-list-check'
                )
            ),
            html.A(id='download-url', target='_blank')
        ]
    )
)


@app.server.route('/download/file>')
def download(file):
    return send_from_directory('NetDisk', file)


@app.callback(
    [Output('file-list-check', 'options'),
     Output('download-url', 'children'),
     Output('download-url', 'href')],
    [Input('upload', 'isCompleted'),
     Input('delete-btn', 'n_clicks'),
     Input('download-btn', 'n_clicks')],
    State('file-list-check', 'value')
)
def render_file_list(isCompleted, delete_n_clicks, download_n_clicks, check_value):
    # 獲取上下文信息
    ctx = dash.callback_context

    if ctx.triggered[0]['prop_id'] == 'delete-btn.n_clicks':

        for file in check_value:
            try:
                os.remove(os.path.join('NetDisk', file))
            except FileNotFoundError:
                pass

    if ctx.triggered[0]['prop_id'] == 'download-btn.n_clicks':

        import zipfile

        with zipfile.ZipFile('NetDisk/打包下載.zip', 'w') as zipobj:
            for file in check_value:
                try:
                    zipobj.write(os.path.join('NetDisk', file))
                except FileNotFoundError:
                    pass

        return [
                   {'label': file, 'value': file}
                   for file in os.listdir('NetDisk')
                   if file != '打包下載.zip'
               ], '打包下載鏈接', '/download/打包下載.zip'

    time.sleep(2)

    return [
               {'label': file, 'value': file}
               for file in os.listdir('NetDisk')
               if file != '打包下載.zip'
           ], '', ''


if __name__ == '__main__':
    app.run_server(debug=True)

以上就是90行Python代碼開發(fā)個人云盤應用的詳細內(nèi)容,更多關于python 開發(fā)個人云盤的資料請關注腳本之家其它相關文章!

您可能感興趣的文章:
  • python 實現(xiàn)百度網(wǎng)盤非會員上傳超過500個文件的方法
  • Python 一鍵獲取百度網(wǎng)盤提取碼的方法
  • Python使用百度API上傳文件到百度網(wǎng)盤代碼分享
  • Python實現(xiàn)115網(wǎng)盤自動下載的方法
  • Python解析網(wǎng)頁源代碼中的115網(wǎng)盤鏈接實例

標簽:赤峰 克拉瑪依 雙鴨山 陽泉 貴州 臨汾 金華 日照

巨人網(wǎng)絡通訊聲明:本文標題《90行Python代碼開發(fā)個人云盤應用》,本文關鍵詞  90行,Python,代碼,開發(fā),個,;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《90行Python代碼開發(fā)個人云盤應用》相關的同類信息!
  • 本頁收集關于90行Python代碼開發(fā)個人云盤應用的相關信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 南汇区| 东莞市| 上饶县| 望都县| 民和| 江源县| 乌审旗| 土默特右旗| 来宾市| 游戏| 海兴县| 织金县| 名山县| 武清区| 溧水县| 宣恩县| 梓潼县| 锦屏县| 芦山县| 忻州市| 湖北省| 东光县| 保康县| 定陶县| 安化县| 漠河县| 东安县| 西乌珠穆沁旗| 麻栗坡县| 竹山县| 巴马| 兰考县| 沙雅县| 东平县| 宣化县| 金寨县| 绵阳市| 瓮安县| 安岳县| 惠州市| 嘉鱼县|