"""Relatively secure server implementation, but still
uses a weak and trivial CAPTCHA."""

import web
from Captcha.Visual import Tests
from Captcha import Factory

urls = ('/', 'index', '/(.*).jpg', 'image')

cf = Factory()

class index:
    def GET(self):
        test = cf.new(Tests.PseudoGimpy)
        print """<html><body>
<p><img src="%s.jpg"/></p>
<p><form action="/" method="post">
    Enter the word shown:
    <input type="hidden" name="id" value="%s" />
    <input type="text" name="word" />
</form></p>
</body></html>
""" % (test.id, test.id)
    
    def POST(self):
        i = web.input('id', 'word')
        test = cf.get(i.id)
        if test.valid and test.testSolutions([i.word]):
            print "Passed"
        else:
            print "Fail!"

class image:
    def GET(self, id):
        print cf.get(id).render().tostring("jpeg", 'RGB')

if __name__ == '__main__': web.run(urls, globals(), web.reloader)