Python post request, problem with posting

[亡魂溺海] 提交于 2021-01-29 03:59:31

问题


I'm trying to write a typeform bot but I am a totally beginner so I have problems with request.post

I am trying to fill this typeform: https://typeformtutorial.typeform.com/to/aA7Vx9 by this code

import requests

token = requests.get("https://typeformtutorial.typeform.com/app/form/result/token/aA7Vx9/default")

data = {"42758279": "true",
        "42758410": "text",
        "token": token}

r = requests.post("https://typeformtutorial.typeform.com/app/form/submit/aA7Vx9", data)

print(r)

I think that something is wrong with "data" and I am not sure if I use token in a good way. Could you help me?


回答1:


So, first of all, you need to get another field with the token. To do that, you should pass the header 'accept': 'application/json' in your first request. In the response, you'll get the json object with the token and landed_at parameters. You should use them in the next step.

Then, the post data shoud be different from what you're passing. See the network tab in the browser's developer tools to find out the actual template. It has a structure like that:

{
    "signature": <YOUR_SIGNATURE>,
    "form_id": "aA7Vx9",
    "landed_at": <YOUR_LANDED_AT_TIME>,
    "answers": [
        {
            "field": {
                "id": "42758279",
                "type": "yes_no"
            },
            "type": "boolean",
            "boolean": True
        },
        {
            "field": {
                "id": "42758410",
                "type": "short_text"
            },
            "type": "text",
            "text": "1"
        }
    ]
}

And finally, you should convert that json to text so the server would successfully parse it.

Working example:

import requests
import json

token = json.loads(requests.post(
    "https://typeformtutorial.typeform.com/app/form/result/token/aA7Vx9/default",
    headers={'accept': 'application/json'}
).text)
signature = token['token']
landed_at = int(token['landed_at'])

data = {
    "signature": signature,
    "form_id": "aA7Vx9",
    "landed_at": landed_at,
    "answers": [
        {
            "field": {
                "id": "42758279",
                "type": "yes_no"
            },
            "type": "boolean",
            "boolean": True
        },
        {
            "field": {
                "id": "42758410",
                "type": "short_text"
            },
            "type": "text",
            "text": "1"
        }
    ]
}

json_data = json.dumps(data)

r = requests.post("https://typeformtutorial.typeform.com/app/form/submit/aA7Vx9", data=json_data)

print(r.text)

Output:

{"message":"success"}


来源:https://stackoverflow.com/questions/58599595/python-post-request-problem-with-posting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!