• 17、监测数据采集物联网应用开发步骤(12.2)


    阶段性源码将于本章节末尾给出下载

    1. 监测数据采集物联网应用开发步骤(12.1)

    新建web数据接口http-request解析类com.zxy.tcp.Request.py

    1. #! python3
    2. # -*- coding: utf-8 -
    3. '''
    4. Created on 2017年05月10日
    5. @author: zxyong 13738196011
    6. '''
    7. import urllib.parse,json
    8. from com.zxy.common import Com_Para
    9. from com.zxy.common.Com_Fun import Com_Fun
    10. from com.zxy.model.Return_Value import Return_Value
    11. from com.zxy.z_debug import z_debug
    12. #监测数据采集物联网应用--web数据接口http-request解析
    13. class Request(z_debug):
    14. attStrIP = ""
    15. attServSocket = None
    16. attUri = ""
    17. attPost_str = []
    18. attRv = Return_Value()
    19. attUploadFile = ""
    20. attConnection = ""
    21. def __init__(self):
    22. pass
    23. def parseUri(self,inputValue):
    24. temStrResult = ""
    25. if inputValue.find("/favicon.ico") != -1:
    26. temStrResult += "favicon.ico"
    27. return temStrResult
    28. elif inputValue.find(Com_Para.Inf_Name) != -1:
    29. for temStrITem in inputValue.split("\r\n"):
    30. if temStrITem.find(Com_Para.Inf_Name) != -1:
    31. if (temStrITem.split(" ")[1]).find("?") != -1:
    32. temStrResult += urllib.parse.unquote(temStrITem.split(" ")[1].split("?")[1])
    33. else:
    34. temStrResult += urllib.parse.unquote(temStrITem.split(" ")[1])
    35. break
    36. elif self.FindWebName(inputValue):
    37. for temStrITem in inputValue.split("\r\n"):
    38. if self.FindWebName(temStrITem):
    39. temStrT = temStrITem.split(" ")[1]
    40. if temStrT.find("?") == -1:
    41. temStrResult = urllib.parse.unquote(temStrITem.split(" ")[1],Com_Para.U_CODE)
    42. else:
    43. temStrResult = urllib.parse.unquote(temStrT[0:temStrT.find("?")],Com_Para.U_CODE)
    44. break
    45. elif len(inputValue) > 10:
    46. temStrResult = inputValue
    47. return temStrResult
    48. def FindWebName(self,inputValue):
    49. for temAttF in Com_Para.web_Name:
    50. if inputValue.find(temAttF) != -1:
    51. return True
    52. return False
    53. def PostData(self,inputValue):
    54. temStrResult = ["",""]
    55. if self.FindWebName(inputValue):
    56. temStrTem = inputValue.split("\r\n")
    57. if len(temStrTem[0].split(" ")) > 1 and (temStrTem[0].split(" ")[0] == "POST" or temStrTem[0].split(" ")[0] == "OPTIONS") :
    58. temContent_Length = -1
    59. temStrEnd = inputValue[len(inputValue) - 4:len(inputValue)]
    60. if temStrEnd != "\r\n\r\n":
    61. temStrResult[1] = temStrTem[len(temStrTem) - 1]
    62. for temStrItem in temStrTem:
    63. temStrItem = urllib.parse.unquote(temStrItem,Com_Para.U_CODE)
    64. if temStrItem.find("post_param: ") == 0:
    65. temStrResult[1] = temStrItem[temStrItem.find("post_param: ") + 12:len(temStrItem)]
    66. temStrResult[0] = "Content-Length:"
    67. temStrResult[0] += str(len(temStrResult[1]))
    68. break
    69. if temStrItem.find("Content-Length:") == 0:
    70. temContent_Length = int(temStrItem.split(":")[1].strip())
    71. temStrResult[0] = "Content-Length:"
    72. temStrResult[0] += str(temContent_Length)
    73. if temContent_Length > 0 and temContent_Length == len(temStrResult[1].encode(Com_Para.U_CODE)):
    74. break
    75. return temStrResult
    76. def GetHttpHeadByte(self,inputValue):
    77. temResult = {}
    78. for temStrItem in inputValue.split(b"\r\n"):
    79. if temStrItem.find(b"POST") == 0 or temStrItem.find(b"GET") == 0:
    80. strKey = temStrItem.split(b" ")[0]
    81. strValue = temStrItem.split(b" ")[1]
    82. else:
    83. strKey = temStrItem[0:temStrItem.find(b":")]
    84. strValue = temStrItem[len(strKey)+1:len(temStrItem)]
    85. if Com_Fun.GetHashTableNone(temResult, strKey) == None:
    86. Com_Fun.SetHashTable(temResult, strKey, strValue)
    87. return temResult
    88. def GetHttpHead(self,inputValue):
    89. temResult = {}
    90. for temStrITem in inputValue.split("\r\n"):
    91. if temStrITem.find("POST") == 0 or temStrITem.find("GET") == 0:
    92. strKey = temStrITem.split(" ")[0]
    93. strValue = temStrITem.split(" ")[1]
    94. else:
    95. strKey = temStrITem[0:temStrITem.find(":")]
    96. strValue = temStrITem[len(strKey)+1:len(temStrITem)]
    97. if Com_Fun.GetHashTableNone(temResult, strKey) == None:
    98. Com_Fun.SetHashTable(temResult, strKey, strValue)
    99. return temResult
    100. def GetHttpHeadArray(self,inputValue):
    101. inputValue = inputValue[inputValue.find(b"\r\n\r\n")+4:len(inputValue)]
    102. temResult = []
    103. for temStrITem in inputValue.split(b"\n"):
    104. temResult.append(temStrITem)
    105. return temResult
    106. #从套接字中读取字符信息
    107. def parse(self):
    108. temInit_msg = b'' # 初始化流
    109. temFile = None
    110. temValue = ""
    111. try:
    112. temInit_msg = self.attServSocket.recv(20480) #接受数据 20480
    113. temStrCheck = []
    114. #特殊符号处理
    115. try:
    116. temValue = temInit_msg.decode(Com_Para.U_CODE)
    117. self.attUri = self.parseUri(temValue)
    118. temStrCheck = self.PostData(temValue)
    119. except Exception as et:
    120. if temInit_msg.find(b"\r\n\r\n") == -1:
    121. return
    122. else:
    123. temValue = temInit_msg[0:temInit_msg.find(b"\r\n\r\n")].decode(Com_Para.U_CODE)
    124. self.attUri = self.parseUri(temValue)
    125. temStrCheck = self.PostData(temValue)
    126. inputHtHead = self.GetHttpHeadByte(temInit_msg)
    127. self.attConnection = Com_Fun.GetHashTable(inputHtHead,b"Connection").decode(Com_Para.U_CODE)
    128. #数据接口
    129. if temStrCheck[0] != "" and int(temStrCheck[0].split(":")[1].strip()) == len(temStrCheck[1].encode(Com_Para.U_CODE)):
    130. self.attPost_str = urllib.parse.unquote(temStrCheck[1].replace("+","%20"),Com_Para.U_CODE).split("&")
    131. if temStrCheck[1] != "":
    132. self.attUri += "&" + urllib.parse.unquote(temStrCheck[1].replace("+","%20"),Com_Para.U_CODE)
    133. #附件上传
    134. elif temStrCheck[0] != "" and int(temStrCheck[0].split(":")[1].strip()) > 0:
    135. if self.attUri.find("param_name=upLoadFile") != -1:
    136. bSaveFile = False
    137. #附件大小
    138. iAllLength = int(temStrCheck[0].split(":")[1].strip())
    139. if Com_Fun.GetHashTable(inputHtHead,b"Content-Type").find(b"boundary=") == -1:
    140. boundary = Com_Fun.Get_New_GUID().encode(Com_Para.U_CODE)
    141. else:
    142. boundary = Com_Fun.GetHashTable(inputHtHead,b"Content-Type").split(b";")[1].split(b"=")[1]
    143. oldFileName = []
    144. newFileName = []
    145. temFile_dataAry = []
    146. bFlagF = -1
    147. while iAllLength > 0:
    148. bLastCR = False
    149. if Com_Fun.GetHashTableNone(inputHtHead, b"Content-Disposition") != None and len(temFile_dataAry) == 0:
    150. temFile_dataAry = self.GetHttpHeadArray(temInit_msg)
    151. if temInit_msg[len(temInit_msg)-1:len(temInit_msg)] == b'\n':
    152. bLastCR = True
    153. else:
    154. temInit_msg = self.attServSocket.recv(iAllLength)
    155. temFile_dataAry = temInit_msg.split(b'\n')
    156. if temInit_msg[len(temInit_msg)-1:len(temInit_msg)] == b'\n':
    157. bLastCR = True
    158. iIndex = 0
    159. for temItem in temFile_dataAry:
    160. #判断是否正确附件码
    161. if temItem.find(b"--"+boundary) == 0 and temFile is not None:
    162. bSaveFile = True
    163. temFile.close()
    164. temFile = None
    165. bFlagF = -1
    166. #判断是否附件模块
    167. if temItem.find(b"Content-Disposition: form-data") == 0:
    168. cdAry = temItem.split(b";")
    169. if len(cdAry) == 3 and cdAry[2].find(b"filename=") == 1:
    170. bFlagF = 0
    171. else:
    172. bFlagF = -1
    173. if bFlagF == 0 and temItem.find(b"Content-Disposition:") == 0:
    174. oldN = temItem.split(b":")[1].split(b";")[2].split(b"=")[1].replace(b"\r",b"").replace(b"\n",b"").replace(b"\"",b"")
    175. if oldN != b"" and oldN.find(b".") != -1:
    176. if Com_Para.attUpFile.find((oldN.split(b".")[1].lower()+b"|").decode(Com_Para.U_CODE)) == -1:
    177. oldFileName.append("不符合上传文件格式,上传失败:"+oldN.decode(Com_Para.U_CODE))
    178. newFileName.append("不符合上传文件格式,上传失败:"+oldN.decode(Com_Para.U_CODE))
    179. else:
    180. oldFileName.append(oldN.decode(Com_Para.U_CODE))
    181. if oldN.find(b".") == -1:
    182. newFileName.append(Com_Fun.Get_New_GUID().replace("-", "")+".no")
    183. else:
    184. newFileName.append(Com_Fun.Get_New_GUID().replace("-", "")+"."+oldN.decode(Com_Para.U_CODE).split(".")[1])
    185. strF = Com_Para.ApplicationPath+Com_Para.zxyPath+"web"+Com_Para.zxyPath+"file"+Com_Para.zxyPath+newFileName[len(newFileName) - 1]
    186. temFile = open(strF, "wb")
    187. bFlagF = 1
    188. elif bFlagF == 1 and temItem == b"\r":
    189. bFlagF = 2
    190. elif bFlagF == 2 and temFile is not None and iAllLength > 0:
    191. if temItem != b'' and (b"--"+boundary).find(temItem) == 0:
    192. bSaveFile = True
    193. temFile.close()
    194. temFile = None
    195. bFlagF = -1
    196. #break
    197. else:
    198. temFile.write(temItem)
    199. #加上\n间隔符
    200. if iIndex != len(temFile_dataAry) - 1 or bLastCR == True:
    201. temFile.write(b'\n')
    202. iIndex = iIndex + 1
    203. iAllLength = iAllLength - len(temItem+b'\n')
    204. if temFile is not None:
    205. bSaveFile = True
    206. temFile.close()
    207. temFile = None
    208. if bSaveFile == False:
    209. self.attRv.s_result = 0
    210. self.attRv.err_desc = "文件上传失败,请刷新网络或重新上传"
    211. self.attUploadFile = "{\"A01_UpLoadFile\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"上传失败,请刷新网络或重新上传\"}]}"
    212. return
    213. jso = {}
    214. jsary = []
    215. iIndex = 0
    216. for temItem in oldFileName:
    217. temjso = {}
    218. temjso[Com_Fun.GetLowUpp("oldFileName")] = temItem
    219. temjso[Com_Fun.GetLowUpp("newFileName")] = newFileName[iIndex]
    220. jsary.append(temjso)
    221. iIndex = iIndex + 1
    222. jso["A01_UpLoadFile"] = jsary
    223. self.attUploadFile = json.dumps(jso,ensure_ascii=False)
    224. else:
    225. temStrCheck[1] = ""
    226. temInit_msg = b''
    227. temInit_msg = self.attServSocket.recv(20480)
    228. temStrCheck[1] = urllib.parse.unquote(temInit_msg.decode(Com_Para.U_CODE),Com_Para.U_CODE)
    229. self.attPost_str = temStrCheck[1].split("&")
    230. if temStrCheck[1] != "":
    231. self.attUri += "&" + temStrCheck[1]
    232. except Exception as e:
    233. self.attRv.s_result = 0
    234. self.attRv.err_desc = repr(e)
    235. self.attUploadFile = "{\"A01_UpLoadFile\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"上传失败,请刷新网络或重新上传\""+ repr(e)+"}]}"
    236. finally:
    237. if temFile is not None:
    238. temFile.close()
    239. temFile = None
    240. Pass

    com.zxy.main.Init_Page.py中添加如下内容

    1. from com.zxy.tcp.ServerThreadHttp import ServerThreadHttp
    2. @staticmethod
    3. def Start_Http():
    4. # 是否启用http协议接口
    5. if Com_Para.bThread == True:
    6. # TCP服务
    7. temSthttp = ServerThreadHttp("", "", Com_Para.port)
    8. t1 = threading.Thread(target=temSthttp.run, name="ServerHttpThread")
    9. t1.start()

    web接口服务运行案例MonitorDataCmd.py主文件中编写:

    添加如下内容:

    1. #web数据接口服务
    2. Init_Page.Start_Http()

    程序运行之后在浏览器敲入如下内容访问数据接口:

    http://localhost:9000/CenterData?param_name=A01_AAA111&sub_code=&sub_usercode=

    http://localhost:9000/CenterData?param_name=A01_AAA222&sub_code=&sub_usercode=

    运行结果见图:

    后台数据获取调式见:

    com.zxy.business.Ope_DB_Cent.py

      def Cal_Data(self, inputSub_code, inputParam_name, inputAryParamValue, inputStrIP,inputSession_id,inputHtParam):
    1. 监测数据采集物联网应用开发步骤(12.3)
  • 相关阅读:
    上周热点回顾(7.3-7.9)
    系统运行缓慢,CPU 100%,以及Full GC次数过多问题的排查思路
    基于SpringBoot的花店销售网站
    【Flask基础】六,拦截器/请求钩子(全局+模块+资源选择性放行)
    Cent OS 使用ip addr or nmcli 分配临时IP地址
    linux安装jdk(正式环境)
    Oracle中LEFT JOIN后AND与WHERE的异同
    LibTorch之网络模型构建
    手记系列之六 ----- 分享个人使用kafka经验
    【云原生之Docker实战】使用Docker部署flatnotes笔记工具
  • 原文地址:https://blog.csdn.net/yong427/article/details/133941079