Spaces:
Sleeping
Sleeping
File size: 21,658 Bytes
e433a21 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
import sqlite3
import requests
import sqlite3
import hashlib
def fetch_data_from_api(code,local_body_type_code):
url = f'https://lgdirectory.gov.in/webservices/lgdws/localBodyList?stateCode={code}&localbodyTypeCode={local_body_type_code}'
payload = {}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code == 200:
data = response.json()
return data
else:
print("Failed to fetch data from the API.")
return None
def calculate_hash(data):
hash_object = hashlib.sha256(str(data).encode())
return hash_object.hexdigest()
def get_level_code(tablename):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Execute the SQL query
query = f"SELECT entityLGDCode FROM {tablename}"
cursor.execute(query)
# Fetch all the rows from the query result
rows = cursor.fetchall()
# Extract the entityLGDCode values into a Python list
result = [row[0] for row in rows]
# Close the cursor and connection
cursor.close()
# Print the final result
return result
def check_and_update_data():
#url = 'https://lgdirectory.gov.in/webservices/lgdws/villageListWithHierarchy?subDistrictCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/subdistrictList?districtCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/districtList?stateCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/blockList?districtCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/getBlockwiseMappedGP?blockCode='
try:
result = get_level_code("states")
for code in result:
print(code)
for local_body_type_code in range(30):
try:
data = fetch_data_from_api(str(code), local_body_type_code)
if data:
data_hash = calculate_hash(data)
insert_local_body_data_in_database(data, data_hash, code)
else:
print("Failed to fetch data from the API.")
except Exception as e:
print("An error occurred:", str(e))
except Exception as e:
print("An error occurred:", str(e))
def insert_district_data_in_database(data,data_hash, code):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Create a table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS district (
entityLGDCode INTEGER PRIMARY KEY,
census2001Code TEXT,
census2011Code TEXT,
entityName TEXT,
levelCode INTEGER,
levelName TEXT,
entityNameVariants TEXT,
entityParent TEXT,
dataHash TEXT
)''')
try:
# Start a transaction
conn.execute("BEGIN TRANSACTION")
# Insert the data into the table
for item in data:
entity_lgd_code = item['districtCode']
census_2001_code = item['census2001Code']
census_2011_code = item['census2011Code']
entity_name = item['districtNameEnglish']
level_code = 2
level_name = "District"
entity_name_variants = item['districtNameLocal']
entity_parent = code
cursor.execute('''INSERT INTO district (
entityLGDCode, census2001Code, census2011Code, entityName,
levelCode, levelName, entityNameVariants, entityParent,dataHash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)''',
(
entity_lgd_code, census_2001_code, census_2011_code, entity_name,
level_code, level_name, entity_name_variants, entity_parent,data_hash
))
print(f"Data for districtCode: {entity_lgd_code} inserted successfully.")
# Commit the changes
conn.execute("COMMIT")
print("All data inserted successfully.")
except Exception as e:
# Rollback the transaction in case of any error
conn.execute("ROLLBACK")
print(f"Error occurred: {str(e)}")
finally:
# Close the connection
conn.close()
import sqlite3
def insert_sub_district_data_in_database(data,datahash ,code):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Create a table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS sub_district (
entityLGDCode INTEGER PRIMARY KEY,
census2001Code TEXT,
census2011Code TEXT,
entityName TEXT,
levelCode INTEGER,
levelName TEXT,
entityNameVariants TEXT,
entityParent TEXT,
dataHash TEXT
)''')
try:
# Start a transaction
conn.execute("BEGIN TRANSACTION")
# Insert the data into the table
for item in data:
entity_lgd_code = item['subdistrictCode']
census_2001_code = item['census2001Code']
census_2011_code = item['census2011Code']
entity_name = item['subdistrictNameEnglish']
level_code = 3
level_name = "sub_district"
entity_name_variants = item['subdistrictNameLocal']
entity_parent = code
cursor.execute('''INSERT INTO sub_district (
entityLGDCode, census2001Code, census2011Code, entityName,
levelCode, levelName, entityNameVariants, entityParent, dataHash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)''',
(
entity_lgd_code, census_2001_code, census_2011_code, entity_name,
level_code, level_name, entity_name_variants, entity_parent,datahash
))
print(f"Data for subdistrictCode: {entity_lgd_code} inserted successfully.")
# Commit the changes
conn.execute("COMMIT")
print("All data inserted successfully.")
except Exception as e:
# Rollback the transaction in case of any error
conn.execute("ROLLBACK")
print(f"Error occurred: {str(e)}")
finally:
# Close the connection
conn.close()
import sqlite3
def insert_block_data_in_database(data,datahash ,code):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Create a table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS block (
entityLGDCode INTEGER PRIMARY KEY,
entityName TEXT,
levelCode INTEGER,
levelName TEXT,
entityNameVariants TEXT,
entityParent TEXT,
dataHash TEXT
)''')
try:
# Start a transaction
conn.execute("BEGIN TRANSACTION")
# Insert the data into the table
for item in data:
entity_lgd_code = item['blockCode']
entity_name = item['blockNameEnglish']
level_code = 4
level_name = "block"
entity_name_variants = item['blockNameLocal']
entity_parent = code
cursor.execute('''INSERT INTO block (
entityLGDCode, entityName,
levelCode, levelName, entityNameVariants, entityParent, dataHash
) VALUES (?, ?, ?, ?, ?, ?, ?)''',
(
entity_lgd_code, entity_name,
level_code, level_name, entity_name_variants, entity_parent,datahash
))
print(f"Data for block: {entity_lgd_code} inserted successfully.")
# Commit the changes
conn.execute("COMMIT")
print("All data inserted successfully.")
except Exception as e:
# Rollback the transaction in case of any error
conn.execute("ROLLBACK")
print(f"Error occurred: {str(e)}")
finally:
# Close the connection
conn.close()
import sqlite3
import urllib3
def insert_gp_data_in_database(data, datahash, code):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Create a table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS gp (
entityLGDCode INTEGER PRIMARY KEY,
entityName TEXT,
levelCode INTEGER,
levelName TEXT,
entityNameVariants TEXT,
entityParent TEXT,
entityParentName TEXT,
dataHash TEXT
)''')
try:
# Start a transaction
conn.execute("BEGIN TRANSACTION")
# Insert the data into the table
for item in data:
entity_lgd_code = item['localBodyCode']
entity_name = item['localBodyNameEnglish']
level_code = 5
level_name = "Gram Panchayats"
entity_name_variants = item['localBodyNameLocal']
entity_parent = code
entity_parent_name = "block"
cursor.execute('''INSERT INTO gp (
entityLGDCode, entityName,
levelCode, levelName, entityNameVariants, entityParent,entityParentName, dataHash
) VALUES (?, ?, ?, ?, ?, ?, ?,?)''',
(
entity_lgd_code, entity_name,
level_code, level_name, entity_name_variants, entity_parent,entity_parent_name,datahash
))
print(f"Data for gp: {entity_lgd_code} inserted successfully.")
# Commit the changes
conn.execute("COMMIT")
print("All data inserted successfully.")
except urllib3.exceptions.TimeoutError as te:
print("Timeout error occurred while making the HTTP request.")
# Handle the timeout error here, e.g., retry the request or log the error.
except Exception as e:
# Rollback the transaction in case of any other error
conn.execute("ROLLBACK")
print(f"Error occurred: {str(e)}")
finally:
# Close the connection
conn.close()
import sqlite3
import urllib3
def insert_local_body_data_in_database(data, datahash, code):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Create a table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS local_body (
entityLGDCode INTEGER PRIMARY KEY,
entityName TEXT,
entitylocalBodyTypeName TEXT,
levelCode INTEGER,
levelName TEXT,
entityNameVariants TEXT,
entityParent TEXT,
entityParentName TEXT,
dataHash TEXT
)''')
try:
# Start a transaction
conn.execute("BEGIN TRANSACTION")
# Insert the data into the table
for item in data:
entity_lgd_code = item['localBodyCode']
entity_name = item['localBodyNameEnglish']
entity_local_body_type_name = item['localBodyTypeName']
level_code = -1
level_name = "Local Body Type Name"
entity_name_variants = item['localBodyNameLocal']
entity_parent = code
entity_parent_name = "state"
cursor.execute('''INSERT INTO local_body (
entityLGDCode, entityName,entitylocalBodyTypeName,
levelCode, levelName, entityNameVariants, entityParent,entityParentName, dataHash
) VALUES (?, ?, ?, ?, ?, ?, ?,?,?)''',
(
entity_lgd_code, entity_name,entity_local_body_type_name,
level_code, level_name, entity_name_variants, entity_parent,entity_parent_name,datahash
))
print(f"Data for gp: {entity_lgd_code} inserted successfully.")
# Commit the changes
conn.execute("COMMIT")
print("All data inserted successfully.")
except urllib3.exceptions.TimeoutError as te:
print("Timeout error occurred while making the HTTP request.")
# Handle the timeout error here, e.g., retry the request or log the error.
except Exception as e:
# Rollback the transaction in case of any other error
conn.execute("ROLLBACK")
print(f"Error occurred: {str(e)}")
finally:
# Close the connection
conn.close()
import sqlite3
def store_village_data_in_database(data, data_hash):
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Create a table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS villages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stateCode INTEGER,
stateNameEnglish TEXT,
districtCode INTEGER,
districtNameEnglish TEXT,
subDistrictCode INTEGER,
subDistrictNameEnglish TEXT,
blockCode INTEGER,
blockNameEnglish TEXT,
localBodyCode INTEGER,
localBodyTypeCode INTEGER,
localBodyNameEnglish TEXT,
villageCode INTEGER,
villageNameEnglish TEXT,
villageStatus TEXT,
dataHash TEXT
)''')
try:
# Start a transaction
conn.execute("BEGIN TRANSACTION")
# Insert the data
for item in data:
state_code = item['stateCode']
state_name = item['stateNameEnglish']
district_code = item['districtCode']
district_name = item['districtNameEnglish']
subdistrict_code = item['subDistrictCode']
subdistrict_name = item['subDistrictNameEnglish']
block_code = item['blockCode']
block_name = item['blockNameEnglish']
local_body_code = item['localBodyCode']
local_body_type_code = item['localBodyTypeCode']
local_body_name = item['localBodyNameEnglish']
village_code = item['villageCode']
village_name = item['villageNameEnglish']
village_status = item['villageStatus']
# Insert a new row
cursor.execute('''INSERT INTO villages (
stateCode, stateNameEnglish, districtCode, districtNameEnglish,
subDistrictCode, subDistrictNameEnglish, blockCode, blockNameEnglish,
localBodyCode, localBodyTypeCode, localBodyNameEnglish,
villageCode, villageNameEnglish, villageStatus, dataHash
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)''',
(
state_code, state_name, district_code, district_name,
subdistrict_code, subdistrict_name, block_code, block_name,
local_body_code, local_body_type_code, local_body_name,
village_code, village_name, village_status, data_hash
))
print(f"Data for stateCode: {state_code}, villageCode: {village_code} inserted successfully.")
# Commit the changes
conn.execute("COMMIT")
print("All data inserted successfully.")
except Exception as e:
# Rollback the transaction in case of any error
conn.execute("ROLLBACK")
print(f"Error occurred: {str(e)}")
finally:
# Close the connection
conn.close()
def check_write_and_update_data(data,table_name):
try:
data = data
if data:
conn = sqlite3.connect('lgd_database.db')
cursor = conn.cursor()
# Retrieve the stored data from the database
cursor.execute(f'SELECT entityLGDCode, entityName FROM {table_name}')
rows = cursor.fetchall()
changed_rows = set()
for item in data:
if table_name == 'states':
entity_lgd_code = item['stateCode']
entity_name = item['stateNameEnglish']
elif table_name == 'district':
entity_lgd_code = item['districtCode']
entity_name = item['districtNameEnglish']
elif table_name == 'sub_district':
entity_lgd_code = item['subdistrictCode']
entity_name = item['subdistrictNameEnglish']
elif table_name == 'block':
entity_lgd_code = item['blockCode']
entity_name = item['blockNameEnglish']
elif table_name == 'gp':
entity_lgd_code = item['localBodyCode']
entity_name = item['localBodyNameEnglish']
""" elif table_name == 'villages':
entity_lgd_code = item['localBodyCode']
entity_name = item['localBodyNameEnglish'] """
# Find the matching row in the database
matching_rows = [row for row in rows if row[0] == entity_lgd_code]
if matching_rows:
# Check if entityLGDCode and entityName have changed
row = matching_rows[0]
if row[0] != entity_lgd_code or row[1] != entity_name:
changed_rows.add((entity_lgd_code, entity_name))
if changed_rows:
print("The following rows have changed:")
for row in changed_rows:
entity_lgd_code, entity_name = row
print("entityLGDCode:", entity_lgd_code)
print("entityName:", entity_name)
print()
# Update the values in the database
cursor.execute(f"UPDATE {table_name} SET entityName = ? WHERE entityLGDCode = ?", (entity_name, entity_lgd_code))
conn.commit()
print("Data updated successfully!")
else:
print("Data has not changed.")
# Update the data hash in the database
conn.close()
else:
print("Failed to fetch data from the API.")
except Exception as e:
print("An error occurred:", str(e))
def fetch_data_from_api_update(url):
payload = {}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code == 200:
data = response.json()
return data
else:
print("Failed to fetch data from the API.")
return None
def update_all_data():
#url = 'https://lgdirectory.gov.in/webservices/lgdws/villageListWithHierarchy?subDistrictCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/subdistrictList?districtCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/districtList?stateCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/blockList?districtCode='
#url = 'https://lgdirectory.gov.in/webservices/lgdws/getBlockwiseMappedGP?blockCode='
name_pair = {'district':'states','sub_district':'district','block':'district','gp':'block'}
for key, value in name_pair.items():
table_name = key
print('table name:', table_name)
try:
result = get_level_code(value)
for code in result:
try:
if table_name == 'states':
url = f'https://lgdirectory.gov.in/webservices/lgdws/stateList'
elif table_name == 'district':
url = f'https://lgdirectory.gov.in/webservices/lgdws/districtList?stateCode={code}'
elif table_name == 'sub_district':
url = f'https://lgdirectory.gov.in/webservices/lgdws/subdistrictList?districtCode={code}'
elif table_name == 'block':
url = f'https://lgdirectory.gov.in/webservices/lgdws/blockList?districtCode={code}'
elif table_name == 'gp':
url = f'https://lgdirectory.gov.in/webservices/lgdws/getBlockwiseMappedGP?blockCode={code}'
data = fetch_data_from_api_update(url)
if data:
check_write_and_update_data(data,table_name)
else:
print("Failed to fetch data from the API.")
except Exception as e:
print("An error occurred:", str(e))
except Exception as e:
print("An error occurred:", str(e)) |