你的第一個(gè)網(wǎng)站
先安裝一個(gè)框架
$ sudo pip install lpthw.web
所謂框架通常是指讓某件事情做起來更容易的軟件包。
項(xiàng)目骨架
.
├── bin
│ ── app.py
│
├── docs
├── gothonweb
│ └── __init__.py
├── templates
│ └── index.html
└── tests
└── __init__.py
5 directories, 4 files
web應(yīng)用
import web
urls = ('/','Index')
app = web.application(urls,globals())
class Index(object):
def GET(self):
greeting = "Hello World"
return greeting
if __name__ == '__main__':
app.run()
運(yùn)行程序后,打開鏈接,頁面上會(huì)顯示Hello World
模板
創(chuàng)建一個(gè)templates/index.html文件
$def with (greeting)
<html>
<head>
<title>Gothons Of Planet Percal #25</title>
</head>
<body>
$if greeting:
I just wanted to say <em style="color: green; font-size:2em;">$greeting</em>.
$else:
<em>Hello</em>, world!
</body>
</html>
在程序中調(diào)用模板
import web
urls = ('/','Index')
app = web.application(urls,globals())
render = web.template.render('templates/')
class Index(object):
def GET(self):
greeting = "Hello World"
return render.index(greeting = greeting)
if __name__ == '__main__':
app.run()
但運(yùn)行后,提示
AttributeError: No template named index
Google后發(fā)現(xiàn)是模板路徑問題
看上面的骨架目錄,app.py位于bin目錄下,index模板位于與bin平行的templates目錄下
所以有兩種方法解決這個(gè)問題
- 將templates目錄復(fù)制到app.py所在的目錄
- 將語句中的相對(duì)路徑
render = web.template.render('templates/')改為絕對(duì)路徑render = web.template.render('/home/damao/Documents/gothonweb/templates/')
完成后,即可正常打開經(jīng)過模板渲染的網(wǎng)頁
I just wanted to say Hello World.