import json import requests from config_base import * import pyodbc import requests from bs4 import BeautifulSoup from html import escape import json from decimal import Decimal import datetime import time import sys import traceback import re from config_base import * from general_functions import * cursor, cnxn = create_cursor() #Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/ class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, Decimal): return float(obj) return json.JSONEncoder.default(self, obj) query = ''' select s.ID as sectionId ,isnull(s.CAPTION,'') as title -- عنوان بخش: مثلا ماده 5 ,isnull(s.F_PARENTID,0) as parentId ,isnull(lss.CAPTION,'') as sectionStatus -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و ,isnull(lss2.CAPTION,'') as qanon_etebar -- برای کل قانون نه جزء یا ماده خاص : ... منسوخه، معتبر، اصلاحی، موقت و ,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره ,isnull(s.SECTIONLEVEL,0) as sectionLevel -- نسبت به عنوان قانون نامرتب و دارای مقدار تکراری هم هست ؟؟؟ ,isnull(nestedLawType.CAPTION,'') as lawType --,isnull(nestedLawStatus.CAPTION,'') as lawStatus ,isnull(s.TEXTORDER,0) as textOrder -- ترتیب نمایش مواد و تبصره ها ,s.STATENO as stateNo -- ??? ,isnull(s.SECTIONTYPENO,0) as sectionTypeNumber -- دوهزار رکورد با مقدار صفر دارد اما مقادیر دیگری نیز پذیرفته است ؟؟؟ -- بیش از پنج هزار رکورد با مقدار بالاتر از 1500 دارد که چنین مقادیری در جدول سکشن_تایپ وجود ندارد پس با این جدول رابطه ندارد ,isnull(l.CAPTION,'') as lawTitle -- عنوان قانون ,isnull(l.ID,0) as lawId -- شناسه قانون ,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب ,isnull(l.EXPIREDATE,'') as expireDate -- تاریخ انقضا --,isnull(s.F_LWPHASEID,0) as phaseId -- شناسه فاز ,s.FULLPATH as sectionFullPath -- عنوان ماده یا تبصره ,isnull(s.SECTIONTYPENOTEXT,'') as sectionType -- ??? استفساریه، کنوانسیون، موافقت نامه، اساسنامه، تفسیر، دوم ، سوم ، چهارم، دوازدهم، خالی، 1، 2، 3، 4 ,isnull(s.FIRSTSATENO,0) as firstStateNo -- ??? بازه 0 تا 169 ,isnull(s.LASTSTATENO,0) as lastStateNo -- ??? بازه 0 تا 112 ,isnull(s.HIERARCHY,'') as hierarchy ,isnull(s.DISPLAYINCONTENTS,0) as displayInContents -- ??? صد و پنجاه و سه رکورد دارای مقدار یک و بقیه یک میلیون رکورد مقدار 0 دارد ,isnull(s.ISINTERPRETATION,0) as isInterpretation -- ??? چهارصد و پنجاه و سه رکورد با مقدار یک دارد و بقیه مقادیر نال است ,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_TOPICID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM lwsectiontopic where [F_SECTIONID]=s.id) as topics ,l.[ISLAW] -- قانون ,l.[ISREGULATION] -- مقرره ,l.[ISCORRECTIONLETTER] -- اصلاحیه ,( SELECT top (1) p3.CAPTION FROM [lwPhase] p1 left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id where l.ID = p1.F_LWLAWID order by p2.APPROVEDATE asc ) as ts_ref -- مرجع تصویب ,( SELECT cbt.CAPTION FROM lwLaw l2 left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID where l.ID = l2.id ) as regulationType from lwSection s left join lwLawSectionStatus lss on s.F_CMBASETABLEID_SECTIONSTATUS = lss.ID left join lwLaw l on s.F_LWLAWID = l.ID left join lwLawSectionStatus lss2 on lss2.id= l.[F_CMBASETABLEID_LASTSTATUS] left JOIN ( SELECT l2.F_LWBASETABLEID_LAWTYPE,l2.ID,cbt.CAPTION FROM lwLaw l2 left JOIN cmBasetable cbt ON l2.F_LWBASETABLEID_LAWTYPE = cbt.ID ) AS nestedLawType ON s.F_LWLAWID = nestedLawType.ID left JOIN ( SELECT l2.[F_LWBASETABLEID_REGULATIONTYPE],l2.ID,cbt.CAPTION FROM lwLaw l2 left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID ) AS nestedRegulationType ON s.F_LWLAWID = nestedRegulationType.ID where l.[ISREGULATION] = 1 order by s.F_LWLAWID,textOrder ''' cursor.execute(query) url = BASE_URL + "repo/majles/rgsection/multi/add" dict_topic = json.loads(open("list_LWTopic.json").read()) headers = HEADERS bulk_count = 1 bulk_data = [] t1= datetime.datetime.now() print(t1) i = 1 while 1: # print(i) i=i+1 row = cursor.fetchone() if not row: break # if i > 1000: # break # print(row.sectionId) html = '' if isNeedHtml(row.sectionText) : html = row.sectionText try: soup = BeautifulSoup(row.sectionText, "html.parser") text = soup.get_text("\n", strip=True) # text = removeHtmlNoTableTag(row.sectionText) # خطا داره except Exception as e: text = row.sectionText text = normalYehKe(text) content_len = text.__len__() qanon_title = normalYehKe( row.lawTitle ) eid='qs'+ str(row.sectionId) parentId = '0' if row.parentId != 0 : parentId = 'qs'+ str(row.parentId) lawId='qq'+ str(row.lawId) main_type = '' if(row.ISLAW == 1): main_type = 'قانون' elif(row.ISREGULATION == 1): main_type = 'مقرره' sub_type = '' if(row.ISLAW == 1): sub_type = row.lawType elif(row.ISREGULATION == 1): sub_type = row.regulationType sub_type = normalYehKe(sub_type) # other_type = 'اصلی' # if(row.ISCORRECTIONLETTER == 1): # other_type = 'اصلاحی' ts_year = '' if row.aproveDate : items = row.aproveDate.split("/") if items.__len__() > 0: ts_year = items[0] tt = time.time() tt = int( round(tt) * 1000) version_ifo = { "timestamp": tt, "operation": "create", "number" : 1 } other_info = { "level": row.sectionLevel, "full_path": normalYehKe( row.sectionFullPath ), "number_text":row.sectionType , "hierarchy" : row.hierarchy } topics = [] if row.topics: topic_ids = row.topics.split(",") topic_list = list(set(topic_ids)) for item in topic_ids: if str(item) in dict_topic: topics.append( {'id': dict_topic[str(item)]['id'], 'title': normalYehKe(dict_topic[str(item)]['title'])} ) ts_ref = '' if(row.ts_ref): ts_ref = normalYehKe(row.ts_ref) sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی try: sort_date_timestamp = getSortTimestamp(row.aproveDate) except Exception as e: sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی expire_date = row.expireDate.strip() # state_etebar = normalYehKe(row.lawStatus) state_etebar = normalYehKe(row.sectionStatus) qanon_etebar = '' if row.qanon_etebar : qanon_etebar = row.qanon_etebar data={ 'id':eid, 'ref_id':row.sectionId, 'ref_key':'m_qavanin', 'main_type': main_type, 'sub_type': sub_type, 'content': text, 'html' : html, 'version_info': version_ifo, 'qanon_title': qanon_title, 'expire_date': expire_date, 'ts_date': row.aproveDate, 'ts_year': ts_year, 'ts_ref': ts_ref, 'state_etebar': state_etebar, 'qanon_id': lawId, 'parent_id': parentId, 'child_order': row.textOrder, 'other_info': other_info, 'content_len': content_len, 'topics': topics, 'qanon_etebar' : qanon_etebar, #'categories': row.oooo, #'tags': row.oooo, #'keywords': row.oooo, 'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp } if bulk_count > 100: print('=' * 10 ) print(str(i)+ ', id=' + eid) print(', lawid=' + lawId) if bulk_count > 0: print(', lawid_first=' + bulk_data[0]['qanon_id']) payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! response = requests.request("POST", url, headers=headers, data=payload) # print(response) bulk_data = [] bulk_count = 0 # print(response.text) #print(row.txt) bulk_data.append(data) bulk_count +=1 if bulk_count > 0: print(bulk_count) if bulk_count > 0: print(', lawid_first=' + bulk_data[0]['qanon_id']) payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! response = requests.request("POST", url, headers=headers, data=payload) cursor.close() cnxn.close() print('end success') t2= datetime.datetime.now() print(t2-t1)