1.手工創(chuàng)建文件夾用于存放網(wǎng)頁(yè)模板以及靜態(tài)文件

image.png
2.實(shí)現(xiàn)代碼
demo.py
"""
tornado web app對(duì)于網(wǎng)頁(yè)模板的處理和靜態(tài)文件的操作
網(wǎng)頁(yè)模板:html頁(yè)面
處理:定義html頁(yè)面、渲染html頁(yè)面,響應(yīng)html頁(yè)面[瀏覽器]
靜態(tài)資源:圖片/js/css/字體...
操作:配置靜態(tài)資源、查詢(xún)靜態(tài)資源[html]、響應(yīng)數(shù)據(jù)
"""
# 引入需要的模塊
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.options import define, options, parse_command_line
from tornado.httpserver import HTTPServer
import os.path
# 定義變量
define("port", default=8000, help="默認(rèn)端口8000")
# 創(chuàng)建視圖類(lèi)
class IndexHandler(RequestHandler):
def get(self):
msg = "hello,零"
self.render("index.html", info=msg)
# 程序入口
if __name__ == '__main__':
# 開(kāi)始監(jiān)聽(tīng)
parse_command_line()
app = Application(
[
(r'/', IndexHandler)
],
# 項(xiàng)目配置信息
# 網(wǎng)頁(yè)模板
template_path=os.path.join(os.path.dirname(__file__), "templates"),
# 靜態(tài)文件
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True
)
# 部署
server = HTTPServer(app)
server.listen(options.port)
# 輪詢(xún)監(jiān)聽(tīng)
IOLoop.current().start()
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!--<link rel="stylesheet" href="/static/css/index.css">-->
<link rel="stylesheet" href="{{static_url('css/index.css')}}">
</head>
<body>
<h1>hello</h1>
<h1>{{info}}</h1>
</body>
</html>
注意:
Tornado模板模塊提供了一個(gè)叫作static_url的函數(shù)來(lái)生成static目錄下文件的URL。
在index.html中static_url的調(diào)用的示例代碼:
<link rel="stylesheet" href="{{static_url('css/index.css')}}">
這個(gè)對(duì)static_url的調(diào)用生成了URL的值,并渲染輸出類(lèi)似下面的代碼:
<link rel="stylesheet" href="/static/css/index.css">