Python 接口调用

Posted by ZhangShun Blog on December 28, 2018
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
	# !/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):
	        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)
	                end_time = datetime.datetime.now()
	                Rtime=(end_time-start_time).microseconds / 1000
	                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
	    print  gettoken_url
	    try:
	        token_file = urllib2.urlopen(gettoken_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']
	    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",
	        "msgtype":"text",
	        "agentid":"1000002",
	        "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__':
	        url = 'http://1.1.1.1:8080/api/v1/'
	        data = {
	        "name":"二三三",
	        "pid":"4A99881B1C1AEF6B7220245439FEA196A1F6BDF01C3FD8E1FA750640497419FF",
	        "mobile":"BDA6E1DE2852BA16AE1F88A7D426AD26CECCBB5F570122EAA368CF0A03313D12"
	 
	}
	        subject = run('POST',url,data)
	        corpid =  'xxxxxxxxxxxxxxx'  #CorpID是企业号的标识
	        corpsecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  #corpsecretSecret是企业微信应用的密钥
	        accesstoken = gettoken(corpid,corpsecret)
	        senddata(accesstoken,subject)