《笨辦法學(xué)Python》筆記37-----你的第一個(gè)網(wǎng)站

你的第一個(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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容