Jelajahi Sumber

更新物理世界数据

李莎 1 tahun lalu
melakukan
59b13202b5
10 mengubah file dengan 567 tambahan dan 0 penghapusan
  1. 9 0
      Dockerfile
  2. 49 0
      MyUtils/ConfigUtils.py
  3. 121 0
      MyUtils/DateUtils.py
  4. 42 0
      MyUtils/HttpUtil.py
  5. 53 0
      MyUtils/MetadataWebUtil.py
  6. 70 0
      MyUtils/MysqlUtils.py
  7. 115 0
      MyUtils/ZillionUtil.py
  8. 6 0
      config.xml
  9. 4 0
      requirements.txt
  10. 98 0
      start.py

+ 9 - 0
Dockerfile

@@ -0,0 +1,9 @@
+FROM python:3.7.15-slim
+
+
+WORKDIR ./python_physical_world_v3
+ADD . .
+
+RUN  pip install -r requirements.txt
+
+CMD ["python", "-u","./start.py"]

+ 49 - 0
MyUtils/ConfigUtils.py

@@ -0,0 +1,49 @@
+import xml.etree.ElementTree as ET
+
+
+#读取xml文件
+class ConfigUtils():
+    def __init__(self,file):
+        self.url = ""
+        self.tree = ET.parse(file)
+        self.root = self.tree.getroot()
+
+    def readTop(self, key, child):
+        datas = []
+        data = self.root.find(key)
+        for key in child:
+            datas.append(data.get(key))
+        return datas
+
+    def readTopDict(self, key, child):
+        datas = {}
+        data = self.root.find(key)
+        for key in child:
+            datas[key] = data.get(key)
+        return datas
+
+    def readConfig(self,parent,child):
+        datas=[]
+        for childLine in self.root.find(parent):
+            data=[]
+            for key in child:
+                data.append(childLine.get(key))
+            datas.append(data)
+        return datas
+
+    def readConfigDict(self,parent,child):
+        datas=[]
+        for childLine in self.root.find(parent):
+            data={}
+            for key in child:
+                data[key]=childLine.get(key)
+            datas.append(data)
+        return datas
+
+    def readConfigSingle(self,key):
+        data = self.root.find(key).text
+        return data
+
+
+if __name__ == '__main__':
+    config = ConfigUtils("logger.conf")

+ 121 - 0
MyUtils/DateUtils.py

@@ -0,0 +1,121 @@
+import datetime
+
+from dateutil import rrule
+
+YYmmddHHMMSS = "%Y%m%d%H%M%S"
+YYmmdd = "%Y%m%d"
+
+# 根据开始月份结束月份获取所有月份
+def get_each_month(start_month, end_month):
+    if str(start_month).count('-') != 1 or str(end_month).count('-') != 1:
+        print("Parameter Error: Pls input a string such as '2019-01'")
+        return []
+    if int(str(start_month).split('-')[1]) > 12 or int(str(end_month).split('-')[1]) > 12:
+        print('Parameter Error: Pls input correct month range such as between 1 to 12')
+        return []
+    if int(str(start_month).split('-')[1]) == 0 or int(str(end_month).split('-')[1]) == 13:
+        print('Parameter Error: Pls input correct month range such as between 1 to 12')
+        return []
+    start = datetime.datetime.strptime(start_month, "%Y-%m")
+    end = datetime.datetime.strptime(end_month, "%Y-%m")
+    month_count = rrule.rrule(rrule.MONTHLY, dtstart=start, until=end).count()  # 计算总月份数
+    if end < start:
+        print("Parameter Error: Pls input right date range,start_month can't latter than end_month")
+        return []
+    else:
+        list_month = []
+        year = int(str(start)[:7].split('-')[0])  # 截取起始年份
+        for m in range(month_count):  # 利用range函数填充结果列表
+            month = int(str(start)[:7].split('-')[1])  # 截取起始月份,写在for循环里,作为每次迭代的累加基数
+            month = month + m
+            if month > 12:
+                if month % 12 > 0:
+                    month = month % 12  # 计算结果大于12,取余数
+                    if month == 1:
+                        year += 1  # 只需在1月份的时候对年份加1,注意year的初始化在for循环外
+                else:
+                    month = 12
+            if len(str(month)) == 1:
+                list_month.append(str(year) + '-0' + str(month))
+            else:
+                list_month.append(str(year) + '-' + str(month))
+        return list_month
+
+
+# 转换格式,去掉"-",%Y%m
+def get_eachmonth(start_month, end_month):
+    startmonth = start_month[0:4] + "-" + start_month[4:6]
+    endmonth = end_month[0:4] + "-" + end_month[4:6]
+    months = get_each_month(startmonth, endmonth)
+    list_month = [i[0:4] + i[5:7] for i in months]
+    return list_month
+
+
+def get_month(starttime, endtime):
+    months = []
+    starttime = datetime.datetime.strptime(starttime[0:6], "%Y%m")
+    endtime = datetime.datetime.strptime(endtime[0:6], "%Y%m")
+    while starttime <= endtime:
+        start = starttime.strftime("%Y%m")
+        if start not in months:
+            months.append(start)
+        starttime = starttime + datetime.timedelta(days=1)
+    return months
+
+
+def get_month1(starttime, endtime):
+    months = []
+    startyear = int(starttime[0:4])
+    startmonth = int(starttime[4:6])
+    endyear = int(endtime[0:4])
+    endmonth = int(endtime[4:6])
+    while startyear != endyear or startmonth != endmonth:
+        startyearstr = str(startyear)
+        startmonthstr = str(startmonth)
+        if startmonth < 10:
+            startmonthstr = "0" + str(startmonth)
+        months.append(startyearstr + startmonthstr)
+        startmonth += 1
+        if startmonth == 13:
+            startyear += 1
+            startmonth = 1
+    months.append(endtime[0:6])
+    return months
+
+#根据开始结束时间获取最大区间为1天的时间区间
+# def get_day(starttime,endtime):
+#     times = []
+#     starttime = datetime.datetime.strptime(starttime, YYmmddHHMMSS)
+#     endtime = datetime.datetime.strptime(endtime, YYmmddHHMMSS)
+#     while starttime < endtime:
+#         start = starttime.strftime(YYmmddHHMMSS)
+#         starttime_delta = starttime + datetime.timedelta(days=1)
+#         end = starttime_delta.strftime(YYmmddHHMMSS)
+#         if str(starttime)[0:7]<str(starttime_delta)[0:7] :
+#             end = starttime_delta.strftime("%Y%m") +"01000000"
+#             starttime = datetime.datetime.strptime(end, YYmmddHHMMSS)
+#             times.append([start, end])
+#             continue
+#         if starttime >= starttime_delta:
+#             end = starttime_delta.strftime(YYmmddHHMMSS)
+#         starttime = starttime + datetime.timedelta(days=1)
+#         times.append([start,end])
+#     return times
+#根据开始结束时间获取最大区间为1天的时间区间
+def get_day(starttime,endtime):
+    times = []
+    starttime = datetime.datetime.strptime(starttime, YYmmddHHMMSS)
+    endtime = datetime.datetime.strptime(endtime, YYmmddHHMMSS)
+    while starttime < endtime:
+        start = starttime.strftime(YYmmddHHMMSS)
+        stratDay = datetime.datetime.strptime(start[0:8],YYmmdd)
+        starttime_delta = stratDay + datetime.timedelta(days=1)
+        end = starttime_delta.strftime(YYmmddHHMMSS)
+        if endtime <= starttime_delta:
+            end = endtime.strftime(YYmmddHHMMSS)
+        starttime = stratDay + datetime.timedelta(days=1)
+        times.append([start,end])
+    return times
+
+if __name__ == '__main__':
+    print(get_each_month("2020-01", "2020-12"))

+ 42 - 0
MyUtils/HttpUtil.py

@@ -0,0 +1,42 @@
+# coding=utf-8
+import sys
+
+if (sys.version_info.major == 3):
+    from urllib import parse
+    import urllib.request as urllib2
+else:
+    import urllib2
+
+
+class HttpUtil(object):
+    #post方法获取数据  application/json
+    @staticmethod
+    def post(url, postData):  #
+        req = urllib2.Request(url, data=postData.encode('utf-8'),
+                              headers={'Content-Type': 'application/json;charset=UTF-8'})
+        res = urllib2.urlopen(req, timeout=60).read().decode("utf-8")
+        return res
+
+    #post方法获取数据  application/x-www-form-urlencoded
+    @staticmethod
+    def postText(url, postData):
+        req = urllib2.Request(url, data=postData.encode('utf-8'),
+                              headers={'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'})
+        res = urllib2.urlopen(req, timeout=60).read().decode("utf-8")
+        return res
+
+    #get方法获取数据  text/xml
+    @staticmethod
+    def get(url, getData, isquote):
+        if isquote:
+            getData = parse.quote(getData)
+        req = urllib2.Request((url + getData), headers={'Content-Type': 'text/xml;charset=UTF-8'})
+        res = urllib2.urlopen(req, timeout=60)
+        req = res.read()
+        return req.decode()
+
+
+# if __name__ == '__main__':
+    # httputil = HttpUtil()
+    # httputil.postText()
+    # HttpUtil.postText()

+ 53 - 0
MyUtils/MetadataWebUtil.py

@@ -0,0 +1,53 @@
+import json
+from MyUtils.HttpUtil import *
+
+
+class MetadataWebUtil(object):
+    def __init__(self, url):
+        self.url = url
+
+    def get_hbase(self, params):
+        params = json.dumps(params)
+        word = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.persagy.com/" xmlns:ent="http://entity.persagy.com">' \
+               '<soapenv:Header/>' \
+               '<soapenv:Body><ser:Query>' \
+               '<arg0>%s</arg0>' \
+               '</ser:Query></soapenv:Body></soapenv:Envelope>' % (params)
+        res = HttpUtil.post(self.url, word)
+        res = res.split("<return>")[1].split("</return>")[0]
+        res = json.loads(res.replace("&#xd;", ""))
+        return res
+
+    def database_list(self):
+        params = {
+            "QueryType": "database_list"
+        }
+        res = self.get_hbase(params)
+        return res["Content"]
+
+    def table_list(self, database):
+        params = {
+            "QueryType": "table_list_strict",
+            "Database": database
+        }
+        table_list_strict = self.get_hbase(params)["Content"]
+        params = {
+            "QueryType": "table_list",
+            "Database": database
+        }
+        table_list = self.get_hbase(params)["Content"]
+        table_list = [i for i in table_list if i not in table_list_strict]
+        tables = {}
+        for table in table_list_strict:
+            childs = []
+            for i in table_list:
+                if i.startswith(table + "_"):
+                    try:
+                        word = i[len(table + "_"):]
+                        if len(word) == 4 or len(word) == 6:
+                            word = int(word)
+                            childs.append(i)
+                    except:
+                        pass
+            tables[table] = childs
+        return tables

+ 70 - 0
MyUtils/MysqlUtils.py

@@ -0,0 +1,70 @@
+import pymysql
+from dbutils.pooled_db import PooledDB
+
+
+class MysqlUtils():
+    # 连接池对象
+    __pool = None
+    def __init__(self,**config):
+        self.host = config["host"]
+        self.port = int(config["port"])
+        self.user = config["user"]
+        self.passwd = config["passwd"]
+        self.database = None
+        if "database" in config:
+            self.database = config["database"]
+        # self.pool = self.get_conn()
+        self.pool = None
+
+    def get_conn(self):
+        if MysqlUtils.__pool is None:
+            __pool = PooledDB(pymysql, mincached=1, maxcached=5, maxconnections=5,
+                              host=self.host, port=self.port, user=self.user, passwd=self.passwd,
+                              database=self.database,
+                               use_unicode=False, blocking=False, charset="utf8")
+            self.pool = __pool
+
+
+    def query(self,sql):
+        con = None
+        cur = None
+        try:
+            con = self.pool.connection()
+            cur = con.cursor()
+            count = cur.execute(sql)
+            if count >= 0:
+                result = cur.fetchall()
+                result = [[j.decode() if isinstance(j,bytes) else j for j in i] for i in result]
+                # print(result)
+            else:
+                result = False
+            return result
+        except Exception as e:
+            print(e)
+        finally:
+            if cur:
+                cur.close()
+            if con:
+                con.close()
+
+
+    def update(self,sql):
+        con = None
+        cur = None
+        try:
+            con = self.pool.connection()
+            cur = con.cursor()
+            cur.execute(sql)
+            con.commit()
+        except Exception as e:
+            con.rollback()  # 事务回滚
+            print(e)
+        finally:
+            if cur:
+                cur.close()
+            if con:
+                con.close()
+
+    def close(self):
+        if MysqlUtils.__pool:
+            MysqlUtils.__pool.close()

+ 115 - 0
MyUtils/ZillionUtil.py

@@ -0,0 +1,115 @@
+from MyUtils.MetadataWebUtil import MetadataWebUtil
+
+
+class ZillionUtil():
+    def __init__(self, url):
+        self.metadata = MetadataWebUtil(url)
+
+    ##列出所有数据库
+    def database_list(self):
+        param = {
+            "QueryType": "database_list"
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Content"]
+
+        # TODO  其他zillion语句
+
+    ##列出所有数据库下的表(不包含分表)
+    def table_list_strict(self,table):
+        param = {
+            	"QueryType":"table_list_strict",
+	            "Database":table
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Content"]
+
+
+    ##列出所有数据库
+    # def query(self, database, table, Criteria):
+    #     param = {
+    #         "QueryType": "select",
+    #         "Database": database,
+    #         "Datatable": table,
+    #         "Criteria": Criteria
+    #     }
+    #     print(param)
+    #     databases = self.metadata.get_hbase(param)
+    #     return databases["Content"]
+
+    def select(self, database, table, Criteria):
+        param = {
+            "QueryType": "select",
+            "Database": database,
+            "Datatable": table,
+            "Criteria": Criteria
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Content"]
+
+    def table_key(self, database, table):
+        param = {
+            "QueryType": "table_detail",
+            "Database": database,
+            "Datatable": table
+        }
+        databases = self.metadata.get_hbase(param)
+        key = databases["Content"]["Key"]
+        return key
+
+
+
+    def select_count(self, database, table, Criteria):
+        param = {
+            "QueryType": "select_count",
+            "Database": database,
+            "Datatable": table,
+            "Criteria": Criteria
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+    def query_data(self, sql):
+        databases = self.metadata.get_hbase(sql)
+        return databases["Content"]
+
+    def insert(self,database,table,InsertObject):
+        param = {
+            "QueryType": "batch_insert",
+            "Database": database,
+            "Datatable": table,
+            "InsertObjects": InsertObject
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+    def remove(self,database,table,key):
+        param = {
+            "QueryType": "remove",
+            "Database": database,
+            "Datatable": table,
+            "Key": key
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+    def delete(self,database,table,Criteria):
+        param = {
+            "QueryType": "delete",
+            "Database": database,
+            "Datatable": table,
+            "Criteria": Criteria
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Count"]
+
+
+    def put(self,database,table,InsertObject):
+        param = {
+            "QueryType": "batch_put",
+            "Database": database,
+            "Datatable": table,
+            "InsertObjects": InsertObject
+        }
+        databases = self.metadata.get_hbase(param)
+        return databases["Result"]

+ 6 - 0
config.xml

@@ -0,0 +1,6 @@
+<root>
+
+    <!-- database:数据源位置  -->
+    <metadata database="physical_world_v3" url="http://192.168.100.29:7777/metadata-web/services/Service1_WS?wsdl" />
+    <cmd sourcepath="D:\develop\物理世界数据导出" targetpath="D:\develop\physical_world_v3_226\3301100002"/>
+</root>

+ 4 - 0
requirements.txt

@@ -0,0 +1,4 @@
+pymysql==1.0.2
+pytz==2021.1
+python-dateutil==2.8.1
+dbutils==2.0.2

+ 98 - 0
start.py

@@ -0,0 +1,98 @@
+#!/usr/bin/python3
+# -*- coding: utf-8 -*-
+import json
+from MyUtils.DateUtils import *
+from MyUtils.ConfigUtils import ConfigUtils
+from MyUtils.ZillionUtil import ZillionUtil
+import os,time,datetime
+
+#插入hbase
+def put_hbase(hbasedatabase,hbasetable,datas):
+    for i in range(0, len(datas), 1000):
+        dataranges = datas[i:i + 1000]
+        zillionUtil.put(hbasedatabase, hbasetable, dataranges)
+#删除hbase数据
+def remove_hbase(hbasedatabase,hbasetable,key):
+    zillionUtil.remove(hbasedatabase, hbasetable, key)
+
+#删除hbase数据
+def delete_hbase(hbasedatabase,hbasetable):
+    Criteria = {"project_id":"3301100002"}
+    zillionUtil.delete(hbasedatabase, hbasetable, Criteria)
+
+#获取表主键
+def get_hbase_key(hbasedatabase, hbasetable):
+    keys = zillionUtil.table_key(hbasedatabase, hbasetable)
+    return keys
+
+
+datetimenow = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+datetimenow_strp = datetime.datetime.strptime(datetimenow,"%Y-%m-%d %H:%M:%S")
+print(type(datetimenow_strp),datetimenow_strp)
+
+config = ConfigUtils("config.xml")
+url, hbasedatabase = config.readTop("metadata", ["url", "database"])
+sourcepath, targetpath = config.readTop("cmd", ["sourcepath", "targetpath"])
+
+#连接hbase
+zillionUtil = ZillionUtil(url)
+
+# #切换到输出目录,清空文件
+# os.chdir(targetpath)
+# os.system("rm -rf *")
+
+#切换到java程序工作目录,执行导出数据程序
+os.chdir(sourcepath)
+print("进入%s目录,开始执行java程序"%os.getcwd())
+cmd = "java -jar -Dfile.encoding=UTF-8 data-migration.jar"
+status = os.system(cmd)
+#如果程序执行成功
+if status == 0:
+    print("导出程序执行成功")
+    #切换到输出目录,判断文件是否是最新文件
+    os.chdir(targetpath)
+    print("进入%s目录,检查文件并写入hbase"%os.getcwd())
+    list = os.listdir(os.getcwd())
+    for file in list:
+        #linux 导出程序bug,需要处理下文件名称
+        # print(i)
+        # file = i.lstrip("\\")
+        # cmd_mv = "mv \%s %s"%(i,file)
+        # print(cmd_mv)
+        # os.system(cmd_mv)
+        updatetime = os.path.getmtime(file) #查询文件修改时间
+        timeArray = time.localtime(updatetime)
+        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
+        otherStyleTime_strp = datetime.datetime.strptime(otherStyleTime,"%Y-%m-%d %H:%M:%S")
+        detal_time = (otherStyleTime_strp - datetimenow_strp).total_seconds()
+        print("%s文件最新修改时间:%s"%(file,otherStyleTime))
+        hbasetable = file.split(".")[0]
+        if int(detal_time) < 10000:
+            with open(file,"r",encoding = 'utf-8') as fp:
+                print(fp.name)
+                if file == "rel_btw_objs.json":
+                    datas_rel = []
+                    for line in fp.readlines():
+                        data = json.loads(line)
+                        datas_rel.append(data)
+                    print("删除%s"%fp.name)
+                    delete_hbase(hbasedatabase,hbasetable)
+                    put_hbase(hbasedatabase, hbasetable, datas_rel)
+                else:
+                    keys = get_hbase_key(hbasedatabase, hbasetable)
+                    datas = []
+                    for line in fp.readlines():
+                        data = json.loads(line)
+                        hbase_key = {}
+                        for key in keys:
+                            if key in data:
+                                hbase_key[key] = data[key]
+                        datas.append(data)
+                        remove_hbase(hbasedatabase,hbasetable,hbase_key)
+                    time.sleep(0.1)
+                    put_hbase(hbasedatabase,hbasetable,datas)
+            print("%s写入完成"%hbasetable)
+        else:
+            print("检查%s导出文件数据,可能不是最新数据"%file)
+else:
+    print("执行java程序失败")