设置文件下载,还是有上篇文章讲到的static_file()方法,只不过是我们多添加了个参数:download=filename,这是告诉程序,我可强制下载这个文件,如果不用这个参数,而且你的文件又是html的话,一点击这个文件,可能就在浏览器显示出来,而不是下载下来。
- #/usr/bin/env python
- #coding=utf-8
- from bottle import route, run
- from bottle import template,static_file
- #定义下载路径
- download_path = './download'
- #强制文件下载
- @route('/download/<filename:path>')
- def download(filename):
- return static_file(filename, root=download_path, download=filename)
- @route('/')
- def index():
- return template('index')
- run(host='0.0.0.0', port=8080, debug=True)
index.tpl模板代码:
- [root@linuxyw bottle]# cat views/index.tpl
- <html>
- <head>
- </head>
- <body>
- </p>
- <a href="/download/linuxyw.png">点击下载</a>
- </body>
- </html>
在main.py当前目录创建一个download目录,然后上传一张图片,叫linuxyw.png,这张图片和相关代码,已上传到SVN,程序目录:
- [root@linuxyw bottle]# tree
- .
- ├── download
- │ └── linuxyw.png
- ├── main.py
- └── views
- └── index.tpl
更多的功能,可以查看bottle官网文档或其它教程
官方文档:http://www.bottlepy.org/docs/dev/index.html
SVN请跳转至:python bottle框架(WEB开发、运维开发)教程目录
这些代码已提交到SVN中,有需要的朋友可在SVN下载
来自外部的引用: 1