一、通过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()