分类:
2010-12-29 01:32:29
是一个漂亮的 Python web 框架,
当前最新版本是 0.3,增加了 sessions、subdir_application 和 subdomain_application 以及更好的数据库支持。
git clonegit://github.com/webpy/webpy.git
git clone
cd webpy此外,也许您还需要安装 ,
python setup.py build
sudo python setup.py install
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import web
# URL 规则
urls = (
'/(.*)', 'hello'
)
# 应用程序
app = web.application(urls, globals())
class hello:
def GET(self, name):
if not name: name = 'world'
web.header('Content-Type', 'text/html; charset=UTF-8')
return '你好,' + 世界 + '!'
# 启动
if __name__ == "__main__":
app.run()
python code.py现在这个 web.py 应用程序就运行了一个 web 服务器默认监听 8080 端口了,在浏览器中访问,应该就可以看到 “您好,世界!” 了。
python code.py 0.0.0.0:8000或者,只接受 192.168.1.25 来的 8086 端口
python code.py 0.0.0.0:8000
import web
urls = (
"/hello", "hello",
"/magic/.*", "magic"
)
app = web.application(urls, globals())
import web
app = web.auto_application()
class hello(app.page):
def GET(self):
return "hello, world!"
web.py 支持集成多个应用程序,或说将应用划分到多个子应用程序。
比如将 /blog 分出在 blog.py 里边import web在 code.py:
urls = (
"", "reblog",
"/(.*)", "blog",
)
class reblog:
def GET(self): raise web.seeother('/')
class blog:
def GET(self, path):
return "blog " + path
app_blog = web.application(urls, locals())
import web
import blog
urls = (
"/blog", blog.app_blog,
"/(.*)", "index",
)
class index:
def GET(self, path):
return "hello " + path
app = web.application(urls, locals())
可以根据子目录来划分应用程序,
比如将 wiki.py , blog.py , auth.py 分出来
import web
import wiki
import blog
import auth
mapping = (
"/wiki", wiki.app,
"/blog", blog.app,
"/auth", auth.app,
)
app = web.subdir_application(mapping)
也可以根据子域名来划分应用程序,这可以方便做 virtual hosting
比如
(和 example.com)是 mainsite
XXXX.example.com 是 usersite
import web
import mainsite
import usersite
mapping = (
"(www\.)?example.com", mainsite.app,
".*\.example.com", usersite.app,
)
app = web.subdomain_application(mapping)
import web
urls = (
"/hello", "hello",
)
app = web.application(urls, globals())
class hello:
"""Hello world example.
>>> response = app.request("/hello")
>>> response.data
'hello, world!'
>>> response.status
'200 OK'
>>> response.headers['Content-Type']
'text/plain'
"""
def GET(self):
web.header('Content-Type', 'text/plain')
return "hello, world!"
import unittest
from helloworld import app
class HelloWorldTest(unittest.TestCase):
def testHelloWorld(self):
response = app.request('GET', '/')
self.assertEquals(response.data, 'hello, world!')
self.assertEquals(response.headers['Content-Type'],
'text/plain')
self.assertEquals(response.status, '200 OK')
if __name__ == "__main__":
unittest.main()
web.py 0.3 正式提供了基于 cookie 的 session 支持。
import web
urls = (
"/count", "count",
"/reset", "reset"
)
app = web.application(urls, locals())
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'count': 0})
class count:
def GET(self):
session.count += 1
return str(session.count)
class reset:
def GET(self):
session.kill()
return ""
if __name__ == "__main__":
app.run()
上边 Session 的 initializer 参数可以是 dict 或 func,用来初始化 session。
web.py 的 session 存储有基于文件的 DiskStore 和基于数据库的 DBStore ,上边例子是 DiskStore。
也可以使用基于数据库的 DBStore。
使用 DBStore session 前需要在数据库建表create table sessions (然后就可以
session_id char(128) UNIQUE NOT NULL,
atime datetime NOT NULL default current_timestamp,
data text
);
db = web.database(dbn='postgres', db='mydatabase', user='myname', pw='')
store = web.session.DBStore(db, 'sessions')
session = web.session.Session(app, store, initializer={'count': 0})
可以用 web.setcookie() 、web.cookies() 来设置和读取 cookies
参数:web.setcookie(name, value, expires="", domain=None, secure=False)
class CookieSet:
def GET(self):
i = web.input(age='25')
web.setcookie('age', i.age, 3600)
return "Age set in your cookie"
web.cookies().get(cookieName)2. 有预设值,避免异常
#cookieName is the name of the cookie submitted by the browser
foo = web.cookies(cookieName=defaultValue)例子:
foo.cookieName # return the value (which could be default)
#cookieName is the name of the cookie submitted by the browser
通过 web.cookies() 来访问
如果先前 web.setcookie() 设置了 age , 那可以这样读取
class CookieGet:上边的当没有 cookie 时会异常,如果要考虑没有 cookie 的情况,可以类似下边这样:
def GET(self):
c = web.cookies(age="25")
return "Your age is: " + c.age
class CookieGet:
def GET(self):
try:
return "Your age is: " + web.cookies().get('age')
except:
# Do whatever handling you need to, etc. here.
return "Cookie does not exist."