简体   繁体   English

向 reCAPTCHA Enterprise API 发送请求失败

[英]Sending request to reCAPTCHA Enterprise API fails

I am trying to create ReCaptcha assessment using their REST API in my backend server.我正在尝试在我的后端服务器中使用他们的REST API创建 ReCaptcha 评估。

From reading the documentation, I understand that the request body contains an instance of Assesment , but when I try to send a request, I receive the following error:通过阅读文档,我了解到请求正文包含一个Assesment实例,但是当我尝试发送请求时,我收到以下错误:

TypeError: Object of type Assessment is not JSON serializable类型错误:Object 类型评估不是 JSON 可序列化

My code:我的代码:

import requests
from google.cloud import recaptchaenterprise_v1
from google.cloud.recaptchaenterprise_v1 import Assessment

def create_assessment(project_id: str, recaptcha_site_key: str, token: str, recaptcha_action: str, apiKey:str):

    # Create event object
    event = recaptchaenterprise_v1.Event()
    event.site_key = recaptcha_site_key
    event.token = token

    # Create assesment object
    assessment = recaptchaenterprise_v1.Assessment()
    assessment.event = event
    
    # Set project name
    project_name = "projects/"+project_id

    response = requests.post(url="https://recaptchaenterprise.googleapis.com/v1/"+project_name+"/assessments?key="+apiKey, json=assessment)

    return response

I tried to convert the assesment to JSON using dumps() , but I had no success.我尝试使用 dumps dumps()assesment转换为 JSON,但没有成功。

I've also tried to write it as "skinny JSON" like so:我也试过像这样把它写成“瘦 JSON”:

assessment = {
    'event': {
        'token': token,
        'siteKey': recaptcha_site_key,
        'expectedAction': 'LOGIN'
    }
}

Even though I receive status code 200, it indicates that my request is MALFORMED , probably because I don't include some recaptchaenterprise_v1 objects that should be on the assesment .即使我收到状态代码 200,它也表明我的请求是MALFORMED ,可能是因为我没有包含一些应该在assesment上的recaptchaenterprise_v1对象。

Try to use the CreateAssessmentRequest to create the request instead, like so:尝试使用CreateAssessmentRequest来创建请求,如下所示:

client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()
project_name = "projects/"+project_id

# Build the assessment request.
request = recaptchaenterprise_v1.CreateAssessmentRequest()
request.assessment = assessment
request.parent = project_name

response = client.create_assessment(request)

You can find a more complete code sample in GCP's documentation .您可以在 GCP 的文档中找到更完整的代码示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM