Sanic static() 方法/函数

Sanic教程 2019-06-04 17:34:24 阅读(5200) 评论(0)

Sanic 类的static()方法的API接口。

Sanic static() 方法函数

static() 方法/函数

定义

static(uri, file_or_directory, pattern='/?.+', use_modified_since=True, use_content_range=False, stream_large_files=False, name='static', host=None, strict_slashes=None, content_type=None)

注册提供文件的跟目录。输入可以是文件或目录。 此方法将使用简单方便的方法来设置提供静态文件所需的路由。

参数

  • uri : 用来提供静态内容的URL路径
  • file_or_directory: 静态文件的路径,或含有静态文件的目录的路径。
  • pattern:识别有效静态文件的正则表达式。
  • use_modified_since:如果为true,则发送文件修改时间,如果浏览器与服务器匹配,则返回未修改。
  • use_content_range: 如果为true,为范围请求处理请求头,并返回请求的文件片段。
  • stream_large_file:如果为true,使用StreamingHTTPResponse.file_stream() 替代 HTTPResponse.file()。如果这是一个整数,则表示切换到StreamingHTTPResponse.file_stream()的阈值大小。
  • name:用户为url_for() 定义的名字。
  • host : 服务运行的HOST IP 地址或FQDN。
  • strict_slashes:是否检查请求URL结尾的斜杠/。
  • content_type:用户为请求头定义的内容类型。

返回值
无。

例子

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)

猿人学banner宣传图

我的公众号:猿人学 Python 上会分享更多心得体会,敬请关注。

***版权申明:若没有特殊说明,文章皆是猿人学 yuanrenxue.con 原创,没有猿人学授权,请勿以任何形式转载。***

说点什么吧...