我正在尝试使用webpy实现基于某些elses代码的验证码。我开始的代码在这里:https://kzar.co.uk/blog/2009/07/14/web.py-captcha/
那里的示例代码不完整,我需要弄清楚如何处理这个app变量。这是我的代码:
import web
from captcha import getCaptcha
render = web.template.render('templates/')
urls = (
'/([a-zA-Z]+/[a-zA-Z]+)', 'index',
'/', 'index',
'/captcha.gif', 'captcha'
)
if web.config.get("_session") is None:
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'captcha': ''})
web.config._session = session
else:
session = web.config._session
vcaptcha = form.Validator('Please enter the code', lambda x:x == session.captcha)
enquiry_form = form.Form(
form.Textbox("captcha", vcaptcha, description="Validation Code", pre="<img src='/captcha.gif' valign=center><br>", class_="standard", style="width:70px;"),
)
class index:
def GET(self, argu = "Anonymous/Person"):
args = argu.split('/')
firstname = args[0]
if (len(args) >= 2):
lastname = args[1]
return render.index(firstname, lastname)
return render.index(firstname, "Snow")
class captcha:
def GET(self):
web.header("Content-Type", "image/gif")
captcha = getCaptcha
session.captcha = captcha[0]
return captcha[1].read()
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
运行时出现此错误:
$ python code.py
Traceback (most recent call last):
File "code.py", line 13, in <module>
session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'captcha': ''})
NameError: name 'app' is not defined
我一直在查看webpy文档和API参考,我无法弄清楚如何正确初始化这个'app'变量。
当你打电话给app
时,你正在使用尚未定义的session = web.session.Session(app, ...
你有没有看过关于sessions的文档?在使用它之前,请看它们如何在示例中定义app
。
在URL之后,应该有这个:
app = web.application(urls, globals())