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


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

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

    本章节进行前端web UI开发+web数据接口服务开发

    web数据接口服务利用SOCKET TCP服务方式解析http协议内容模式

    com.zxy.common.Com_Para.py中添加如下内容

    1. #修改web数据接口服务端口
    2. port = 9000
    3. #是否启用http协议
    4. bThread = True
    5. #web数据接口访问函数名
    6. Inf_Name = "CenterData"
    7. #web文件后缀{}
    8. web_Name = [".html", ".js", ".css", ".jpg", ".gif", ".png", ".svg", ".eot", ".ttf", ".woff2", ".woff", ".ico" ,".json", ".log",".xlsx",".xls",".vue",".dlls"]
    9. #web数据接口返回值字段大小写,0不设置 1大写 2小写
    10. iReturnUppLower = 1
    11. #web数据接口TCP连接socket统计
    12. socket_count = 0
    13. #指定跨域访问IP xxx.xx.xx.xxx 默认为空
    14. HttpUrl = ""
    15. #上传文件后缀
    16. attUpFile = ".txt|.zip|.rar|.tar|.json|.jpg|.bmp|.gif|.xls|.xlsx|.sql|.doc|.docx|"

    com.zxy.common.Com_Fun.py中添加代码

    1. #web数据接口返回值参数大小写
    2. @staticmethod
    3. def GetLowUpp(inputValue):
    4. if Com_Para.iReturnUppLower == 1:
    5. return inputValue.upper()
    6. elif Com_Para.iReturnUppLower == 2:
    7. return inputValue.lower()
    8. else:
    9. return inputValue

    新建web数据接口返回格式类com.zxy.model.Return_Value.py

    1. #! python3
    2. # -*- coding: utf-8 -
    3. '''
    4. Created on 2017年05月10日
    5. @author: zxyong 13738196011
    6. '''
    7. from com.zxy.common.Com_Fun import Com_Fun
    8. #监测数据采集物联网应用--web数据接口返回格式
    9. class Return_Value(object):
    10. attParam_name = "COMMOND_NAME"
    11. attS_result = 1
    12. attErr_desc = "成功"
    13. def __init__(self):
    14. pass
    15. def Back_Value(self):
    16. return "{\""+self.attParam_name+"\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\""+self.attS_result+"\",\""+Com_Fun.GetLowUpp("err_desc")+"\":\""+self.attErr_desc+"\"}]}"
    17. 新建数据业务处理和获取类com.zxy.business.Ope_DB_Cent.py
    18. #! python3
    19. # -*- coding: utf-8 -
    20. '''
    21. Created on 2017年05月10日
    22. @author: zxyong 13738196011
    23. '''
    24. from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
    25. from com.zxy.common import Com_Para
    26. from com.zxy.common.Com_Fun import Com_Fun
    27. from com.zxy.db_Self.Db_Common_Self import Db_Common_Self
    28. from com.zxy.z_debug import z_debug
    29. #监测数据采集物联网应用--数据业务处理、获取
    30. class Ope_DB_Cent(z_debug):
    31. attICount = 0
    32. attS_result = 1
    33. def __init__(self):
    34. pass
    35. #带参数数据库读写
    36. # temSqlIns = "insert into xxx(x,x,x) values(?,?,?)
    37. # temParameters = []
    38. # temParamTypes = []
    39. # temParamOutName = []
    40. # temParamOutType = []
    41. # iIndex = 0
    42. # try:
    43. # temDb_self = Db_Common_Self()
    44. # temTpn = T_PROC_NAME()
    45. # temTpn.attINF_EN_SQL = temSqlIns
    46. # temDb_self.Common_Sql_Proc("Ins_Data_JSON",temParameters,temParamTypes,temParamOutName,temParamOutType,temTpn)
    47. # #temSqlException = temDb_self.attSqlException
    48. # #temColumnNames = temDb_self.attColumnNames
    49. # except Exception as es:
    50. # temError = "get data error[Ins_Data_JSON]" +temSqlIns+") "+temstrSqlValues+")" +"\r\n"+repr(es)
    51. # uL = UsAdmin_Log(Com_Para.ApplicationPath, temError)
    52. # uL.WriteLog()
    53. #resultSet转Json
    54. def ResultSetToJson(self,input_sql):
    55. temDbSelf = Db_Common_Self()
    56. temRs = temDbSelf.Common_Sql(input_sql)
    57. temColumnNames = temDbSelf.attColumnNames
    58. jsary1 = []
    59. try:
    60. for temItem in temRs:
    61. temjso1 = {}
    62. for i in range(0,len(temColumnNames)):
    63. if temItem[i] != "null":
    64. temjso1[Com_Fun.GetLowUpp(temColumnNames[i][0])] = temItem[i]
    65. else:
    66. temjso1[Com_Fun.GetLowUpp(temColumnNames[i][0])] = ""
    67. jsary1.append(temjso1)
    68. except Exception as e:
    69. temLog = ""
    70. if str(type(self)) == "":
    71. temLog = self.debug_info(self)+input_sql+"==>"+repr(e)
    72. self.debug_in(self,input_sql+"==>"+repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    73. else:
    74. temLog = self.debug_info(self)+input_sql+"==>"+repr(e)
    75. self.debug_in(input_sql+"==>"+repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    76. uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
    77. uL.WriteLog()
    78. return jsary1
    79. #数据业务处理、获取
    80. def Cal_Data(self, inputSub_code, inputParam_name, inputAryParamValue, inputStrIP,inputSession_id,inputHtParam):
    81. temResult = ""
    82. if inputParam_name == "init_page":
    83. #写读取缓存内容
    84. return "{\"" + inputParam_name + "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"读取缓存信息成功!\"}]}"
    85. elif inputParam_name == "A01_AAA111":
    86. return "{\"" + inputParam_name + "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"后台获取的业务时间:"+Com_Fun.GetTimeDef()+"\"}]}"
    87. elif inputParam_name == "A01_AAA222":
    88. return "{\"" + inputParam_name + "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"后台获取的GUID:"+Com_Fun.Get_New_GUID()+"\"}]}"
    89. return temResult

    新建web数据接口业务查询类com.zxy.business.Query_Data.py

    1. #! python3
    2. # -*- coding: utf-8 -
    3. '''
    4. Created on 2017年05月10日
    5. @author: zxyong 13738196011
    6. '''
    7. from com.zxy.z_debug import z_debug
    8. from com.zxy.model.Return_Value import Return_Value
    9. from com.zxy.business.Ope_DB_Cent import Ope_DB_Cent
    10. #监测数据采集物联网应用--web数据接口业务查询
    11. class Query_Data(z_debug):
    12. attSession_id = ""
    13. attReturn_Value = Return_Value()
    14. def __init__(self,inputReturn_Value):
    15. self.attReturn_Value = inputReturn_Value
    16. #后台数据处理
    17. def GetDataList(self,inputSub_code, inputSub_usercode, inputParam_name, inputAryParamValue, inputStrUrl, inputDelay_data, inputDelay_code, inputStrIP,inputHtParam):
    18. temOpd = Ope_DB_Cent()
    19. temResult = temOpd.Cal_Data(inputSub_code,inputParam_name,inputAryParamValue,inputStrIP,self.attSession_id,inputHtParam)
    20. return temResult
    21. 新建web数据接口socket服务类com.zxy.tcp.ServerThreadHttp.py
    22. #! python3
    23. # -*- coding: utf-8 -
    24. '''
    25. Created on 2017年05月10日
    26. @author: zxyong 13738196011
    27. '''
    28. import socket,threading
    29. from com.zxy.z_debug import z_debug
    30. from com.zxy.tcp.ServerHandlerHttp import ServerHandlerHttp
    31. #监测数据采集物联网应用--web数据接口socket服务
    32. class ServerThreadHttp(z_debug):
    33. attStrValue = ""
    34. attStrNum = ""
    35. attPort = 0
    36. def __init__(self, inputStrValue,inputNum,inputPort):
    37. self.attStrNum = inputNum
    38. self.attStrValue = inputStrValue
    39. self.attPort = inputPort
    40. def run(self):
    41. temS = None
    42. try:
    43. temS = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    44. temS.bind(('0.0.0.0', self.attPort))
    45. temS.listen(400)
    46. while True:
    47. try:
    48. sock,addr = temS.accept()
    49. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    50. temServerHH = ServerHandlerHttp()
    51. temServerHH.attServSocket = sock
    52. temServerHH.attStrIP = addr
    53. t1 = threading.Thread(target=temServerHH.run, name="ServerHttpThread"+"_"+str(addr[0])+"_"+str(addr[1]))
    54. t1.start()
    55. except Exception as en:
    56. if str(type(self)) == "":
    57. self.debug_in(self,repr(en)+"=>"+str(en.__traceback__.tb_lineno))#打印异常信息
    58. else:
    59. self.debug_in(repr(en)+"=>"+str(en.__traceback__.tb_lineno))#打印异常信息
    60. pass
    61. except Exception as e:
    62. if str(type(self)) == "":
    63. self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    64. else:
    65. self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    66. pass

    新建web数据接口服务Handler类com.zxy.tcp.ServerHandlerHttp.py

    1. #! python3
    2. # -*- coding: utf-8 -
    3. '''
    4. Created on 2017年05月10日
    5. @author: zxyong 13738196011
    6. '''
    7. import os
    8. from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
    9. from com.zxy.business.Query_Data import Query_Data
    10. from com.zxy.common import Com_Para
    11. from com.zxy.common.Com_Fun import Com_Fun
    12. from com.zxy.model.Return_Value import Return_Value
    13. from com.zxy.tcp.Request import Request
    14. from com.zxy.z_debug import z_debug
    15. #监测数据采集物联网应用--web数据接口服务Handler
    16. class ServerHandlerHttp(z_debug):
    17. attServSocket = None
    18. attStrIP = "0.0.0.0"
    19. attReturn_Value = Return_Value()
    20. attConnection = ""
    21. def __init__(self):
    22. pass
    23. def run(self):
    24. self.server_link()
    25. def server_link(self):
    26. Com_Para.socket_count = Com_Para.socket_count + 1
    27. if Com_Para.driverClassName == "org.sqlite.JDBC":
    28. self.init()
    29. else:
    30. self.init()
    31. Com_Para.socket_count = Com_Para.socket_count - 1
    32. #web文件内容加载,如:html css js......
    33. def webPage_Real(self,inputStrUrl,inputS_guid,inputPost_str,inputQuery_Data,inputReturnMessage,inputWeb_name):
    34. temFilePath = Com_Para.ApplicationPath +Com_Para.zxyPath+ "web"
    35. if inputWeb_name == ".log":
    36. temFilePath = Com_Para.ApplicationPath
    37. if inputStrUrl[0:10] =="/root_api/":
    38. temFUrl = inputStrUrl[10:inputStrUrl.index(inputWeb_name)]
    39. else:
    40. temFUrl = inputStrUrl[0:inputStrUrl.index(inputWeb_name)]
    41. temFilePath = temFilePath + Com_Para.zxyPath+temFUrl
    42. temFilePath = temFilePath + inputWeb_name
    43. if os.path.exists(temFilePath):
    44. bVue = False
    45. #自定义页面组件后缀
    46. if inputStrUrl.find(".dlls") != -1 and inputStrUrl.find(".dlls") == len(inputStrUrl) - len(".dlls"):
    47. bVue = True
    48. temFile = None
    49. try:
    50. temFile = open(file=temFilePath,mode='rb')
    51. self.attServSocket.send((inputReturnMessage +"\r\n\r\n").encode(Com_Para.U_CODE))
    52. if bVue:
    53. self.attServSocket.send(b'ReadCommonRes("')
    54. while True:
    55. byt = temFile.read(1024)# 每次读取1024个字节
    56. if bVue :
    57. self.attServSocket.send(byt.replace(b'\t',b'').replace(b'\n',b'').replace(b'\r',b'').replace(b'\"',b'\\\"').replace(b'$',b'"'))
    58. else:
    59. self.attServSocket.send(byt)#字节形式发送数据
    60. if not byt: #如果没有读到数据,跳出循环
    61. break
    62. if bVue:
    63. self.attServSocket.send(b'");')
    64. self.attServSocket.send("\r\n".encode(Com_Para.U_CODE))
    65. except Exception as e:
    66. if str(type(self)) == "":
    67. self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    68. else:
    69. self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    70. finally:
    71. if not temFile is None:
    72. temFile.close()
    73. else:
    74. temErrorMessage = "HTTP/1.1 404 File Not Found\r\n"
    75. temErrorMessage += "Content-Type: text/html\r\n"
    76. temErrorMessage += "Content-Length: 230\r\n"
    77. temErrorMessage += "\r\n" + "

      未找到正确页面

      "
    78. try:
    79. self.attServSocket.send(temErrorMessage.encode(Com_Para.U_CODE))
    80. self.attServSocket.send("\r\n".encode(Com_Para.U_CODE))
    81. except Exception as e:
    82. pass
    83. #解析http协议
    84. def SubAnalyseRecBytes(self,temRequest):
    85. temS_guid = ""
    86. temRequest.parse()
    87. self.attConnection = temRequest.attConnection
    88. temStrUrl = temRequest.attUri
    89. temPost_Str = temRequest.attPost_str
    90. self.attReturn_Value = temRequest.attRv
    91. temReturnMessage = "HTTP/1.1 200 OK\r\n"
    92. if temStrUrl.find(".html") != -1 and temStrUrl.find(".html") == len(temStrUrl) - 5:
    93. temReturnMessage += "Content-Type: text/html\r\n"
    94. elif temStrUrl.find(".js") != -1 and temStrUrl.find(".js") == len(temStrUrl) - 3:
    95. temReturnMessage += "Content-Type: application/x-javascript\r\n"
    96. elif temStrUrl.find(".css") != -1 and temStrUrl.find(".css") == len(temStrUrl) - 4:
    97. temReturnMessage += "Content-Type: text/css\r\n"
    98. elif temStrUrl.find(".jpg") != -1 and temStrUrl.find(".jpg") == len(temStrUrl) - 4:
    99. temReturnMessage += "Content-Type: image/jpg\r\n"
    100. elif temStrUrl.find(".gif") != -1 and temStrUrl.find(".gif") == len(temStrUrl) - 4:
    101. temReturnMessage += "Content-Type: image/jpg\r\n"
    102. elif temStrUrl.find(".png") != -1 and temStrUrl.find(".png") == len(temStrUrl) - 4:
    103. temReturnMessage += "Content-Type: mage/png\r\n"
    104. elif temStrUrl.find(".svg") != -1 and temStrUrl.find(".svg") == len(temStrUrl) - 4:
    105. temReturnMessage += "Content-Type: text/svg+xml\r\n"
    106. elif temStrUrl.find(".eot") != -1 and temStrUrl.find(".eot") == len(temStrUrl) - 4:
    107. temReturnMessage += "Content-Type: application/vnd.ms-fontobject\r\n"
    108. elif temStrUrl.find(".ttf") != -1 and temStrUrl.find(".ttf") == len(temStrUrl) - 4:
    109. temReturnMessage += "Content-Type: application/x-font-ttf\r\n"
    110. elif temStrUrl.find(".woff") != -1 and temStrUrl.find(".woff") == len(temStrUrl) - 5:
    111. temReturnMessage += "Content-Type: application/x-font-woff\r\n"
    112. elif temStrUrl.find(".woff2") != -1 and temStrUrl.find(".woff2") == len(temStrUrl) - 6:
    113. temReturnMessage += "Content-Type: application/x-font-woff\r\n"
    114. elif temStrUrl.find(".ico") != -1 and temStrUrl.find(".ico") == len(temStrUrl) - 4:
    115. temReturnMessage += "Content-Type: image/ico\r\n"
    116. elif temStrUrl.find(".log") != -1 and temStrUrl.find(".log") == len(temStrUrl) - 4:
    117. temReturnMessage += "Content-Type: text\r\n"
    118. elif temStrUrl.find(".dlls") != -1 and temStrUrl.find(".dlls") == len(temStrUrl) - 4:
    119. temReturnMessage += "Content-Type: application/x-javascript\r\n"
    120. elif temStrUrl.find(".vue") != -1 and temStrUrl.find(".vue") == len(temStrUrl) - 4:
    121. temReturnMessage += "Content-Type: application/x-javascript\r\n"
    122. else:
    123. temReturnMessage += "Content-Type: text/html\r\n"
    124. temReturnMessage += "Access-Control-Allow-Methods: POST,GET\r\n"
    125. temReturnMessage += "Access-Control-Allow-Origin:*" + Com_Para.HttpUrl
    126. temReturnMessage += "\r\n" + "Connection: Keep-Alive"
    127. temStrResult = "-1"
    128. temGd = Query_Data(self.attReturn_Value)
    129. #通用接口
    130. bWeb_Name = False
    131. for temAttF in Com_Para.web_Name:
    132. if temStrUrl.find(temAttF) != -1 and temStrUrl.find(temAttF) == len(temStrUrl) - len(temAttF) and temStrUrl.find("param_name=") == -1:
    133. self.webPage_Real(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage,temAttF)
    134. bWeb_Name = True
    135. break
    136. if bWeb_Name == True or temRequest.attUploadFile != "":
    137. pass
    138. elif temStrUrl.find("sub_code=") != -1 and temStrUrl.find("param_name=") != -1:
    139. temStrResult = self.Center_Data_Rel(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage,temRequest.attStrIP[0])
    140. elif temStrUrl.strip() == "" and temStrUrl.strip().find("GET /favicon.ico HTTP/1.1") != -1:
    141. temStrResult = self.Send_Error(temStrUrl,temS_guid,temPost_Str,temGd,temReturnMessage)
    142. elif temStrUrl.strip() != "":
    143. self.attServSocket.send((temReturnMessage+"\r\n\r\n请求错误接口或页面\r\n").encode(Com_Para.U_CODE))
    144. if temRequest.attUploadFile != "":
    145. self.attServSocket.send((temReturnMessage + "\r\n\r\n" + temRequest.attUploadFile + "\r\n").encode(Com_Para.U_CODE))
    146. elif temStrResult != "-1":
    147. self.attServSocket.send((temReturnMessage + "\r\n\r\n" + temStrResult + "\r\n").encode(Com_Para.U_CODE))
    148. return temReturnMessage
    149. #初始化
    150. def init(self):
    151. try:
    152. temRequest = Request()
    153. temRequest.attServSocket = self.attServSocket
    154. temRequest.attStrIP = self.attStrIP
    155. self.attServSocket.setblocking(1)
    156. temReturnMessage = self.SubAnalyseRecBytes(temRequest)
    157. except Exception as e:
    158. self.attServSocket.send(temReturnMessage+"\r\n\r\n"+repr(e)+"\r\n".encode(Com_Para.U_CODE))
    159. temLog = ""
    160. if str(type(self)) == "":
    161. temLog = self.debug_info(self)+repr(e)
    162. self.debug_in(self,repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    163. else:
    164. temLog = self.debug_info()+repr(e)
    165. self.debug_in(repr(e)+"=>"+str(e.__traceback__.tb_lineno))#打印异常信息
    166. uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
    167. uL.WriteLog()
    168. finally:
    169. self.attServSocket.shutdown(1)
    170. self.attServSocket.close()
    171. def Send_Error(self,inputStrUrl,inputS_guid,inputPost_Str,inputGd,inputReturnMessage):
    172. inputReturnMessage = "Error请求语法错误"
    173. return inputReturnMessage
    174. #通用获取数据接口
    175. def Center_Data_Rel(self,inputStrUrl, inputS_guid, inputPost_Str, inputGd, inputReturnMessage, inputStrIP):
    176. temStrAry = ""
    177. #
    178. temHtParam = {}
    179. for temStrTemV in inputStrUrl.split("&"):
    180. temStrTemPar = temStrTemV.split("=")
    181. if len(temStrTemPar) == 2:
    182. Com_Fun.SetHashTable(temHtParam,temStrTemPar[0],temStrTemPar[1])
    183. else:
    184. Com_Fun.SetHashTable(temHtParam,temStrTemPar[0],"")
    185. temSub_code = Com_Fun.GetHashTable(temHtParam,"sub_code")
    186. temSub_usercode = Com_Fun.GetHashTable(temHtParam,"sub_usercode")
    187. temDelay_data = Com_Fun.GetHashTable(temHtParam,"delay_data")
    188. temDelay_code = Com_Fun.GetHashTable(temHtParam,"delay_code")
    189. temParam_name = Com_Fun.GetHashTable(temHtParam,"param_name")
    190. temSession_id = Com_Fun.GetHashTable(temHtParam,"session_id")
    191. temJsoncallback = Com_Fun.GetHashTable(temHtParam,"jsoncallback")
    192. self.attReturn_Value.attParam_name = temParam_name
    193. #传递in 参数
    194. temAryParamValue = []
    195. for temTemstr in inputPost_Str:
    196. if temTemstr == "jsonpzxyong":
    197. temJsoncallback = temTemstr.split("=")[1]
    198. break
    199. #获取版本号
    200. if temParam_name == "get_version":
    201. temStrAry = "{\""+ temParam_name+ "\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"1\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"\",\""+Com_Fun.GetLowUpp("version")+"\":\""+Com_Para.version+"\"}]}"
    202. #通用数据接口
    203. else:
    204. inputGd.attSession_id = temSession_id
    205. temStrAry = inputGd.GetDataList(temSub_code,temSub_usercode,temParam_name,temAryParamValue,inputStrUrl,temDelay_data,temDelay_code,inputStrIP,temHtParam)
    206. if temJsoncallback != "":
    207. temStrAry = temJsoncallback + "("+temStrAry+")"
    208. if self.attReturn_Value.attS_result == 1:
    209. self.attReturn_Value = inputGd.attReturn_Value
    210. temHtParam = None
    211. return temStrAry

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

  • 相关阅读:
    如何获取ABAP的程序事件顺序的调用堆栈
    HTML + JQuery + CSS 实现动态变色雪花特效
    算法通过村第十四关-堆|黄金笔记|中位数
    java毕业设计网约车管理系统源码+lw文档+mybatis+系统+mysql数据库+调试
    工程师如何对待开源
    java线程转储分析
    python基础06——控制流语句:顺序、分支、循环
    yolov5、yolov7-火焰识别项目实战
    2022.9.15模拟赛总结
    [附源码]java毕业设计二手车交易系统
  • 原文地址:https://blog.csdn.net/yong427/article/details/133940849