Python3 Post Get API

 

import sys,urllib.request,urllib.parse,json,string

class GetDeviceDataAPI():

    def __init__(self,name,password):
        #定义主url、获取token的url,获取设备信息的url
        self.url = 'https://control.abc.com/apis/'
        self.url_token = 'my/token'
        self.url_devicelist = 'dds/list'
        self.url_temp = 'dd/dd-temperature'
        self.name = name
        self.password = password
        #定义登陆认证的用户名和密码
        self.data = {'name' : self.name,
                     'password' : self.password
                     }
        self.devicedata = {'pageSize':1000,
                            'pageIndex':0
                            } 
        self.headers = {'Content-Type':'application/json','User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
        self.token = self.get_token()
        #将获取到的Token绑定到Headers中
        self.headers['Authorization'] = self.token

    #获取token
    def get_token(self):
        postdata = bytes(json.dumps(self.data),'utf8') #post json格式数据
        content = self.post_request(self.url_token,postdata)
        # print(content)
        try:
            token = content['access_token']
            return token
        except Exception as ErrorMsg:
            print(ErrorMsg)

    #发送POST请求
    def post_request(self,prefix='/',postdata=None):
        try:
            request = urllib.request.Request(self.url + prefix,postdata,headers=self.headers)
            # print(request.full_url)
            reponse = urllib.request.urlopen(request).read()
            content  = json.loads(reponse.decode('utf8'))
            return content
        except Exception as ErrorMsg:
            print(ErrorMsg)
            exit()

    
    #发送GET请求
    def get_request(self,url_getdata):
        try:
            url_getdata =urllib.parse.quote(url_getdata,safe=string.printable) #防止在有中文的时候解析错误
            request = urllib.request.Request(url_getdata,headers=self.headers)
            reponse = urllib.request.urlopen(request).read()
            content  = json.loads(reponse.decode('utf8'))
            return content
        except Exception as ErrorMsg:
            print(ErrorMsg)

    #打印Headers内容
    def PrintHeaders(self):
        print(self.headers)

    #获取设备列表
    def get_devicelist(self):
        temp_data = bytes(json.dumps(self.devicedata),'utf8')
        try:
            content = self.post_request(self.url_devicelist,temp_data)
            return content['items'][0]
        except Exception as ErrorMsg:
            print(ErrorMsg)

    # #获取温度、湿度
    # def get_temp(self,deviceID):
    #     device_param_json = {'deviceId': deviceID,
    #                 'pageIndex':10,
    #                 'pageSize':1
    #                 }   
    #     #对json格式参数编码
    #     device_param = urllib.parse.urlencode(device_param_json)
    #     url_device_temp = self.url + self.url_temp + '?' + device_param 
    #     url_device_temp =urllib.parse.quote(url_device_temp,safe=string.printable) #防止在有中文的时候解析错误
    #     request = urllib.request.Request(url_device_temp,headers=self.headers)
    #     reponse = urllib.request.urlopen(request).read()
    #     content  = json.loads(reponse.decode('utf8'))
    #     try:
    #         return content
    #     except Exception as ErrorMsg:
    #         print(ErrorMsg)

    #获取温度、湿度
    def get_temp(self,deviceID):
        device_param_json = {'deviceId': deviceID,
                    'pageIndex':10,
                    'pageSize':1
                    }   
        #对json格式参数编码,然后转换为key=value&key=value格式 string
        device_param = urllib.parse.urlencode(device_param_json)
        url_device_temp = self.url + self.url_temp + '?' + device_param 
        content = self.get_request(url_device_temp)
        try:
            temphum = content['items']
            return temphum[0]['temperature']except Exception as ErrorMsg:
            print(ErrorMsg)


name = 'myname'
password = 'mypassword'
deviceID = 'XK21Tabc'
GetDeviceData = GetDeviceDataAPI(name,password)

# #Print Token
# print(GetDeviceData.get_token())
# #Print Headers
# print(GetDeviceData.PrintHeaders())

print(GetDeviceData.get_devicelist())

print(GetDeviceData.get_temp(deviceID)

在post、get出错时,可以参考 https://www.cnblogs.com/dreamer-fish/p/12971711.html ,不同api接口对post的参数类型不同,有的是json格式,有个是str格式

 

posted on 2021-12-05 00:35  momingliu11  阅读(132)  评论(0编辑  收藏  举报