Verify reCAPTCHA in DRF
Suppose we have some Django REST framework view with POST method which receives g_recaptcha_response key in post data, we can use request module to easily verify reCAPTCHA:
def post(self, request):
g_recaptcha_response = request.data['g_recaptcha_response']
r = requests.post(settings.GR_CAPTCHA_URL, {
'secret': settings.GR_CAPTCHA_SECRET_KEY,
'response': g_recaptcha_response
})
if not json.loads(r.content.decode())['success']:
return response.Response(status=HTTP_400_BAD_REQUEST)
# Captcha is ok do what you need and return good response
In settings.py define next constants:
GR_CAPTCHA_URL = "https://www.google.com/recaptcha/api/siteverify" GR_CAPTCHA_SITE_KEY = "COPY FROM reCAPTCHA SITE" GR_CAPTCHA_SECRET_KEY = "COPY FROM reCAPTCHA SITE"
Vue.js example how to generate g_recaptcha_response is here: https://hinty.io/ivictbor/recaptcha-with-vue-js-example/