как остановить загрузку файла через wget по клику на кнопку?

Рейтинг: 0Ответов: 1Опубликовано: 06.08.2023

есть такой код:

from flet import *

import wget

def main(page: Page):
    url = "https://drive.google.com/uc?export=download&confirm=no_antivirus&id=10Vov9B3KDNM7mnQ5e1WTyd2zbx3qmkf_"

    def download():
        btn_download_map.visible = False
        btn_stop_download.visible = True
        btn_download_map.update()
        btn_stop_download.update()
        wget.download(url = url, bar = progress)
        btn_download_map.visible = True
        btn_stop_download.visible = False
        btn_download_map.update()
        btn_stop_download.update()

    def stop_download():
        btn_download_map.visible = True
        btn_stop_download.visible = False
        btn_download_map.update()
        btn_stop_download.update()


    btn_download_map = ElevatedButton(
    width = 200,
    height = 50,
    text = "Download",
    on_click = lambda _: download()
    )


    btn_stop_download = ElevatedButton(
    visible = False,
    width = 200,
    height = 50,
    text = "Stop",
    on_click = lambda _: stop_download()
    )

    def progress(current, total, width):
        progress_bar.value = current / total
        progress_bar.update()
        tx_progress.value = f"{int(current / 1024)} KB / {int(total / 1024)} KB"
        tx_progress.update()


    tx_progress = Text(value = "", style = "headlineSmall")
    progress_bar = ProgressBar(
    width = 250
    )

    map_downloader = Container(
    width = 300,
    height = 250,
    margin = 20,
    padding = 10,
    alignment = alignment.center,
    border = border.all(5, "black"),
    content = Column([
        Column([
            tx_progress,
            progress_bar
        ]),
        btn_download_map,
        btn_stop_download
    ], alignment = MainAxisAlignment.CENTER, horizontal_alignment = CrossAxisAlignment.CENTER)
    )
    
    page.add(map_downloader)


if __name__ == "__main__":
    app(target=main)

как при нажатии на кнопку стоп останавливать загрузку?

Ответы

▲ 0Принят

Для отображения прогресса каждые 4 килобайта в requests

with requests.get(url, stream=True) as r:
    r.raise_for_status()
    total = int(r.headers['content-length'])
    current = 0
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=4096): 
            f.write(chunk)
            current += len(chunk)
            progress(current,total,None) # ← тут