web.py轻量级开发框架——python的超轻量级服务器

By | 2014/05/12

上次介绍了python的sqlalchemy框架略讲 ,  这一次介绍一下另一个轻量级开发框架web.py

运行环境:

操作系统:Ubuntu 12.04 STL
python版本:2.7.5

1.安装web.py
打开终端,执行命令:

[code]
sudo easy_install web.py
[/code]

2.安装lpthw.web
安装lpthw.web的目的纯粹是为了打印log,便于后台查看,
依旧在终端中,运行命令:

[code]
sudo pip install lpthw.web
[/code]

OK,此时开始写一个简单的程序试一下:
执行如下命令:

[code]
mkdir karlweb
cd karlweb
mkdir bin gothonweb tests docs templates
touch bin/app.py
touch templates/index.html
[/code]

此时,一个web.py的项目创建完毕,接下来开始编辑,
执行如下代码:

[code]
vi bin/app.py
[/code]

然后输入如下代码:

[code lang=”python”]
import web

urls = (
‘/’, ‘Index’,#url地址的映射
‘/book’,’Book’
)

app = web.application(urls, globals())

render = web.template.render(‘templates/’)

class Index(object):#此类与‘/’地址映射
def GET(self):
greeting = "Hello World"
return render.index(greeting = greeting)

class Book(object):#此类与‘/book’地址映射
def GET(self):
return render.book()

if __name__ == "__main__":
app.run()
[/code]

保存并退出,执行如下命令:

[code]
touch templates/index.html
vi templates/index.html
[/code]

输入如下代码:

[code lang=”html”]
$def with (greeting)

<html>
<head>
<title>Web.py test</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>
[/code]

此时,运行如如下代码:

[code]
python bin/app.py
[/code]

然后访问localhost:8080/就会出现如下效果:
I just wanted to say Hello World.
这时,我们再执行如下命令:

[code]
touch templates/book.html
vi templates/book.html
[/code]

输入如下代码:

[code lang=”html”]
<html>
<head>
<title>BOOK</title>
</head>
<body>
<center>BOOK</center>
</body>
</html>
[/code]

然后我们访问localhost:8080/book将会看到浏览器显示BOOK。
从上面的过程可以看出webpy比较不错的集成了mvc设计模式,实现了多层架构,
而且webpy非常轻量级,值得程序开发人员学习一下

One thought on “web.py轻量级开发框架——python的超轻量级服务器

  1. Jerry Wang

    我在前面加了一句话,主要是加上了个链接

    Reply

发表评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据