静态资源

静态文件和目录,如图像文件,会在注册 app.static 方法后提供服务。该方法采用端 URL 和文件名。指定的文件将通过给定的端被访问。

  1. from sanic import Sanic
  2. from sanic.blueprints import Blueprint
  3. app = Sanic(__name__)
  4. # Serves files from the static folder to the URL /static
  5. app.static('/static', './static')
  6. # use url_for to build the url, name defaults to 'static' and can be ignored
  7. app.url_for('static', filename='file.txt') == '/static/file.txt'
  8. app.url_for('static', name='static', filename='file.txt') == '/static/file.txt'
  9. # Serves the file /home/ubuntu/test.png when the URL /the_best.png
  10. # is requested
  11. app.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
  12. # you can use url_for to build the static file url
  13. # you can ignore name and filename parameters if you don't define it
  14. app.url_for('static', name='best_png') == '/the_best.png'
  15. app.url_for('static', name='best_png', filename='any') == '/the_best.png'
  16. # you need define the name for other static files
  17. app.static('/another.png', '/home/ubuntu/another.png', name='another')
  18. app.url_for('static', name='another') == '/another.png'
  19. app.url_for('static', name='another', filename='any') == '/another.png'
  20. # also, you can use static for blueprint
  21. bp = Blueprint('bp', url_prefix='/bp')
  22. bp.static('/static', './static')
  23. # servers the file directly
  24. bp.static('/the_best.png', '/home/ubuntu/test.png', name='best_png')
  25. app.blueprint(bp)
  26. app.url_for('static', name='bp.static', filename='file.txt') == '/bp/static/file.txt'
  27. app.url_for('static', name='bp.best_png') == '/bp/test_best.png'
  28. app.run(host="0.0.0.0", port=8000)