赞
踩
你的鼓励是我前进的动力,请为我点个赞吧!
静态文件和文件夹例如图片等静态资源,都是可以通过app.static进行定义,并且服务与sanic的文档。该需要两个参数,一个时url,一个是文件名字,文件将指向。
from sanic import Sanic from sanic.blueprints import Blueprint app = Sanic(__name__) # Serves files from the static folder to the URL /static app.static('/static', './static') # use url_for to build the url, name defaults to 'static' and can be ignored app.url_for('static', filename='file.txt') == '/static/file.txt' app.url_for('static', name='static', filename='file.txt') == '/static/file.txt' # Serves the file /home/ubuntu/test.png when the URL /the_best.png # is requested app.static('/the_best.png', '/home/ubuntu/test.png', name='best_png') # you can use url_for to build the static file url # you can ignore name and filename parameters if you don't define it app.url_for('static', name='best_png') == '/the_best.png' app.url_for('static', name='best_png', filename='any') == '/the_best.png' # you need define the name for other static files app.static('/another.png', '/home/ubuntu/another.png', name='another') app.url_for('static', name='another') == '/another.png' app.url_for('static', name='another', filename='any') == '/another.png' # also, you can use static for blueprint bp = Blueprint('bp', url_prefix='/bp') bp.static('/static', './static') # servers the file directly bp.static('/the_best.png', '/home/ubuntu/test.png', name='best_png') app.blueprint(bp) app.url_for('static', name='bp.static', filename='file.txt') == '/bp/static/file.txt' app.url_for('static', name='bp.best_png') == '/bp/test_best.png' app.run(host="0.0.0.0", port=8000)
需要注意的是: Sanic不提供文件夹文件夹索引功能。
(1)虚拟地址
app.static方法提供虚拟host,如下所示:
from sanic import Sanic
app = Sanic(__name__)
app.static('/static', './static')
app.static('/example_static', './example_static', host='www.example.com')
(2)大文件的流
有些情况下,开发者可能使用流比较大的服务器,开发者可以streaming file而不是直接下载文件。具体示例如下:
from sanic import Sanic
app = Sanic(__name__)
app.static('/large_video.mp4', '/home/ubuntu/large_video.mp4', stream_large_files=True)
当stream_large_file设置为Ture时,sanic使用file_stream()代替file()用于静态文件,文件传送时将会默认数据块为1kb,开发者可以根据自己需要进行设置。
from sanic import Sanic
app = Sanic(__name__)
chunk_size = 1024 * 1024 * 8 # Set chunk size to 8KB
app.static('/large_video.mp4', '/home/ubuntu/large_video.mp4', stream_large_files=chunk_size)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。