前言
python开发中时长遇到要下载文件的情况,最常用的方法就是通过http利用urllib或者urllib2模块。
当然你也可以利用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 错误
# 发送文件
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():
# 假设压缩包文件路径为 '/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> <!-- 新增的下载按钮 -->
后续只需要把对应文件放置在相应位置即可
截图如下:

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 创建的证书路径
到此这篇关于python下载文件的两种方式的文章就介绍到这了,更多相关python下载文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论