python下載文件的兩種方式
前言
Python開發(fā)中時長遇到要下載文件的情況,最常用的方法就是通過Http利用urllib或者urllib2模塊。
當(dāng)然你也可以利用ftplib從ftp站點下載文件。此外Python還提供了另外一種方法requests。
下面來看看三兩種方式是如何來下載文件的:
1. 接口方式
對于flask1.0的版本可以使用如下方式(通過接口)
from flask import Flask, send_file, abort
app = Flask(__name__)
@app.route('/download/<filename>')
def download_file(filename):
try:
# 文件路徑
file_path = f'/path/to/your/files/{filename}'
# 確保文件存在
if not os.path.isfile(file_path):
abort(404) # 文件不存在,返回 404 錯誤
# 發(fā)送文件
return send_file(file_path, as_attachment=True, attachment_filename=filename)
except Exception as e:
# 捕獲異常并返回 500 錯誤
return str(e), 500
if __name__ == '__main__':
app.run(debug=True)
以上只是作為展示
如果是前后進行交互,基本的Demo如下:(flask2.0版本)
from flask import Blueprint, render_template, send_file
bp = Blueprint('main', __name__)
@bp.route('/')
def index():
return render_template('index.html')
@bp.route('/download')
def download():
# 假設(shè)壓縮包文件路徑為 '/path/to/your/file.zip'
file_path = '/root/xx.rar'
return send_file(file_path, as_attachment=True, download_name='xx.rar')
對于前端的按鈕配置如下:
<button onclick="downloadFile()">下載壓縮包</button> <!-- 新增的下載按鈕 -->
后續(xù)只需要把對應(yīng)文件放置在相應(yīng)位置即可
截圖如下:

2. Nginx
總體配置如下:
server {
listen 80;
server_name ip地址;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /downloads/ {
alias /root/;
autoindex on; # 啟用目錄索引(可選)
}
# Redirect HTTP to HTTPS
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
server_name ip地址;
ssl_certificate /etc/letsencrypt/live/your_domain/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your_domain/privkey.pem;
location / {
proxy_pass http://127.0.0.1:5000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /downloads/ {
alias /root/;
autoindex on; # 啟用目錄索引(可選)
}
}
請確保替換 /etc/letsencrypt/live/your_domain/fullchain.pem 和 /etc/letsencrypt/live/your_domain/privkey.pem 路徑為 Certbot 創(chuàng)建的證書路徑
到此這篇關(guān)于python下載文件的兩種方式的文章就介紹到這了,更多相關(guān)python下載文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Python構(gòu)建深度學(xué)習(xí)圖像分類模型
在人工智能的浪潮中,圖像分類作為計算機視覺領(lǐng)域的基礎(chǔ)任務(wù)之一,一直備受關(guān)注,本文將介紹如何使用Python和PyTorch框架,構(gòu)建一個簡單的深度學(xué)習(xí)圖像分類模型,感興趣的可以了解下2024-12-12

