我嘗試將登錄功能添加到web.py
todo example。登錄Web.py待辦事項列表
這是我的代碼:
""" Basic todo list using webpy 0.3 """
import web
import model
### Url mappings
urls = (
'/', 'Index',
'/login', 'Login',
'/logout', 'Logout',
'/del/(\d+)', 'Delete',
)
### Templates
render = web.template.render('templates', base='base')
app = web.application(urls, locals())
session = web.session.Session(app, web.session.DiskStore('sessions'))
allowed = (
('user','pass'),
('tom','pass2')
)
class Login:
login_form = web.form.Form(web.form.Textbox('username'),
web.form.Password('password'),
web.form.Button('Login'),
)
def GET(self):
f = self.login_form()
return render.login(f)
def POST(self):
# Validation
if not self.login_form.validates():
print "it didn't validate!"
session.logged_in = True
raise web.seeother('/')
class Logout:
def GET(self):
session.logged_in = False
raise web.seeother('/')
class Index:
form = web.form.Form(
web.form.Textbox('title', web.form.notnull,
description="I need to:"),
web.form.Button('Add todo'),
)
def GET(self):
print "logged_in " + str(session.get('logged_in', False))
if session.get('logged_in', False):
""" Show page """
todos = model.get_todos()
form = self.form()
return render.index(todos, form)
else:
raise web.seeother('/login')
def POST(self):
""" Add new entry """
form = self.form()
if not form.validates():
todos = model.get_todos()
return render.index(todos, form)
model.new_todo(form.d.title)
raise web.seeother('/')
class Delete:
def POST(self, id):
""" Delete based on ID """
id = int(id)
model.del_todo(id)
raise web.seeother('/')
app = web.application(urls, globals())
if __name__ == '__main__':
app.run()
當用戶執行POST
在/login
,logged_in
總是False
。
任何想法爲什麼?
Login類似乎只顯示錶單。當他們提交用戶名/密碼時會發生什麼。我沒有看到實際登錄用戶的代碼。 – Sid 2012-02-03 19:49:32
@Sid:那裏沒什麼特別的。你可以寫任何你想要的東西,當你執行'POST'時,它總是登錄,但'logged_in' var永遠不會變爲'True'。 – Macarse 2012-02-03 20:00:58
那麼爲什麼這段代碼在登錄和註銷時將logged_in明確設置爲True和False http://webpy.org/docs/0.3/sessions – Sid 2012-02-03 20:06:52