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

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

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

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

#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import urllib.parse,json
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.model.Return_Value import Return_Value               
from com.zxy.z_debug import z_debug

#监测数据采集物联网应用--web数据接口http-request解析
class Request(z_debug):

    attStrIP = ""
    attServSocket = None
    attUri = ""
    attPost_str = []
    attRv = Return_Value()
    attUploadFile = ""
    attConnection = ""
    
    def __init__(self):
        pass
    
    def parseUri(self,inputValue):
        temStrResult = ""
        if inputValue.find("/favicon.ico") != -1:
            temStrResult += "favicon.ico"
            return temStrResult
        elif inputValue.find(Com_Para.Inf_Name) != -1:
            for temStrITem in inputValue.split("\r\n"):
                if temStrITem.find(Com_Para.Inf_Name) != -1:
                    if (temStrITem.split(" ")[1]).find("?") != -1:
                        temStrResult += urllib.parse.unquote(temStrITem.split(" ")[1].split("?")[1])
                    else:
                        temStrResult += urllib.parse.unquote(temStrITem.split(" ")[1])
                    break
        elif self.FindWebName(inputValue):
            for temStrITem in inputValue.split("\r\n"):
                if self.FindWebName(temStrITem):
                    temStrT = temStrITem.split(" ")[1]
                    if temStrT.find("?") == -1:
                        temStrResult = urllib.parse.unquote(temStrITem.split(" ")[1],Com_Para.U_CODE)
                    else:
                        temStrResult = urllib.parse.unquote(temStrT[0:temStrT.find("?")],Com_Para.U_CODE)
                    break
        elif len(inputValue) > 10:
            temStrResult = inputValue
        return temStrResult
    
    def FindWebName(self,inputValue):
        for temAttF in Com_Para.web_Name:
            if inputValue.find(temAttF) != -1:
                return True
        return False
    
    def PostData(self,inputValue):
        temStrResult = ["",""]
        if self.FindWebName(inputValue):
            temStrTem = inputValue.split("\r\n")
            if len(temStrTem[0].split(" ")) > 1 and (temStrTem[0].split(" ")[0] == "POST" or temStrTem[0].split(" ")[0] == "OPTIONS") :
                temContent_Length = -1
                temStrEnd = inputValue[len(inputValue) - 4:len(inputValue)]
                if temStrEnd != "\r\n\r\n":
                    temStrResult[1] = temStrTem[len(temStrTem) - 1]
                for temStrItem in temStrTem:
                    temStrItem = urllib.parse.unquote(temStrItem,Com_Para.U_CODE)
                    if temStrItem.find("post_param: ") == 0:
                        temStrResult[1] = temStrItem[temStrItem.find("post_param: ") + 12:len(temStrItem)]
                        temStrResult[0] = "Content-Length:"
                        temStrResult[0] += str(len(temStrResult[1]))
                        break
                    if temStrItem.find("Content-Length:") == 0:
                        temContent_Length = int(temStrItem.split(":")[1].strip())
                        temStrResult[0] = "Content-Length:"
                        temStrResult[0] += str(temContent_Length)
                    if temContent_Length > 0 and temContent_Length == len(temStrResult[1].encode(Com_Para.U_CODE)):
                        break
        return temStrResult
    
    def GetHttpHeadByte(self,inputValue):
        temResult = {}
        for temStrItem in inputValue.split(b"\r\n"):
            if temStrItem.find(b"POST") == 0 or temStrItem.find(b"GET") == 0:                
                strKey = temStrItem.split(b" ")[0]          
                strValue = temStrItem.split(b" ")[1]
            else:
                strKey = temStrItem[0:temStrItem.find(b":")]            
                strValue = temStrItem[len(strKey)+1:len(temStrItem)]
            if Com_Fun.GetHashTableNone(temResult, strKey) == None:
                Com_Fun.SetHashTable(temResult, strKey, strValue)
        return temResult
    
    def GetHttpHead(self,inputValue):
        temResult = {}
        for temStrITem in inputValue.split("\r\n"):
            if temStrITem.find("POST") == 0 or temStrITem.find("GET") == 0:                
                strKey = temStrITem.split(" ")[0]          
                strValue = temStrITem.split(" ")[1]
            else:
                strKey = temStrITem[0:temStrITem.find(":")]            
                strValue = temStrITem[len(strKey)+1:len(temStrITem)]
            if Com_Fun.GetHashTableNone(temResult, strKey) == None:
                Com_Fun.SetHashTable(temResult, strKey, strValue)
        return temResult
    
    def GetHttpHeadArray(self,inputValue):
        inputValue = inputValue[inputValue.find(b"\r\n\r\n")+4:len(inputValue)]
        temResult = []
        for temStrITem in inputValue.split(b"\n"):
            temResult.append(temStrITem)
        return temResult
    
    #从套接字中读取字符信息
    def parse(self):        
        temInit_msg = b'' # 初始化流
        temFile = None
        temValue = ""
        try:        
            temInit_msg = self.attServSocket.recv(20480) #接受数据  20480
            temStrCheck = []
            #特殊符号处理
            try:
                temValue = temInit_msg.decode(Com_Para.U_CODE)
                self.attUri = self.parseUri(temValue)
                temStrCheck = self.PostData(temValue)
            except Exception as et:
                if temInit_msg.find(b"\r\n\r\n") == -1:
                    return
                else:
                    temValue = temInit_msg[0:temInit_msg.find(b"\r\n\r\n")].decode(Com_Para.U_CODE)                    
                    self.attUri = self.parseUri(temValue)
                    temStrCheck = self.PostData(temValue)                    
            inputHtHead = self.GetHttpHeadByte(temInit_msg)
            self.attConnection = Com_Fun.GetHashTable(inputHtHead,b"Connection").decode(Com_Para.U_CODE)            
            #数据接口
            if temStrCheck[0] != "" and int(temStrCheck[0].split(":")[1].strip()) == len(temStrCheck[1].encode(Com_Para.U_CODE)):
                self.attPost_str = urllib.parse.unquote(temStrCheck[1].replace("+","%20"),Com_Para.U_CODE).split("&")
                if temStrCheck[1] != "":
                    self.attUri += "&" + urllib.parse.unquote(temStrCheck[1].replace("+","%20"),Com_Para.U_CODE)                
            #附件上传
            elif temStrCheck[0] != "" and int(temStrCheck[0].split(":")[1].strip()) > 0:                
                if self.attUri.find("param_name=upLoadFile") != -1:
                    bSaveFile = False
                    #附件大小
                    iAllLength = int(temStrCheck[0].split(":")[1].strip())
                    if Com_Fun.GetHashTable(inputHtHead,b"Content-Type").find(b"boundary=") == -1:
                        boundary = Com_Fun.Get_New_GUID().encode(Com_Para.U_CODE)
                    else:
                        boundary = Com_Fun.GetHashTable(inputHtHead,b"Content-Type").split(b";")[1].split(b"=")[1]
                    oldFileName = []
                    newFileName = []
                    temFile_dataAry = []
                    bFlagF = -1
                    while iAllLength > 0:
                        bLastCR = False
                        if Com_Fun.GetHashTableNone(inputHtHead, b"Content-Disposition") != None and len(temFile_dataAry) == 0:
                            temFile_dataAry = self.GetHttpHeadArray(temInit_msg)
                            if temInit_msg[len(temInit_msg)-1:len(temInit_msg)] == b'\n':
                                bLastCR = True
                        else:
                            temInit_msg = self.attServSocket.recv(iAllLength)
                            temFile_dataAry = temInit_msg.split(b'\n')
                            if temInit_msg[len(temInit_msg)-1:len(temInit_msg)] == b'\n':
                                bLastCR = True                                
                        iIndex = 0
                        for temItem in temFile_dataAry:
                            #判断是否正确附件码
                            if temItem.find(b"--"+boundary) == 0 and temFile is not None:
                                bSaveFile = True
                                temFile.close()
                                temFile = None
                                bFlagF = -1
                            #判断是否附件模块
                            if temItem.find(b"Content-Disposition: form-data") == 0:
                                cdAry = temItem.split(b";")
                                if len(cdAry) == 3 and cdAry[2].find(b"filename=") == 1:
                                    bFlagF = 0                     
                                else:
                                    bFlagF = -1                            
                            if bFlagF == 0 and temItem.find(b"Content-Disposition:") == 0:
                                oldN = temItem.split(b":")[1].split(b";")[2].split(b"=")[1].replace(b"\r",b"").replace(b"\n",b"").replace(b"\"",b"")
                                if oldN != b"" and oldN.find(b".") != -1:
                                    if Com_Para.attUpFile.find((oldN.split(b".")[1].lower()+b"|").decode(Com_Para.U_CODE)) == -1:
                                        oldFileName.append("不符合上传文件格式,上传失败:"+oldN.decode(Com_Para.U_CODE))
                                        newFileName.append("不符合上传文件格式,上传失败:"+oldN.decode(Com_Para.U_CODE))
                                    else:
                                        oldFileName.append(oldN.decode(Com_Para.U_CODE))                                
                                        if oldN.find(b".") == -1:
                                            newFileName.append(Com_Fun.Get_New_GUID().replace("-", "")+".no")                                
                                        else:
                                            newFileName.append(Com_Fun.Get_New_GUID().replace("-", "")+"."+oldN.decode(Com_Para.U_CODE).split(".")[1])
                                        strF = Com_Para.ApplicationPath+Com_Para.zxyPath+"web"+Com_Para.zxyPath+"file"+Com_Para.zxyPath+newFileName[len(newFileName) - 1]
                                        temFile = open(strF, "wb")
                                        bFlagF = 1
                            elif bFlagF == 1 and temItem == b"\r":
                                bFlagF = 2
                            elif bFlagF == 2 and temFile is not None and iAllLength > 0:
                                if temItem != b'' and (b"--"+boundary).find(temItem) == 0:
                                    bSaveFile = True
                                    temFile.close()
                                    temFile = None
                                    bFlagF = -1
                                    #break
                                else:
                                    temFile.write(temItem)
                                    #加上\n间隔符
                                    if iIndex != len(temFile_dataAry) - 1 or bLastCR == True:
                                        temFile.write(b'\n')
                            iIndex = iIndex + 1  
                            iAllLength = iAllLength - len(temItem+b'\n')                  
                    if temFile is not None:
                        bSaveFile = True
                        temFile.close()
                        temFile = None               
                    if bSaveFile == False:                        
                        self.attRv.s_result = 0
                        self.attRv.err_desc = "文件上传失败,请刷新网络或重新上传"
                        self.attUploadFile = "{\"A01_UpLoadFile\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"上传失败,请刷新网络或重新上传\"}]}"
                        return
                    jso = {}
                    jsary = []
                    iIndex = 0
                    for temItem in oldFileName:
                        temjso = {}
                        temjso[Com_Fun.GetLowUpp("oldFileName")] = temItem
                        temjso[Com_Fun.GetLowUpp("newFileName")] = newFileName[iIndex]
                        jsary.append(temjso) 
                        
                        iIndex = iIndex + 1    
                    jso["A01_UpLoadFile"] = jsary                        
                    self.attUploadFile = json.dumps(jso,ensure_ascii=False)       
                else:                
                    temStrCheck[1] = ""                
                    temInit_msg = b''
                    temInit_msg = self.attServSocket.recv(20480)
                    temStrCheck[1] = urllib.parse.unquote(temInit_msg.decode(Com_Para.U_CODE),Com_Para.U_CODE)   
                    self.attPost_str = temStrCheck[1].split("&")
                    if temStrCheck[1] != "":
                        self.attUri += "&" + temStrCheck[1]
        except Exception as e:
            self.attRv.s_result = 0
            self.attRv.err_desc = repr(e)
            self.attUploadFile = "{\"A01_UpLoadFile\":[{\""+Com_Fun.GetLowUpp("s_result")+"\":\"0\",\""+Com_Fun.GetLowUpp("error_desc")+"\":\"上传失败,请刷新网络或重新上传\""+ repr(e)+"}]}"
        finally:
            if temFile is not None:
                temFile.close()
                temFile = None
            Pass

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

from com.zxy.tcp.ServerThreadHttp import ServerThreadHttp


        
    @staticmethod
    def Start_Http():        
        # 是否启用http协议接口
        if Com_Para.bThread == True:
            # TCP服务
            temSthttp = ServerThreadHttp("", "", Com_Para.port)
            t1 = threading.Thread(target=temSthttp.run, name="ServerHttpThread")
            t1.start()

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

17、监测数据采集物联网应用开发步骤(12.2)_第1张图片

添加如下内容:

        #web数据接口服务
        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)

你可能感兴趣的:(python,物联网)