November 12, 2020
If you need a captcha that not only helps prevent bots from spamming your website but also want a captcha that respects privacy, hCaptcha is an awesome service. This tutorial will show step by step how to integrate hCaptcha into your Flask application.
First, we need to setup an hCaptcha account to get our credentials to integrate hCaptcha with our website. Head over to https://hcaptcha.com and make an account and go to its dashboard.
Once we make an account, you should be greeted to a dashboard like this
Click on the “Sites” tab on the top left corner (next to the “Overview” and “Settings” tab). You should see a site.
Click on the “Settings” button where your site is. Now this is where your sitekey will be. Store your sitekey somewhere now as we are going to need it later.
Now that we have retrieved our sitekey, we need to get our Secret Key. Go to the “Settings” tab.
Your secret key should be in the Settings tab. Store it somewhere, as we are going to be needing it.
Flask-xCaptcha
Flask-xCaptcha is a Python library that allows us to seamlessly integrate captchas into our Flask applications.
Its PyPi page is https://pypi.org/project/Flask-xCaptcha/,
Its GitHub at https://github.com/benjilev08/flask-xcaptcha
Installing it is a breeze. In your Terminal, just run
Lets make a basic Flask app with a simple form:
Now that we have a basic app.py and template, lets actually add the hCaptcha integration!
First, lets import the XCaptcha
class from our package we just installed
Next, lets set our app config variables to these parameters
And finally, create an object from our XCaptcha class:
Your app.py file should now look something like this
Now that we have configured our back-end, lets add hCaptcha to our front-end. This is just a matter of adding one extra line.
The {{ xcaptcha }}
line will automatically be converted into an hCaptcha
And that is it! Run your app.py file and see for yourself the rendered hCaptcha!
This is really easy to do, and it involves just a few extra lines.
The verify method returns a boolean (True/False) on whether the user has completed the captcha or not. Implementation is as easy as the following:
The complete app.py code:
Now there are a few ways you can customize the hCaptcha.
If we want to make our captcha dark mode:
This is how a dark mode captcha would look like:
If we want a compact captcha:
And this is how a compact captcha looks like:
Compact captchas are great if you want the captcha to be suitable for smaller screens.
And that is how to implement hCaptchas into your Flask application! As we see, the code is super simple and short and implementing them is a breeze. Not only are you doing yourself a favor, you are also doing people who visit your website a favor, by using a service that respects user privacy, so you and your users can feel safe when browsing your website.