随笔 - 911  文章 - 5  评论 - 94  阅读 - 243万

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   momingliu11  阅读(135)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2014-12-05 DNS端口说明
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示