我正在尝试使用webpy根据其他人的代码实现验证码。我开始使用的代码在这里:https://kzar.co.uk/blog/2009/07/14/web.py-captcha/
示例代码还不完整,我需要弄清楚该应用变量的作用。这是我的代码:
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”变量。
答案 0 :(得分:1)
您在致电app
时使用的是尚未定义的session = web.session.Session(app, ...
您是否看到过sessions上的文档?在使用示例之前,请先查看他们如何定义app
。
答案 1 :(得分:1)
仅在URL之后应该有一个:
app = web.application(urls, globals())