Python教程

Python3 Post Get API

本文主要是介绍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格式

 

这篇关于Python3 Post Get API的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!