Tornadao—静态文件

目录

  1. static_path
  2. static
  3. StaticFileHandler

  • static_path


    static_path
    我们可以通过向web.Application类的构造函数传递⼀个名为static_path的参数来
    告诉Tornado从⽂件系统的⼀个特定位置提供静态⽂件,如:
    
    app = tornado.web.Application(
     [(r'/', IndexHandler)],
     static_path=os.path.join(os.path.dirname(__file__), "statics"),
    )
    
    
    在这⾥,我们设置了⼀个当前应⽤⽬录下名为statics的⼦⽬录作为static_path的参
    数。现在应⽤将以读取statics⽬录下的filename.ext来响应诸
    如/static/filename.ext的请求,并在响应的主体中返回。
    
    
  • static


    对于静态⽂件⽬录的命名,为了便于部署,建议使⽤static
    对于我们提供的静态⽂件资源,可以通过
    http://127.0.0.1/static/html/index.html 来访问。⽽且在index.html中引⽤的
    静态资源⽂件,我们给定的路径也符合/static/...的格式,故⻚⾯可以正常浏览。
    
    <link href="/static/plugins/bootstrap/css/bootstrap.min.css"
    rel="stylesheet"> <link href="/static/plugins/font-awesome/css/font-awesome.min.css"
    rel="stylesheet"> <link href="/static/css/reset.css" rel="stylesheet"> <link href="/static/css/main.css" rel="stylesheet"> <link href="/static/css/index.css" rel="stylesheet"> <script src="/static/js/jquery.min.js"></script> <script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script> <script src="/static/js/index.js"></script>
  • StaticFileHandler


    StaticFileHandler
    我们再看刚刚访问⻚⾯时使⽤的路径
    http://127.0.0.1/static/html/index.html ,这中url显然对⽤户是不友好的,访
    问很不⽅便。我们可以通过tornado.web.StaticFileHandler来⾃由映射静态⽂
    件与其访问路径url。
    tornado.web.StaticFileHandler是tornado预置的⽤来提供静态资源⽂件的
    handler。
    
    import os
    current_path = os.path.dirname(__file__)
    app = tornado.web.Application(
     [
     (r'^/()$', StaticFileHandler, {"path":os.path.join(current_path, "statics/html"),
    "default_filename":"index.html"}),
     (r'^/view/(.*)$', StaticFileHandler, {"path":os.path.join(current_path, "statics/html")}),
     ],
     static_path=os.path.join(current_path, "statics"),
    )
发布了258 篇原创文章 · 获赞 6 · 访问量 3535

猜你喜欢

转载自blog.csdn.net/piduocheng0577/article/details/105060762