python:post请求业务、调用微信api监控业务

vim post.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import datetime
import requests
import urllib,urllib2
import sys
import simplejson

reload(sys)
sys.setdefaultencoding('utf-8')
#POST请求业务接口
def run(method,url,data):
     #http请求头信息 headers = { 'content-type':'application/json',  #内容类型,用于定义网络文件的类型和网页的编码 'Authorization':'Basic aGVhbHRoY2hlY2tAaW50ZWxsaWNyZWRpdC5jbjpqZXJyeTM5OlBASGVhbHRoY2hlY2s='  #用于客户端在访问受密码保护的网页时识别自己的身份 } if method == 'POST': data_json = json.dumps(data) start_time = datetime.datetime.now() raw = requests.post(url,data_json,headers=headers)  #post请求,发送json格式的数据 end_time = datetime.datetime.now() Rtime=(end_time-start_time).microseconds / 1000  #请求的时间,单位ms status = raw.status_code subject = '%s status:\t%s\n%s 时延:%s' %(url,status,url,Rtime) return subject #获取access_token def gettoken(corpid,corpsecret): gettoken_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' + corpid + '&corpsecret=' + corpsecret  #企业微信获取token的url print gettoken_url try: token_file = urllib2.urlopen(gettoken_url)  #请求token_url except urllib2.HTTPError as e: print e.code print e.read().decode("utf8") sys.exit() token_data = token_file.read().decode('utf-8') token_json = json.loads(token_data)   token_json.keys() token = token_json['access_token']  #获取access_token,这里用来作身份验证,后端代码生成一个token,返回给客户端,客户端储存token return token #给企业微信发消息 def senddata(access_token,subject): send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + access_token send_values = { "touser":"ZhangShun", #企业号中的用户帐号 "toparty":"1", #企业号中的部门id "msgtype":"text", #消息类型 "agentid":"1000002", #企业号中的应用id "text":{ "content":subject  #发送的内容 }, "safe":"0" } # send_data = json.dumps(send_values, ensure_ascii=False) send_data = simplejson.dumps(send_values, ensure_ascii=False).encode('utf-8') send_request = urllib2.Request(send_url, send_data)  #请求企业微信的发送消息接口 response = json.loads(urllib2.urlopen(send_request).read())   print str(response) if __name__ == '__main__':
     #业务api接口 url = 'http://1.1.1.1:8080/api/v1/'
     #POST请求的body data = { "name":"二三三", "pid":"4A99881B1C1AEF6B7220245439FEA196A1F6BDF01C3FD8E1FA750640497419FF", "mobile":"BDA6E1DE2852BA16AE1F88A7D426AD26CECCBB5F570122EAA368CF0A03313D12" } subject = run('POST',url,data) #企业微信 corpid = 'xxxxxxxxxxxxxxx'  #CorpID是企业号的标识 corpsecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  #corpsecretSecret是企业微信应用的密钥 accesstoken = gettoken(corpid,corpsecret) senddata(accesstoken,subject)

  

posted on 2018-12-28 17:14  xiaobai小白  阅读(905)  评论(0编辑  收藏  举报

导航