一、安装WebPy 从 http:/// 获取WebPy-0.34包,解压后进入包目录执行 python setup.py install。 执行完毕后会在Python安装目录的 X:\Python26\Lib\site-packages\web 下。 二、简单Demo实现,开开眼界。 基本思路就是 模板文件+Python代码实现Web程序。 新建文件夹命名为Test,在内部建立一个目录名为templates用来存放模板文件,接着新增一个main.py文件。 ![]() ![]() import web
urls = ( '/(.*)','Control' ) class Control: def GET(self): return '''<html> <head> <title>WebPy Demo</title> </head> <body> Hello World </body> </html>''' if __name__ == '__main__': app = web.application(urls,globals()) app.run() 执行 python main.py 后可以看到命令行如下: C:\WINDOWS\system32\cmd.exe /c python.exe main.py http://0.0.0.0:8080/
在浏览器中访问 http://127.0.0.1:8080/ 即可看到Hello World
三、再进一步,使用模板文件 在templates目录下新建index.html,把上面代码中的html代码,写入其中。 修改 GET代码如下 def GET(self):
render = web.template.render('templates/') return render.index() 重新执行main.py,访问http://127.0.0.1:8080/ 仍旧可以看到Hello World。 注意 render.index 使用的是html文件名。 具体原理稍后研究。 笔记一中实现了简单的示例,其中具体的代码功能还不清楚。 一、Python代码如何响应URL请求? 示例代码中有一个urls结构
urls = (
'/(.*)', 'Control' ) 第一部分是正则表达式,应该和django处理模式一致。 第二部分是处理请求的类名称,必须是类来处理吗? GET请求处理 处理类中通过 GET方法来处理GET 请求, /之后的内容将作为参数传给GET方法处理。 用代码验证下
def GET(self,name):
print(name) render = web.template.render('templates/') return render.index(name) 访问 http://127.0.0.1:8080/hello 时,后台会输出 ‘hello'说明 '/'后的内容传入GET方法中。
处理类中是否也有POST方法来处理POST请求? 尝试一个表单提交,看看如何处理。这里又会涉及到表单数据如何提交给POST方法呢。 web.auto_application() 类似于 web.application() ,但自动根据元类来构造 urls
下面的Demo中URL自动映射不知为何没有效果。 后来发现元类名小写才可以正常,不知自动构造URL是否对元类名书写有规范。 class hello(app.page):
# -*- coding:utf-8 -*-
import web app = web.auto_application() class Hello(app.page): def GET(self): return '''<html> <head> <title>WebPy Demo</title> </head> <body> Hello World </body> </html>''' if __name__=="__main__": app.run() |
|