Closed aum7 closed 6 months ago
ok, i tried to hire sherlock holmes, he is too busy, so i opted to chatgpt below is a working example code
import sys
from dataclasses import dataclass
from pycities import RowFactoryModelConfig, CityDatabase, dict_factory
# we need location / name & country
name = "paris"
country = "france"
@dataclass(frozen=True)
class City:
id: int
name: str
country_name: str
latitude: str
longitude: str
timezone: str
def __str__(self):
return f" {self.id}, {self.name}, {self.country_name}, {self.latitude}, {self.longitude}, {self.timezone}"
# create row factory for your custom model
def city_factory(cursor, row) -> City:
return City(**dict_factory(cursor, row))
# set your factory config for custom model
RowFactoryModelConfig.set(City, city_factory)
# create new instance with our model; fetch wanted fields
db = CityDatabase[City](
fetch_fields=(
"id",
"name",
"country_name",
"latitude",
"longitude",
"timezone",
)
)
# connect to database
try:
db.connect()
result = db.search(query=name, lang="en", limit=5)
# print("result type : " + str(type(result)) + "\n") # > list
for res in result:
if name.lower() != res.name.lower():
continue
if country.lower() != res.country_name.lower():
continue
print(f"res.name : {res.name}")
print(f"res.country_name : {res.country_name}")
print(f"res.latitude : {res.latitude}")
print(f"res.longitude : {res.longitude}")
print(f"res.timezone : {res.timezone}")
db.close()
print("pycities: get coordinates for location - success")
except Exception as e:
print(f"exception : {str(e)}")
long live pycities
have fun
olo
thank you for sharing
i used this module as per example in docs as an average python non-professional (wanna-be) programmer, i have huge difficulties splitting the query result into simple strings
i tried .split(','), multiple for loops and other suggestions / codes from google search, failed i checked result type, got 'class main.city'
question how must i write a pycities code, so i can easily split a result like ie proper returned single city : name = result[1] longitude = result[2] country_name = result[3]
or, if multiple cities are returned : name = result[0][1] longitude = result[0][2] country_name = result[0][3]
i tested by querying 'paris', limit = 5 i got results, including 'parys', 'annapolis', 'new orleans', which makes no sense to me
so i would suggest to add parameter for exact search (matching name parameter), or to also search by ie country_name, at the same time, so wrong results are discarded before they reach users eyes & consequently brain
have fun
aum