#!/usr/bin/python
#coding=utf-8
import urllib.request
import json
import sys
import socket
import ssl
# 获取钉钉消息
def extractionMessage() :
#拼接需要发送的消息
return "##### <font color=orange> message </font>"
#发送钉钉消息
def sendDingDingMessage(url, data):
req = urllib.request.Request(url)
req.add_header("Content-Type", "application/json; charset=utf-8")
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
response = opener.open(req, json.dumps(data))
return response.read()
#主函数
def main():
posturl = "https://oapi.dingtalk.com/robot/send?access_token="
data = {"msgtype": "markdown", "markdown": {"text": extractionMessage(),"title":"Jenkins","isAtAll": "false"}}
sendDingDingMessage(posturl, data)
if __name__=="__main__":
main()
报错信息如下
File "ding.py", line 29, in <module>
File "ding.py", line 26, in main
File "ding.py", line 19, in sendDingDingMessage
File "/usr/local/lib/python3.6/urllib/request.py", line 524, in open
req = meth(req)
File "/usr/local/lib/python3.6/urllib/request.py", line 1248, in do_request_
raise TypeError(msg)
TypeError: POST data should be bytes, an iterable of bytes, or a file object. It
cannot be of type str.
python 版本是3.6.4
1 个解决方案
#1
response = opener.open(req, json.dumps(data))
改成
response = opener.open(req, json.dumps(data).encode('utf-8'))
改成
response = opener.open(req, json.dumps(data).encode('utf-8'))
#1
response = opener.open(req, json.dumps(data))
改成
response = opener.open(req, json.dumps(data).encode('utf-8'))
改成
response = opener.open(req, json.dumps(data).encode('utf-8'))