Python3 --- Tornado之静态资源

一、通过static_path实现

import tornado.web
import tornado.ioloop
import tornado.httpserver
import os

from tornado.options import define, options

define("port", default=8002, help="run on the given port", type=int)


class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("aaa")


handlers = [(r"/", IndexHandler), ]

settings = dict(
    static_path = os.path.join(os.path.dirname(__file__),"statics"),  # 为了便于部署,建议使用static
    static_url_prefix = "/page/"  # 默认使用的是static,为了便于部署,建议使用static
)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers, **settings, debug=True)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

 

二、通过StaticFileHandler实现

tornado.web.StaticFileHandler是tornado预置的用来提供静态资源文件的handler。

import tornado.web
import tornado.ioloop
import tornado.httpserver
import os

from tornado.options import define, options

define("port", default=8002, help="run on the given port", type=int)

current_path = os.path.dirname(__file__)
handlers = [(r"/(.*)", tornado.web.StaticFileHandler, {"path":os.path.join(current_path, "statics/html"), "default_filename":"index.html"})]

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers, static_path=os.path.join(current_path, "statics"), debug=True)
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

参数说明:

  • path:用来指明提供静态文件的根路径,并在此目录中寻找在路由中用正则表达式提取的文件名。
  • default_filename:用来指定访问路由中未指明文件名时,默认提供的文件。

 

三、通过Template实现

import tornado.web
import tornado.ioloop
import tornado.httpserver
import os

from tornado.options import define, options


define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html",price1=100,price2=200)

current_path = os.path.dirname(__file__)
handlers = [
    (r"/",IndexHandler),
]

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers,
        static_path = os.path.join(current_path,"static"),
        template_path = os.path.join(current_path, "template"),
        debug=True
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值