house_land.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. """不动产土地数据处理
  2. """
  3. # 导入必要的库
  4. import re # 用于正则表达式处理
  5. from datetime import datetime # 用于日期时间操作
  6. from dateutil.relativedelta import relativedelta # 用于相对日期计算
  7. from loguru import logger # 日志记录工具
  8. import pandas as pd # 数据处理库
  9. import psycopg # PostgreSQL数据库连接库
  10. import subprocess
  11. import paramiko
  12. # 配置日志记录器,将日志写入文件a.log
  13. logger.add(sink='a.log')
  14. ssh_hostname = '172.16.107.4' # 定义远程主机地址
  15. ssh_port = 22 # 定义SSH服务的端口号
  16. ssh_username = 'app' # 定义登录远程主机的用户名
  17. ssh_password = '(l4w0ST_' # 定义登录远程主机的密码
  18. # 服务器文件夹路径
  19. remote_dir_path = '/data/history/house/land/'
  20. # 数据库连接信息
  21. db_host = "172.16.107.5" # 数据库主机地址
  22. db_port = 5432 # 数据库端口号
  23. db_username = "finance" # 数据库用户名
  24. db_password = "Finance@unicom23" # 数据库密码
  25. dbname = "financialdb" # 数据库名称
  26. conn_info = f"host='{db_host}' port={db_port} user='{db_username}' password='{db_password}' dbname='{dbname}'"
  27. # 获取当前日期,并计算上个月的第一天
  28. today = datetime.today()
  29. start_date = today - relativedelta(months=1, day=1)
  30. year_month = start_date.strftime('%Y%m')
  31. # 数据文件路径
  32. input_path = 'data.xlsx'
  33. # 输出文件路径
  34. output_path = 'output.csv'
  35. def data_process():
  36. org_map = {} # 组织机构ID到组织机构信息的映射
  37. third_org_list_map = {} # 二级组织机构ID到其三级子组织列表的映射
  38. area_map = {} # 区域ID到区域信息的映射
  39. districts_list_map = {} # 城市ID到其区县列表的映射
  40. # 连接到PostgreSQL数据库
  41. with psycopg.connect(
  42. conninfo=conn_info,
  43. row_factory=psycopg.rows.dict_row # 使用字典格式返回查询结果
  44. ) as conn:
  45. with conn.cursor() as curs:
  46. # 查询所有一级组织机构(grade=1)
  47. sql = """
  48. select * from common.organization where grade = 1
  49. """
  50. logger.info(f"sql: {sql}") # 记录SQL语句到日志
  51. curs.execute(sql)
  52. second_orgs = curs.fetchall() # 获取所有一级组织机构
  53. for x in second_orgs:
  54. third_org_list_map[x['id']] = [] # 初始化二级组织机构的三级子组织列表
  55. # 查询所有组织机构
  56. sql = """
  57. select * from common.organization
  58. """
  59. logger.info(f"sql: {sql}")
  60. curs.execute(sql)
  61. orgs = curs.fetchall()
  62. for x in orgs:
  63. if x['parent_id'] in third_org_list_map:
  64. # 如果该组织的父级是二级组织,则将其加入对应的三级子组织列表
  65. third_org_list_map[x['parent_id']].append(x)
  66. org_map[x['id']] = x # 将组织机构信息存入全局映射
  67. # 查询所有一级区域(area_grade=1)
  68. sql = """
  69. select * from common.area where area_grade = 1 order by area_id
  70. """
  71. logger.info(f"sql: {sql}")
  72. curs.execute(sql)
  73. cities = curs.fetchall() # 获取所有一级区域(城市)
  74. for x in cities:
  75. districts_list_map[x['area_id']] = [] # 初始化城市的区县列表
  76. # 查询所有区域
  77. sql = """
  78. select * from common.area
  79. """
  80. logger.info(f"sql: {sql}")
  81. curs.execute(sql)
  82. areas = curs.fetchall()
  83. for x in areas:
  84. if x['parent_id'] in districts_list_map:
  85. # 如果该区域的父级是城市,则将其加入对应城市的区县列表
  86. districts_list_map[x['parent_id']].append(x)
  87. area_map[x['area_id']] = x # 将区域信息存入全局映射
  88. # 读取Excel文件中的数据
  89. df = pd.read_excel(io=input_path)
  90. # 删除字符串字段中的空白字符
  91. df = df.map(lambda x: re.sub(r'\s+', '', x) if type(x) is str else x)
  92. # 去重:根据“土地ID”列去重,保留最后一条记录
  93. df.drop_duplicates(subset=['土地ID'], keep='last', inplace=True)
  94. # 定义函数:获取二级组织机构编码
  95. def get_area_no(x):
  96. second_unit = x['资产所属单位(二级)']
  97. third_unit = x['资产所属单位(三级)']
  98. if '长途通信传输局' == second_unit:
  99. return '-11'
  100. if '保定' in second_unit and ('雄县' in third_unit or '容城' in third_unit or '安新' in third_unit):
  101. return '782'
  102. for second_org in second_orgs:
  103. area_name = second_org['name']
  104. area_no = second_org['id']
  105. if area_name in second_unit:
  106. return area_no
  107. return '-12'
  108. # 应用函数,生成“二级组织机构编码”列
  109. df['二级组织机构编码'] = df.apply(get_area_no, axis=1)
  110. # 定义函数:获取二级组织机构名称
  111. def get_area_name(x):
  112. area_no = x['二级组织机构编码']
  113. second_org = org_map[area_no]
  114. area_name = second_org['name']
  115. return area_name
  116. # 应用函数,生成“二级组织机构名称”列
  117. df['二级组织机构名称'] = df.apply(get_area_name, axis=1)
  118. # 定义函数:获取三级组织机构编码
  119. def get_city_no(x):
  120. third_unit = x['资产所属单位(三级)']
  121. area_name = x['二级组织机构名称']
  122. area_no = x['二级组织机构编码']
  123. if area_name == '石家庄':
  124. if '矿区' in third_unit:
  125. return 'D0130185'
  126. if '井陉' in third_unit:
  127. return 'D0130121'
  128. if area_name == '秦皇岛':
  129. if '北戴河新区' in third_unit:
  130. return 'D0130185'
  131. if '北戴河' in third_unit:
  132. return 'D0130304'
  133. if area_name == '唐山':
  134. if '滦县' in third_unit:
  135. return 'D0130223'
  136. if '高新技术开发区' in third_unit:
  137. return 'D0130205'
  138. if area_name == '邢台':
  139. if '内丘' in third_unit:
  140. return 'D0130523'
  141. if '任泽' in third_unit:
  142. return 'D0130526'
  143. if area_name == '邯郸':
  144. if '峰峰' in third_unit:
  145. return 'D0130406'
  146. if area_name == '省机动局':
  147. if '沧州' in third_unit:
  148. return 'HECS180'
  149. if '唐山' in third_unit:
  150. return 'HECS181'
  151. if '秦皇岛' in third_unit:
  152. return 'HECS182'
  153. if '廊坊' in third_unit:
  154. return 'HECS183'
  155. if '张家口' in third_unit:
  156. return 'HECS184'
  157. if '邢台' in third_unit:
  158. return 'HECS185'
  159. if '邯郸' in third_unit:
  160. return 'HECS186'
  161. if '保定' in third_unit:
  162. return 'HECS187'
  163. if '石家庄' in third_unit:
  164. return 'HECS188'
  165. if '承德' in third_unit:
  166. return 'HECS189'
  167. if '衡水' in third_unit:
  168. return 'HECS720'
  169. if '雄安' in third_unit:
  170. return 'HECS728'
  171. return 'HECS018'
  172. if '雄安' == area_name:
  173. third_unit = third_unit.replace('雄安新区', '')
  174. third_org_list = third_org_list_map[area_no]
  175. for third_org in third_org_list:
  176. city_name = third_org['name']
  177. if city_name in third_unit:
  178. return third_org['id']
  179. if '沧州' == area_name:
  180. return 'D0130911'
  181. if '唐山' == area_name:
  182. return 'D0130202'
  183. if '秦皇岛' == area_name:
  184. return 'D0130302'
  185. if '廊坊' == area_name:
  186. return 'D0131000'
  187. if '张家口' == area_name:
  188. return 'D0130701'
  189. if '邢台' == area_name:
  190. return 'D0130502'
  191. if '邯郸' == area_name:
  192. return 'D0130402'
  193. if '保定' == area_name:
  194. return 'D0130601'
  195. if '石家庄' == area_name:
  196. return 'D0130186'
  197. if '承德' == area_name:
  198. return 'D0130801'
  199. if '衡水' == area_name:
  200. return 'D0133001'
  201. if '雄安' == area_name:
  202. return 'D0130830'
  203. return 'HE001'
  204. # 应用函数,生成“三级组织机构编码”列
  205. df['三级组织机构编码'] = df.apply(get_city_no, axis=1)
  206. # 定义函数:获取三级组织机构名称
  207. def get_city_name(x):
  208. city_no = x['三级组织机构编码']
  209. third_org = org_map[city_no]
  210. city_name = third_org['name']
  211. return city_name
  212. # 应用函数,生成“三级组织机构名称”列
  213. df['三级组织机构名称'] = df.apply(get_city_name, axis=1)
  214. # 定义函数:获取城市ID
  215. def get_city_id(x):
  216. address = x['标准地址']
  217. second_unit = x['资产所属单位(二级)']
  218. third_unit = x['资产所属单位(三级)']
  219. if '雄安' in address or ('保定' in address and ('雄县' in address or '容城' in address or '安新' in address)):
  220. return '133100'
  221. for city in cities:
  222. area_name = city['short_name']
  223. area_id = city['area_id']
  224. if area_name in second_unit:
  225. return area_id
  226. if area_name in third_unit:
  227. return area_id
  228. if area_name in address:
  229. return area_id
  230. return ''
  231. # 应用函数,生成“city_id”列
  232. df['city_id'] = df.apply(get_city_id, axis=1)
  233. # 定义函数:获取城市名称
  234. def get_city(x):
  235. city_id = x['city_id']
  236. area = area_map.get(city_id)
  237. if pd.notna(area):
  238. city = area['area_name']
  239. return city
  240. return ''
  241. # 应用函数,生成“city”列
  242. df['city'] = df.apply(get_city, axis=1)
  243. # 定义函数:获取区县ID
  244. def get_district_id(x):
  245. address = x['标准地址']
  246. city = x['city']
  247. city_id = x['city_id']
  248. if pd.isna(city) or pd.isna(address):
  249. return ''
  250. if city == '石家庄':
  251. if '矿区' in address:
  252. return '130107'
  253. if '井陉' in address:
  254. return '130121'
  255. if city == '唐山':
  256. if '滦县' in address:
  257. return '130284'
  258. if city == '邢台':
  259. if '内邱' in address:
  260. return '130523'
  261. if '任县' in address:
  262. return '130505'
  263. if city == '雄安':
  264. address = address.replace('雄安新区', '')
  265. districts = districts_list_map.get(city_id)
  266. if not districts:
  267. return ''
  268. for district in districts:
  269. district_name = district['short_name']
  270. if district_name in address:
  271. return district['area_id']
  272. return ''
  273. # 应用函数,生成“district_id”列
  274. df['district_id'] = df.apply(get_district_id, axis=1)
  275. # 定义函数:获取区县名称
  276. def get_district(x):
  277. district_id = x['district_id']
  278. area = area_map.get(district_id)
  279. if pd.notna(area):
  280. district = area['area_name']
  281. return district
  282. return ''
  283. # 应用函数,生成“district”列
  284. df['district'] = df.apply(get_district, axis=1)
  285. # 在DataFrame中插入“年月”列
  286. df.insert(0, '年月', year_month)
  287. # 打印DataFrame的基本信息
  288. print(df.info())
  289. # 将处理后的数据保存为CSV文件
  290. df.to_csv(
  291. path_or_buf=output_path,
  292. index=False,
  293. header=[
  294. 'year_month', 'first_unit', 'second_unit', 'third_unit', 'land_name', 'land_id', 'land_ownership',
  295. 'use_right_type', 'land_use', 'acquisition_date', 'idle_start_date', 'site_name', 'site_id',
  296. 'address', 'investor', 'management_level', 'ownership_status', 'usage_status', 'total_land_area',
  297. 'land_area_self_use', 'land_area_idle', 'land_area_rent', 'land_area_unusable', 'has_land_deed',
  298. 'no_land_deed_reason', 'land_preservation_risk', 'open_space', 'courtyard', 'unrelated_assets',
  299. 'assets_num', 'assets_tag_num', 'responsible_department', 'person_in_charge', 'lng_jt', 'lat_jt',
  300. 'property_owner', 'special_specification', 'area_no', 'area_name', 'city_no', 'city_name', 'city_id',
  301. 'city', 'district_id', 'district'
  302. ],
  303. encoding='utf-8-sig' # 确保中文字符不会乱码
  304. )
  305. def data_import():
  306. # 定义 PowerShell 脚本的路径
  307. script_path = r"../../copy.ps1"
  308. # 目标表和文件信息
  309. table = "house.land_month" # 数据库目标表名
  310. # 表字段列名,用于指定导入数据的列顺序
  311. columns = "year_month,first_unit,second_unit,third_unit,land_name,land_id,land_ownership,use_right_type,land_use,acquisition_date,idle_start_date,site_name,site_id,address,investor,management_level,ownership_status,usage_status,total_land_area,land_area_self_use,land_area_idle,land_area_rent,land_area_unusable,has_land_deed,no_land_deed_reason,land_preservation_risk,open_space,courtyard,unrelated_assets,assets_num,assets_tag_num,responsible_department,person_in_charge,lng_jt,lat_jt,property_owner,special_specification,area_no,area_name,city_no,city_name,city_id,city,district_id,district"
  312. # 构造执行 PowerShell 脚本的命令
  313. command = f"powershell -File {script_path} -db_host {db_host} -db_port {db_port} -db_username {db_username} -db_password {db_password} -dbname {dbname} -table {table} -filename {output_path} -columns {columns}"
  314. # 打印生成的命令,方便调试和日志记录
  315. logger.info("command: {}", command)
  316. # 使用 subprocess 模块运行 PowerShell 命令,并捕获输出
  317. completed_process = subprocess.run(
  318. command, # 执行的命令
  319. check=False, # 如果命令执行失败,不抛出异常
  320. text=True, # 将输出作为字符串处理
  321. capture_output=True, # 捕获标准输出和标准错误
  322. )
  323. # 打印命令执行的结果,包括返回码、标准输出和标准错误
  324. logger.info("导入结果:\n{}\n{}\n{}", completed_process.returncode, completed_process.stdout,
  325. completed_process.stderr)
  326. # 定义正则表达式,用于匹配标准输出中的 COPY 结果
  327. p = re.compile(r"^(COPY) (\d+)$")
  328. count = None # 初始化计数变量
  329. matcher = p.match(completed_process.stdout) # 匹配标准输出中的 COPY 结果
  330. if matcher:
  331. count = int(matcher.group(2)) # 提取导入的数据行数
  332. # 如果没有成功提取到导入数据的行数,抛出运行时异常
  333. if count is None:
  334. raise RuntimeError("导入数据失败")
  335. def upload_file():
  336. remote_path = f'{remote_dir_path}{year_month}.xlsx' # 定义远程主机的目标文件路径
  337. # 使用paramiko.SSHClient创建一个SSH客户端对象,并通过with语句管理其上下文
  338. with paramiko.SSHClient() as ssh:
  339. # 设置自动添加主机密钥策略,避免因未知主机密钥导致连接失败
  340. ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  341. # 连接到远程主机,传入主机地址、端口、用户名和密码
  342. ssh.connect(ssh_hostname, port=ssh_port, username=ssh_username, password=ssh_password)
  343. # 执行远程命令,创建远程目录(如果不存在)
  344. ssh.exec_command(f'mkdir -p {remote_dir_path}')
  345. # 打开SFTP会话,用于文件传输,并通过with语句管理其上下文
  346. with ssh.open_sftp() as sftp:
  347. # 记录日志,提示即将上传的本地文件和远程目标路径
  348. logger.info("upload {} to {}", input_path, remote_path)
  349. # 使用SFTP的put方法将本地文件上传到远程主机
  350. sftp.put(input_path, remote_path)
  351. # 记录日志,提示文件已成功上传
  352. logger.info("uploaded {}", input_path)
  353. def data_update():
  354. with psycopg.connect(
  355. conninfo=conn_info,
  356. ) as conn:
  357. with conn.cursor() as curs:
  358. # 更新局址编号
  359. sql = f"""
  360. update
  361. house.land_month a
  362. set
  363. site_num = b.site_num
  364. from
  365. house.site_month b
  366. where
  367. a.site_id = b.site_id
  368. and a.year_month = b.year_month
  369. and a.year_month = {year_month}
  370. """
  371. logger.info(f"sql: {sql}")
  372. curs.execute(sql)
  373. logger.info(f"update {curs.rowcount}")
  374. data_process()
  375. data_import()
  376. upload_file()
  377. data_update()