http://captchas.net http://captchas.net

Sample Python Implementation

Python Module

Have you read our HowTo?

We are providing a python module to simplify the task of writing a web application using captchas.net. It is named CaptchasDotNet.py. To use it, simply copy it to somewhere in your python path or simply into the directory with the CGI-scripts using it.

Stages

Quering

In general the process of using CAPTCHA can be divided into two stages. First you have to query the user for the CAPTCHA, on that page you also usually let the user input the data, which has to be protected, e.g. blog entries.

The following script query.cgi implements this querying phase.

#!/usr/bin/env python

#---------------------------------------------------------------------
# Import the necessary module.
#---------------------------------------------------------------------
import CaptchasDotNet

#---------------------------------------------------------------------
# Construct the captchas object. Replace the required parameters
# 'demo' and 'secret' with the values you receive upon 
# registration at http://captchas.net.
#
# Optional Parameters and Defaults:
#
# alphabet: 'abcdefghkmnopqrstuvwxyz' (Used characters in captcha)
# We recommend alphabet without mistakable ijl.
#
# letters: '6' (Number of characters in captcha)
#
# width: '240' (image width)
# height: '80' (image height)
#
# Don't forget the same settings in check.cgi
#---------------------------------------------------------------------
captchas = CaptchasDotNet.CaptchasDotNet (
                                client   = 'demo'
                                secret   = 'secret'#,
                                #alphabet = 'abcdefghkmnopqrstuvwxyz',
                                #letters  = 6,
                                #width    = 240,
                                #height   = 80
                                )

#---------------------------------------------------------------------
# Print html page
#---------------------------------------------------------------------
print 'Content-Type: text/html'
print
print '''
<html>
  <head><title>Sample Python CAPTCHA Query</title></head>
  <h1>Sample Python CAPTCHA Query</h1>
  <form method="get" action="check.cgi">
    <table>
      <tr>
        <td>
          <input type="hidden" name="random" value="%s" />
          Your message:</td><td><input name="message" size="60" />
        </td>
      </tr>
      <tr>
        <td>
          The CAPTCHA password:
        </td>
        <td>
          <input name="password" size="16" />
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
           %s <br>
           <a href="%s">Phonetic spelling (mp3)</a>
        </td>
      </tr>
      <tr>
        <td>
        </td>
        <td>
          <input type="submit" value="Submit" />
        </td>
      </tr>
    </table>
  </form>
</html>
'''
 % (captchas.random (), captchas.image (), captchas.audio_url ())
#---------------------------------------------------------------------
# End
#---------------------------------------------------------------------

Checking

The second part is to check, whether the user has input the correct letter sequence (as given by the CAPTCHA image or audio). If that is the case the protected operation can be performed. Otherwise the corresponding error message is to be output.

There are two ways, in which a CAPTCHA check can fail. The user can have simply input the wrong letters. But also the random string can have been used more than once. If you would allow a random string to be used multiple times, a human could find out the correct CAPTCHA letter sequence for one random string once and use that information to make a robot post non-human entries to your web application, which still would seem made by a human.

The following script check.cgi implements this checking phase.

#!/usr/bin/env python

#---------------------------------------------------------------------
# Import the necessary modules
#---------------------------------------------------------------------
import CaptchasDotNet
import cgi

#---------------------------------------------------------------------
# Construct the captchas object. Use same Settings as in query.cgi, 
# height and width aren't necessairy
#---------------------------------------------------------------------
captchas = CaptchasDotNet.CaptchasDotNet (
                                client   = 'demo'
                                secret   = 'secret'#,
                                #alphabet = 'abcdefghkmnopqrstuvwxyz',
                                #letters  = 6
                                )

#---------------------------------------------------------------------
# Validate and verify captcha password
#---------------------------------------------------------------------
def get_body ():
    # Read the form values and keep empty fields.
    form = cgi.FieldStorage(keep_blank_values = True)
    try:
        message = form['message'].value
        password = form['password'].value
        random_string = form['random'].value
    except KeyError:
        # Return an error message, when reading the form values fails.
        return 'Invalid arguments.'

    # Check the random string to be valid and return an error message
    # otherwise.
    if not captchas.validate (random_string):
        return ('Every CAPTCHA can only be used once. The current '
                + 'CAPTCHA has already been used. Try again.')

    # Check, that the right CAPTCHA password has been entered and
    # return an error message otherwise.
    if not captchas.verify (password):
        return ('You entered the wrong password. '
                + 'Please use back button and try again.')

    # Return a success message.
    return ('Your message was verified to be entered by a human '
            + 'and is "%s"' % message)

#---------------------------------------------------------------------
# Print html page
#---------------------------------------------------------------------
print 'Content-Type: text/html'
print
print '''
<html>
  <head>
    <title>Sample Python CAPTCHA Check</title>
  </head>
  <h1>Sample Python CAPTCHA Check</h1>
    %s
</html>
'''
 % get_body ()
#---------------------------------------------------------------------
# End
#---------------------------------------------------------------------

Try it

You can also try the above scripts out yourself.

XHTML 1.1 compliant A service of Felix Holderied and Sebastian Wilhelmi (Contact) mail@captchas.net