Google’s reCAPTCHA is a very popular solution to protect your application or website against bots and spam. It is
fairly simple to implement. In this tutorial you will find a working example using only built-in libraries, an
alternative using requests and also an implementation using decorators, to reuse the reCAPTCHA verification across
your application.
Setup
First thing, register your application in the reCAPTCHA admin.
I added the 127.0.0.1 IP address as my domain for testing purpose. Here you are supposed to add your website domain.
After registering your website, you will be handed a Site key and a Secret key. The Site key will be used
in the reCAPTCHA widget which is rendered within the page where you want to place it. The Secret key will be stored
safely in the server, made available through the settings.py module.
settings.py
PS: It is not a good idea to keep this kind of information directly in the settings.py. I’m adding it here so the
example is more explicit. Please refer to this article Package of the Week: Python Decouple
to learn how to separate configuration from settings, and keep sensitive information in a safe place.
Implementing the reCAPTCHA
Let’s say we want to add a reCAPTCHA in a comment section of a website. Inside the form you are currently using to post
the data, add the code provided by reCAPTCHA Admin page:
Make sure you change the data-sitekey with the correct key for your website. You may also place the script tag in the
<head> of your template, or in the bottom of the page (depending on how you are organizing the assets).
Just by adding the tags, the reCAPTCHA widget will already show up.
Validating the reCAPTCHA
Next step is to actually validate the data. It is done by making a POST request to the endpoint
https://www.google.com/recaptcha/api/siteverify, containing your Secret key and the data from the reCAPTCHA
widget, which is identified by g-recaptcha-response.
Python 2 Solution without Third Party Libraries
You can validate it directly in the view function, using just built-in libs:
views.py
Basically result['success'] will return True or False, defining if the reCAPTCHA is valid or not.
Python 3 Solution without Third Party Libraries
views.py
Alternative Solution With a Third Party Library
If you don’t mind adding an extra dependency, install the requests library:
Then you can make the POST in a relatively easier way:
views.py
reCAPTCHA Decorator
This is an extra for this post. This is just an idea of what you can do, to reuse the reCAPTCHA verification code
across the project.
decorators.py
Then you can use it like this:
views.py
That’s about it! Hope you can find it useful somehow. Google’s reCAPTCHA is a very common solution to avoid spam, bots,
and can also be used to mitigate brute force attacks on login pages for example.
As usual, all the source code is available on GitHub so you can try it by yourself. Make sure you register your own
application to get valid Site key and Secret key.