webpy demo核心代码

# -*-encoding:utf-8 -*-

"""Basic Blog using webpy 0.3 """

import web
import config
import controllers



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

if __name__ =='__main__':
app.run()



class Index:

def GET(self):
web.header(
'Content-Type','text/html;charset=UTF-8')
web.setcookie(
"age",30)

posts
=model.get_posts()
return render.index(posts,web.cookies())

class View:

def GET(self,id):
""" View sing post """
post
= model.get_post(int(id))
print datetime.datetime.strptime('2009-9-9 16:56:58','%Y-%m-%d %H:%M:%S')
print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return render.view(post)

class New:
#vtitle = web.form.regex(r".{3,20}$", '标题长度3到20位字符')
form=web.form.Form(
web.form.Textbox(
'title',web.form.notnull,
size
=30,
description
=u"标题"),
web.form.Textarea(
'content',web.form.notnull,
rows
=30,cols=80,
description
=u"内容"),
web.form.Button(
'submit',type="submit",html=u'提交'),


)


def GET(self):
form
= self.form()

return render.new(form)

def POST(self):
form
= self.form()
if not form.validates():
return render.new(form)
model.new_post(form.d.title,form.d.content)
raise web.seeother('/')

class Delete:
def POST(self,id):
model.del_post(int(id))
raise web.seeother('/')

class Edit:

def GET(self,id):
post
= model.get_post(int(id))
form
= New.form()
form.fill(post)
return render.edit(post,form)

def POST(self,id):
form
=New.form()
post
= model.get_post(int(id))
if not form.validates():
return render.edit(post,form)
model.update_post(int(id),form.d.title,form.d.content)
raise web.seeother('/')

def notfound():
return web.notfound("Sorry, the page you were looking for was not found.")








model.py

import web,datetime
db
= web.database(dbn='sqlite',db='blog.db')

def get_posts():
return db.select('entries',order='id desc')

def get_post(id):
try:
return db.select('entries',where='id=$id',vars=locals())[0]
except IndexError:
return None

def new_post(title,text):

db.insert(
'entries',title=title,content=text,post_on=datetime.datetime.utcnow())

def del_post(id):
db.delete(
'entries',where="id=$id",vars=locals())

def update_post(id,title,text):
db.update(
'entries',where="id=$id",vars=locals(),
title
=title,content=text)
posted @ 2011-07-01 13:09  永不言败  阅读(618)  评论(0编辑  收藏  举报