要开发WEB的话,就需要涉及到相关的静态资源,如CSS,JS,图片,字体等,bottle有个函数static_file() 用来提供静态文件服务。它会自动猜测文件的 mime-type,添加 Last-Modified 头。当然你也可指定 MIME 类型来避免其自动猜测。
设置静态资源访问路由,要设置route,如@route('/images/<filename:re:.*\.png>') ,/image,是url访问路径,/<filename:re:.*\.png>' 是一个正则匹配,如匹配以.png结尾的所有文件,如果是jpg图片,即可以用*\.jpg,如果是css或js则用.*\.css,.*\.js。
然后调用bottle static_file()方法,static_file(filename, root=images_path) :filename是url里匹配到的文件名,root是图片等静态资源存放路径。最后,程序就会根据这设置好的路由,去找到相关的文件,并在浏览器显示出来。
以下是一个显示图片的代码:
- [root@linuxyw bottle]# cat main.py
- #/usr/bin/env python
- #coding=utf-8
- from bottle import route, run
- from bottle import template,static_file
- #定义图片路径
- images_path = './images'
- @route('/images/<filename:re:.*\.png>')
- def server_static(filename):
- return static_file(filename, root=images_path)
- @route('/')
- def index():
- return template('index')
- run(host='0.0.0.0', port=8080, debug=True)
在main.py当前目录下,再创建一个images目录,用来存放图片,这图片我已放在SVN,可SVN UP出来直接用就好了,看下目录结构:
- [root@linuxyw bottle]# tree
- .
- ├── images
- │ └── linuxyw.png #这是一张图片
- ├── main.py
- └── views
- └── index.tpl
看下index.tpl代码,就是在首页中,显示这张图片,注意img 路径:
- [root@linuxyw bottle]# cat views/index.tpl
- <html>
- <head>
- </head>
- <body>
- <p>图片</p>
- <p><img src="/images/linuxyw.png"></img></p>
- </body>
- </html>
用浏览器访问看效果:
在实际中,我们可能有很多图片类型,如png,jpg,gif,样式有css,js等,如果每一个类型就要设置一个路由的话,就太麻烦了,其实,我们可以用 | 来匹配多种类型:
- @route('/assets/<filename:re:.*\.css|.*\.js|.*\.png|.*\.jpg|.*\.gif>')
- def server_static(filename):
- """定义/assets/下的静态(css,js,图片)资源路径"""
- return static_file(filename, root=assets_path)
- @route('/assets/<filename:re:.*\.ttf|.*\.otf|.*\.eot|.*\.woff|.*\.svg|.*\.map>')
- def server_static(filename):
- """定义/assets/字体资源路径"""
- return static_file(filename, root=assets_path)
更多的功能,可以查看bottle官网文档或其它教程
官方文档:http://www.bottlepy.org/docs/dev/index.html
SVN请跳转至:python bottle框架(WEB开发、运维开发)教程目录
这些代码已提交到SVN中,有需要的朋友可在SVN下载
2016 年 5 月 20 日 下午 4:18 沙发
不知道为什么,我用你的代码用template显示图片显示不了,图片用相对路径和绝对路径都不行,我用的是ubuntu系统
2016 年 5 月 23 日 下午 6:00 1层
@qq 路径资源访问那里没写好吧
来自外部的引用: 1