Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -167,4 +167,5 @@ poetry.toml


# End of https://www.toptal.com/developers/gitignore/api/python
main.py
main.py
*/.json
14 changes: 14 additions & 0 deletions Json/Query.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import json


def convertJson(cursor):
jsonData = []
rows = [item for item in cursor]
cols = [item[0] for item in cursor.description]
for row in rows:
data = {}
for index, value in zip(cols, row):
data[index] = value
jsonData.append(data)
encodedData = json.dumps(jsonData, ensure_ascii=False)
return encodedData
19 changes: 9 additions & 10 deletions dal/dao.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import sqlite3
import os

'''
Connecting with database
'''


class Database:
def __init__(self, path):
self.databasePath = path

def makeConnection(self):
return sqlite3.connect(f"{self.databasePath}")
def databaseConnection():
dirname = os.path.dirname(__file__)
file_name = os.path.join(dirname, '..', 'database', 'hawqalDB.sqlite')
with open(file_name, 'r', encoding="utf-8"):
database = sqlite3.connect(file_name)
cursor = database.cursor()
cursor.execute("pragma encoding")
return cursor
10 changes: 9 additions & 1 deletion hawqal/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
from hawqal.cities import City
from hawqal.country import Country
from hawqal.states import States
from .filters.state_filter import StateFilter
from .filters.city_filter import CityFilter
from .filters.country_filter import CountryFilter


getCities = City.getCities
getCity = City.getCity
getCountries = Country.getCountries
getCountry = Country.getCountry
getStates = States.getStates
getState = States.getState

__all__ = [getCities, getCountries, getStates]
__all__ = [getCountries, getStates,
getState, StateFilter, CountryFilter, getCountry, getCities, CityFilter, getCity]
174 changes: 122 additions & 52 deletions hawqal/cities.py
Original file line number Diff line number Diff line change
@@ -1,66 +1,136 @@
from dal.dao import Database
from filter.filter import Filter
from dal.dao import databaseConnection
import string
import os
import json
from .filters.city_filter import CityFilter
from Json.Query import convertJson


class City:

@staticmethod
def getCities(country="", state="", meta={}):
def getCities(country_name="", state_name="", filter=CityFilter()):
"""
1. Countries function takes two parameters as input country name and filters.\n
2. By default, function will return countries name.\n
3. Additional fields are included in filter.\n
4. From filter of boolean TRUE fields will be included in output
e.g
{
"coordinates": True,
"country": True,
"state":True
}
Description:\n
getCities function returns data of cities w.r.t to country or state in JSON format
Default: \n
By default it will return all the cities with all the fields including\n
- city_id\n
- country_name\n
- city_name\n
- state_id\n
- state_name\n
- latitude\n
- longitude\n
Args:\n
country_name (str): Optional : To get the cities of some specific country.\n
state_name (str): Optional : To get the cities of some specific state.\n
filters (CityFilter): Optional : A class object specifying which fields to include in the results.\n
Returns:\n
list: A json object containing the requested information about the cities.\n
Example: \n
- To get all cities
```
hawqal.getCities()
```\n
- To get all cities of some country
```
hawqal.getCities(country_name="Pakistan")
```\n
- To get all cities of some state in a country
```
hawqal.getCities(country_name="Pakistan",state_name="Punjab")
```\n
- To apply filters and exclude state_name
```
hawqal.getCities(filter=hawqal.CityFilter(state_name=False))
```
"""
file_name = os.path.join(
os.path.dirname(__file__), '..', 'database', 'hawqalDB.sqlite')
cursor = databaseConnection()
query = "SELECT "
if len(str(filter)) != 0:
query = query + str(filter) + " FROM cities"
else:
query = query + " * FROM cities"

with open(file_name, 'r', encoding="utf8") as db:
database = Database(file_name).makeConnection()
cursor = database.cursor()
if country_name != "" and state_name != "":
query = query + \
f" WHERE country_name = '{string.capwords(country_name)}' AND state_name = '{string.capwords(state_name)}'"
elif country_name != "":
query = query + \
f" WHERE country_name = '{string.capwords(country_name)}'"
elif state_name != "":
query = query + \
f" WHERE state_name = '{string.capwords(state_name)}'"

if state == "" and country == "" and len(meta) == 0:
data = cursor.execute(
f"SELECT city_name FROM cities ORDER BY city_name")
cities = [city[0] for city in data]
return cities
elif country != "" and type(country) != type({}) and state == "" and len(meta) == 0:
data = cursor.execute(
f"SELECT city_name FROM cities WHERE (country_name='{string.capwords(country)}' OR state_name='{string.capwords(country)}') ORDER BY city_name")
return [city[0] for city in data]
cursor.execute(query)

elif (type(country) == type({}) and state == "" and len(meta) == 0):
selectedFields = Filter.CityFilters(country)
if len(selectedFields) != 0:
data = cursor.execute(
f"SELECT city_name,{selectedFields} FROM cities ORDER BY city_name")
return [list(city) for city in list(data)]
else:
data = cursor.execute(
f"SELECT city_name FROM cities ORDER BY city_name")
return [city[0] for city in list(data)]
return convertJson(cursor)

elif country != "" and type(state) == type({}) and len(meta) == 0:
selectedFields = Filter.CityFilters(state)
if len(selectedFields) != 0:
data = cursor.execute(
f"SELECT city_name,{selectedFields} FROM cities WHERE (country_name='{string.capwords(country)}' OR state_name='{string.capwords(country)}') ORDER BY city_name")
return [list(city) for city in list(data)]
else:
data = cursor.execute(
f"SELECT city_name FROM cities WHERE (country_name='{string.capwords(country)}' OR state_name='{string.capwords(country)}') ORDER BY city_name")
return [city[0] for city in data]
@staticmethod
def getCity(country_name="", state_name="", city_name="", filter=CityFilter()):
"""
Description:\n
getCity function returns data of a single city JSON format
Default: \n
By default it will return data of a city if we provide that in the function with all the field
including\n
- city_id\n
- country_name\n
- city_name\n
- state_id\n
- state_name\n
- latitude\n
- longitude\n
Args:\n
country_name (str): Optional : To get the cities of some specific country.\n
state_name (str): Optional : To get the cities of some specific state.\n
city_name (str): Required : To get the city.\n
filters (CityFilter): Optional : A class object specifying which fields to include in the results.\n
Returns:\n
list: A JSON object containing the requested information about the cities.\n
Example: \n
- To get single city with all the filters
```
hawqal.getCity(city_name="wah")
```\n
- To get city of specific country
```
hawqal.getCity(country_name="Pakistan",city_name="wah")
```\n
- To get city of specific state
```
hawqal.getCity(state_name="punjab",city_name="wah")
```\n
- To get city of specific state and country
```
hawqal.getCity(country_name="pakistan",state_name="punjab",city_name="wah")
```\n
- To apply filters and exclude longitude
```
hawqal.getCity(country_name="pakistan",state_name="punjab",city_name="wah",filter=hawqal.CityFilter(longitude=False))
```
"""
cursor = databaseConnection()
if city_name == "":
raise ValueError("City name must be set")
query = "SELECT "
if len(str(filter)) != 0:
query = "SELECT " + str(filter) + " FROM cities "
else:
query = query + " * FROM cities "
if country_name != "":
query = query + \
f" WHERE country_name='{string.capwords(country_name)}' AND city_name='{string.capwords(city_name)}' "
elif state_name != "":
query = query + \
f"Where state_name='{string.capwords(state_name)}' and city_name='{string.capwords(city_name)}'"
elif country_name != "" and state_name != "":
query = query + \
f"Where state_name='{string.capwords(state_name)}' and country_name='{string.capwords(country_name)} and city_name='{string.capwords(city_name)}' '"
else:
query = query + f"where city_name='{string.capwords(city_name)}'"

cursor.execute(query)

elif country != "" and state != "" and len(meta) > 0:
selectedFields = Filter.CityFilters(meta)
data = cursor.execute(
f"SELECT city_name,{selectedFields} FROM cities WHERE country_name='{string.capwords(string.capwords(country))}' AND state_name='{string.capwords(string.capwords(state))}' ORDER BY city_name")
return [list(city) for city in list(data)]
return convertJson(cursor)
Loading