利用flask实现的微信报警restful api接口

微信团体号可以实现报警信息 微信通知,或者用邮件实现报警,但是这些在调用的时候比较麻烦,需要写点代码,为了解决这个问题,我用flask封装了微信的报警功能,用api的形式去提供服务,运维组的都可以调用,而不需要自己申请corpid。当然一个公司肯定会申请一个id,如果没有自己申请一个,下面的代码corpid我已经处理了,不能用。

#!/usr/bin/env python
# coding=utf-8
from flask import Flask
import urllib2
import json
from flask import request
import datetime
now = datetime.datetime.now()
nowStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
get_token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=efc44e79734&corpsecret=ALXK-IiA6Jidt84F-ll4x5goaa7U3iOOmCBOlKT80oAVKkWrltHDE9kH'
res = urllib2.urlopen(get_token_url).read()
token = eval(res)['access_token']
sendurl = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' % (token)
app = Flask(__name__)
@app.route('/api/send', methods=['GET'])
def index():
 """
 使用说明
 curl -X GET "http://127.0.0.1:5000/api/send?username=test&content=123456"
 username 需要去关注自己的团体号,在后台定义一个名字
 countent 就是你需要发送的事件内容
 """
 username_list = ['test', 'test002']
 username = request.args.get('username')
 if username not in username_list:
 return "username is not correct", 804
 content = request.args.get('content')
 json_txt = {
 "touser": username, # 可以是 user1 | user2 | user3; @all是全体成员
 "toparty": " PartyID1 | PartyID2 ",
 "totag": " TagID1 | TagID2 ",
 "msgtype": "text",
 "agentid": 1,
 "text": {
 "content": '[' + str(nowStyleTime) + ']' + '\r' + content
 },
 "safe": "0" # 0是默认,不保密 1是保密
 }
 json_txt = json.dumps(json_txt, ensure_ascii=False, encoding='utf-8')
 req = urllib2.Request(sendurl, json_txt)
 res = urllib2.urlopen(req)
 return res.read()
if __name__ == '__main__':
 app.run(host='0.0.0.0', debug=True)

转载地址:
https://blog.51cto.com/ribble/1834057


分享到:


相關文章: