how to make multiple database with sqlite - python

I want to create multiple databases but I don't know how I can make it
this is python code:
# 1 - for import data in listbox
def clear_item_list():
items.delete(0, END)
# 2 - for import data in listbox
def fill_item_list(items):
for item_ in items:
items.insert(END, item_)
# 3 - for import data in listbox
def item_list_view():
clear_item_list()
items = app.data_1.view()
fill_item_list(items)
# and that for placement data in entries
def get_selected_row_item(event):
global selected_item
if len(items.curselection()) > 0:
index = items.curselection()[0]
selected_item = items.get(index)[:]
item_name.delete(0, END)
item_name.insert(END, selected_item[1])
item_price.delete(0, END)
item_price.insert(END, selected_item[2])
items.bind("<<ListboxSelect>>", get_selected_row_item)
This code is for making a table:
"CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY , Namee VARCHAR , price INTEGER )"
I don't have any idea this is my problem or not, because when I wanna use price, type that data is string and python raise this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\manager_sign_in.py", line 44, in back_to_main_manager
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\sign.py", line 33, in back_to_main_mngr
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\main.py", line 33, in user_sign
user_screen()
NameError: name 'user_screen' is not defined
Traceback (most recent call last):
File "D:\python\WindowsProject\app\main.py", line 4, in <module>
from app.user.user_sign_in import *
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 240, in <module>
user_screen()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 236, in user_screen
item_list_view()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 55, in item_list_view
fill_item_list(items)
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 48, in fill_item_list
items.insert(END, item_)
TypeError: 'str' object cannot be interpreted as an integer
and this is input data:
(1, 'pizza', '6')
if you can help me pls say to I give you more data about that if you need

The issue is on the below function:
def fill_item_list(items): # <- items is passed argument
for item_ in items:
# "items" below is expected to be an instance of tkinter Listbox
# but it is actually the passed argument (a list object)
items.insert(END, item_)
You used same name on the passed argument as the tkinter Listbox.
Use another name for the passed argument:
def fill_item_list(data): # used "data" instead of "items"
for item_ in data:
items.insert(END, item_)

Related

PyMongo getting only the highest value of a string element

i am running a python Application with Mongo DB Backend.
For an EOS Blockchain Query i need to find out the highest Value for an Attribute called eosTimestamp (String)
I created this code:
def getLastEOSTimestampProperty(client,db):
mydb = client[db]
collection = mydb["properties"]
ensure_index(collection,[('eosTimestamp',-1)])
filter={}
project={
'eosTimestamp': 1
}
sort=list({
'eosTimestamp': -1
}.items())
result = list(client[db][collection].find(
filter=filter,
projection=project,
sort=sort
).limit(1))
maxtimestamp=result[0]['eosTimestamp']
#return(maxblocknum)
return str(maxtimestamp)
When i run this code i get the following Error Message:
Traceback (most recent call last):
File "c:\projects\UplandDB\worker.py", line 408, in <module>
print(getLastEOSTimestampProperty(client,db))
File "c:\projects\UplandDB\worker.py", line 387, in getLastEOSTimestampProperty
result = list(client[db][collection].find(
File "C:\projects\UplandDB\.venv\lib\site-packages\pymongo\database.py", line 237, in __getitem__
return Collection(self, name)
File "C:\projects\UplandDB\.venv\lib\site-packages\pymongo\collection.py", line 212, in __init__
raise TypeError("name must be an instance of str")
TypeError: name must be an instance of str
Do You have any hints what i made wrong?

Replit DB is not loading data into variables

i'm using replits database but when i try to load it in it returns an error
any ideas?
cookie = db[name]
cookiepc = db[name + "cookiepc"]
increase = db[name + "increase"]
the error is
Traceback (most recent call last):
File "main.py", line 25, in <module>
cookiepc = db[name + "cookiepc"]
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 439, in __getitem__
raw_val = self.get_raw(key)
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 479, in get_raw
raise KeyError(key)
KeyError: 'shdfgwbdhfbadwcookiepc'
According to the documentation for replit-py, a KeyError is raised when an attempt is made to read from a key that doesn't exist in the database.
You can use db.get to specify a default value for if the key doesn't exist:
print(db.get("b", "default")) # default
db["b"] = "pie"
print(db.get("b", "default")) # pie

Wolfram Alpha Application Programming Interface Not Working

code:-
import wolframalpha
wolframappid = wolframalpha.Client("XXXXXX-XXXXXXXXXX")
res = wolframappid.query('temperature in mumbai')
answer = next(res.results).text
print(answer)
result:-
Traceback (most recent call last):
File "c:/Users/Harsh/Desktop/Harsh Python Projects/Test.py", line 5, in <module>
answer = next(res.results).text
File "C:\Users\Harsh\AppData\Roaming\Python\Python36\site-packages\wolframalpha\__init__.py", line 166, in text
return next(iter(self.subpod)).plaintext
ValueError: dictionary update sequence element #0 has length 1; 2 is required
any ideas how to solve this issue? i have also tried next(res.results).plaintext but another error pops up..
code:-
import wolframalpha
wolframappid = wolframalpha.Client("XXXXXX-XXXXXXXXXX")
res = wolframappid.query('temperature in mumbai')
answer = next(res.results).plaintext
print(answer)
result:-
Traceback (most recent call last):
File "C:\Users\Harsh\AppData\Roaming\Python\Python36\site-packages\wolframalpha\__init__.py", line 86, in __getattr__
val = self[name] if name in self else self[attr_name]
KeyError: '#plaintext'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/Harsh/Desktop/Harsh Python Projects/Test.py", line 5, in <module>
answer = next(res.results).plaintext
File "C:\Users\Harsh\AppData\Roaming\Python\Python36\site-packages\wolframalpha\__init__.py", line 88, in __getattr__
raise AttributeError(name)
AttributeError: plaintext
thanks in advance...

Unable to access mongo entry by "id"

I have a Mongo Document with some fields (_id, id, name, status, etc...). I wrote a typical document in a class(like a model would do):
class mod(Document):
id=fields.IntField()
name = fields.StringField()
status=fields.StringField()
description_summary = fields.StringField()
_id = fields.ObjectIdField()
And with this model, I tried to access them:
>>> from mongoengine import *
>>> from api.models import *
>>> connect('doc')
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
I tried to fetch all the entries in the "mod" document: It Worked! I can get all the fields of all the entries (id, name, etc...)
>>> mod_ = mod.objects.all()
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
I tried to filter and return all the entries with the field "status" = "Incomplete": It works, just like before.I tried to filter other fields: it works too
>>> mod_ = mod.objects(status="Incomplete")
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
But When I try to filter with the id I don't manage to get a result:
>>> mod_ = mod.objects(id=102)
>>> mod_[0].name
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
>>> mod_[0].id
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
So I tried with mod.objects.get(id=102)
>>> mod_ = mod.objects.get(id=102)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 271, in get
raise queryset._document.DoesNotExist(msg)
api.models.DoesNotExist: mod matching query does not exist.
Mod matching query does not exist, so it doesn't recognize the id field but when I write mod_[0].id I do have a result, so what can be wrong?
EDIT: I believe that when writing mod.objects(id=102), the field id is interpreted as the _id. How can I specify, I want to query by id and not _id? My Document is already written, so I cannot change the name of the fields.
So, the problem does not come from the difference between _id and id, like said #HourGlass. The values of the id field were stored as integer, I wrote fields.IntField() for the id field, and called mod.objects(id=102) (without quotes).
But for some reason, I have to write them as fields.StringField(), and call mod.objects(id='102').

Getting function containing a line in Python

I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?
There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:
import re
def get_function_name(module, line):
module_file = module.replace('.', '/') + '.py'
lines = open(module_file, 'r').xreadlines()
i = line - 1
try:
while i:
tmp = next(lines)
i -= 1
except StopIteration:
raise EOFError('Not enought lines in module %s' % module)
function_line = next(lines)
function_name = re.match('def (\w+)\([^)]*\):', function_line)
if function_name:
return function_name.group(1)
raise ValueError('No function declared on line %s' % line)
This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an Error. E.g.:
>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module

Categories