-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_city.py
53 lines (46 loc) · 1.43 KB
/
create_city.py
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
#!/usr/bin/python3
"""
Author: Konstantinos Liosis
File: create_city.py
Desc: City creation
"""
import geopy.geocoders
from geopy.geocoders import Nominatim
import certifi
import ssl
ctx = ssl.create_default_context(cafile=certifi.where())
geopy.geocoders.options.default_ssl_context = ctx
geolocator = Nominatim(scheme="http")
def city(latitude, longitude, cursor, db_conn, ALTITUDE, country_id, geo_id, force=None):
if not force:
try:
city = geolocator.reverse(','.join([str(latitude), str(longitude)]), language='en', timeout=3)
if "address" in city.raw and "city" in city.raw["address"]:
city = city.raw["address"]["city"]
else:
city = "Undefined"
except Exception as e:
print(e)
return None
else:
city = force
# Create a city record, if it does not exist
city_id = None
try:
cursor.execute("SELECT ct_uid FROM city WHERE name = %s", [city])
city_id = cursor.fetchall()
if len(city_id) != 0:
city_id = city_id[0][0]
else:
pass
except Exception as e:
print(e)
if not city_id:
try:
query = "INSERT INTO city(name, geol_uid)" \
"VALUES (%s, %s)"
args = [city, geo_id]
cursor.execute(query, args)
except Exception as e:
print(e)
db_conn.commit()