笨办法学Pythonpython

《笨办法学Python》笔记37-----你的第一个网站

2016-07-24  本文已影响309人  大猫黄

你的第一个网站

先安装一个框架

$ sudo pip install lpthw.web

所谓框架通常是指让某件事情做起来更容易的软件包。

项目骨架

.
├── bin
│   ── app.py
│  
├── docs
├── gothonweb
│   └── __init__.py
├── templates
│   └── index.html
└── tests
    └── __init__.py

5 directories, 4 files

web应用

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()

运行程序后,打开链接,页面上会显示Hello World

模板

创建一个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>

在程序中调用模板

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()

但运行后,提示

AttributeError: No template named index

Google后发现是模板路径问题

看上面的骨架目录,app.py位于bin目录下,index模板位于与bin平行的templates目录下

所以有两种方法解决这个问题

完成后,即可正常打开经过模板渲染的网页

I just wanted to say Hello World.

上一篇 下一篇

猜你喜欢

热点阅读