I am creating a program where the user selects a city from a drop down menu in data.py* and it prints out data for that city. After the user selects the city, it goes into a getJson function in backend.py* that takes the user's selected city as an argument. The getJson function extracts data from a SQLite3 table and returns a json string which is a list containing a dictionary with the city as the key and the data as the values. After I got the code in getJson function to work in it's own module, by hard coding the city argument, it prints out the correct json string output. However, when I try running getJson from the menu module, it prints out the correct user inputed city but an empty list with no dictionary when I try to run getJson through that UI module.
Here is my code for creating the SQLite3 table and the getJson function in the backend module:
class Backend:
def sql(self):``
self.cur.execute(
'CREATE TABLE IF NOT EXISTS C(City TEXT, Year TEXT, Value TEXT)')
for record in self.cities:
self.cur.execute(
'''INSERT INTO C (City, Year, Value) VALUES (?, ?, ?)''',
(record[0], record[1], record[2]))
def getJson(self, userInput):
self.cur = self.conn.cursor()
self.cur.execute("""SELECT * FROM C WHERE City='%s'""" % userInput)
records = self.cur.fetchall()
#self.cur.execute("DELETE FROM C")^^^this line
with open('Cities.json', 'w') as fh:
city_as_dict = [{'City': city[0], 'Year': city[1], 'Value': city[2]} for city in records]
json.dump(city_as_dict, fh, indent=3)
with open('Cities.json', 'r') as fh:
self.json_string = json.load(fh)
fh.close()
print(self.json_string)
return self.json_string
And here is the code for the menu and function that takes user's input in the data module:
from backend import Backend
class UI:
def __init__(self):
self.b = Backend()
self.OPTIONS =self.b.cities
self.master = Tk()
self.variable = StringVar(self.master)
self.variable.set(self.OPTIONS[0])
self.city = ""
w = OptionMenu(self.master, self.variable, *self.OPTIONS)
w.pack()
button = Button(self.master, text="OK", command=self.ok)
button.pack()
def ok(self):
self.city = self.variable.get()
print(self.city)
self.b.getJson(self.city)
Ex Output When Running backend.py With Hardcoded City:
[{Chicago: 2015, 100}, {Chicago: 2016, 200}, {Chicago: 2017, 300}]
Ex Output When Running data.py With Chicago Selected From Menu:
Chicago
[]
Also an error I get is, when I run backend.py with (self.cur.execute("DELETE FROM C")) this line of code, it works perfectly fine, but when I run from data.py, it gives a database is locked error. I'm guessing most of my mistakes are some sort of syntax mistake, but I cannot seem to figure out what part is wrong with my code. Any feedback or corrections would be really helpful. Thanks guys!!