我知道有很多文字,但我不相信这实际上是一个难以解决的问题。对于TLDR,请查看问题的结尾。
所以,我正在尝试在我的web.py应用程序中实现一个类似于验证码的基本表单。此代码取自http://kzar.co.uk/blog/2009/07/14/web.py-captcha。我只是展示了一个我正在研究的基本测试示例,试图弄清楚我的大应用程序出了什么问题。
当我在索引页面上按Enter键时,即使我得到正确的代码(我通过将captcha.py中的'word'变量打印到终端来验证),我仍然会收到错误说我的验证码是无效的。我已经尝试了所有的东西,并检查了会话变量以及单词变量,但无论我被告知我的代码是错误的。这是整个测试应用程序。
test.py:
import web
from web import form
from captcha import getCaptcha
render = web.template.render('templates/')
urls = (
'/', 'index',
'/captcha.gif', 'captcha'
)
app = web.application(urls, locals())
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:
# Display the create match page
def GET(self):
form = enquiry_form()
return render.captcha(form)
# Save the data
def POST(self):
form = enquiry_form()
if not form.validates(): # If there is an issue
return render.captcha(form) # Return them to the create page
else:
return "Success!"
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()
captcha.py:
from PIL import Image, ImageDraw, ImageFont
import cStringIO, random
def getCaptcha():
im = Image.new("RGB", (175, 60))
draw = ImageDraw.Draw(im)
for x in range(0, 175):
for y in range(0, 60):
draw.point((x, y), (135, 191, 107))
font = ImageFont.truetype('static/ZXX Camo.otf', 50)
alphabet = 'abcdefghijklmnopqrstuvwxyz'
word = ''
for i in range(5):
word = word + alphabet[random.randint(0, len(alphabet) -1)]
draw.text((5, 5), word, font=font, fill=(0, 0, 0))
f = cStringIO.StringIO()
im.save(f, "GIF")
f.seek(0)
return word, f
captcha.html:
$def with (form)
<head>
<link rel="shortcut icon" href="/static/favicon.ico" type="image/x-icon">
</head>
<h1>Testing Captcha</h1>
<form name="main" method="post">
$:form.render()
</form>
我使用的字体可在此处找到:http://dl.dropbox.com/u/20517415/ZXX.zip
我对这里发生的事情感到十分困惑。我相信这里的错误代码是验证码lambda x:x == session.captcha
。我已尝试过这一行的许多不同版本,似乎没有任何工作。最令人困惑的是,我甚至可以将行更改为lambda x:x != session.captcha
,并且 STILL 不起作用。我很感激你的帮助。我一直在看这个问题,不知道出了什么问题。
TLDR;我在web.py应用程序上使用的一些类似CAPTCHA的基本代码无法识别正确的代码条目,并且我提供了源文件供您检查错误。
答案 0 :(得分:0)
对于那些通过谷歌找到这个的人:
解决方案很简单。我正在重新初始化app实例,这意味着我每次都在创建一个新会话,没有session.captcha var。并且因为web.py处理验证的方式,它没有发出错误来解释存在AttributeError。所以,我所要做的就是删除__main__中的app声明。
此外,如果没有禁用调试模式,此代码将无法工作,因为web.py会话变量很奇怪= /