Python 请求 Returns 400

Python Requests Returns 400

我有这个命令

curl -X POST --data-urlencode "payload={\"channel\": \"#test\", \"username\": \"kuhkuh\", \"text\": \"This is posted to #test\", \"icon_emoji\": \":ghost:\"}" https://hooks.slack.com/services/123/123/123

我正在尝试使用 python 创建它,以便我可以在我的项目中使用它

import requests
import json

class SlackWrapper:

    def __init__(self):
        pass

    @classmethod
    def post_message_to_slack(self, err):

        url = 'https://hooks.slack.com/services/123/123/123'

        payload = {
            'channel' :  '#test',
            'username' :  'kuhkuh',
            'message' : err,
            'icon_emoji' : ':ghosts:'
        }
        
        try:
            alert = requests.post(url, data=payload, headers={'Content-Type': 'application/json'})
            print(alert.status_code, ' - ', alert.text, ' - ', json.dumps(payload))
        except Exception as e:
            print(e)

SlackWrapper.post_message_to_slack("testing error message requests")

问题是,我一直收到此错误

<Response [400]>

我哪里错了?

您正在尝试将数据作为字典发送到服务器。

而是尝试使用请求 POST json attribute

将其作为 json 数据发送
payload = {
    "channel" =  '#test',
    "username" =  'kuhkuh',
    "message" = err,
    "icon_emoji" = ':ghosts:'
}

alert = requests.post(url, json = payload)


Error 400 表示“Bad Request”,所以您的有效载荷是错误的。

如果您的 payload 已经是 dict,则无需在 post requestjson 参数中 json.dumps。此外,requests 足够聪明,可以推断出 Content-Type,因此无需显式设置此 Header。

@classmethod
    def post_message_to_slack(self, err):

        url = 'https://hooks.slack.com/services/123/123/123'
        
        # changed the payload
        payload = {
            "channel": "#test", 
            "username": "kuhkuh", 
            "text": "This is posted to #test",
            "icon_emoji": ":ghost:"
        }
        
        try:
            # changed the parameters for posting
            alert = requests.post(url, json=payload) 
            print(alert.status_code, ' - ', alert.text, ' - ', json.dumps(payload))
        except Exception as e:
            print(e)

您可以将 curl 代码粘贴到 postman,然后获取 python 代码并使用它。 对于您的代码,等效的 python 代码:

import requests

url = "https://hooks.slack.com/services/123/123/123"

payload = 'payload=%7B%22channel%22%3A%20%22%23test%22%2C%20%22username%22%3A%20%22kuhkuh%22%2C%20%22text%22%3A%20%22This%20is%20posted%20to%20%23test%22%2C%20%22icon_emoji%22%3A%20%22%3Aghost%3A%22%7D'
headers = {
  'Content-Type': 'application/x-www-form-urlencoded'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.text.encode('utf8'))