我有这个命令
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]>
我在哪里弄错了?
答案 0 :(得分:0)
错误400表示“请求错误”,因此您的有效负载是错误的。
如果您的othermodule.number
已经是payload
,则无需在dict
的{{1}}参数中json.dumps
。另外,json
足够聪明,可以推断post request
,因此无需显式设置此标头。
requests
答案 1 :(得分:0)
您可以将curl代码粘贴到邮递员,然后获取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'))
答案 2 :(得分:-1)
您正在尝试将数据作为字典发送到服务器。
请尝试使用请求POST json attribute
将其作为json数据发送payload = {
"channel" = '#test',
"username" = 'kuhkuh',
"message" = err,
"icon_emoji" = ':ghosts:'
}
alert = requests.post(url, json = payload)