Error inserting an email string in sqlite3 and python Tkinter - python-3.x

I am writing a simple program to update a basic db based on data entered on a simple GUI. I'm using string formatting but keep getting an error trying to enter an email address , which I know should be surrounded with double-quotes. I'm sure the solution is simple- I just don't know what it is!
def update_rec():
# Connect to the db
conn = sqlite3.connect("address_book.db")
# create a cursor
c = conn.cursor()
fields = ["f_name", "s_name", "mob", "email"]
# Check which textboxes have data
update_txt = ""
update_field = ""
rec_no = str(id_no.get())
if len(f_name.get()) > 0:
update_txt = f_name.get()
update_field = fields[0]
elif len(s_name.get()) > 0:
update_txt = s_name.get()
update_field = fields[1]
elif len(mob.get()) > 0:
update_txt = mob.get()
update_field = fields[2]
elif len(email.get()) > 0:
update_txt = email.get()
update_field = fields[3]
else:
update_txt = ""
update_field = ""
c.execute("""UPDATE address_book SET {0} = ? WHERE {1} = ?""".format(update_field, update_txt), rec_no)
conn.commit()
conn.close()
I keep getting this error:
c.execute("""UPDATE address_book SET {0} = ? WHERE {1} = ?""".format(update_field, update_txt), rec_no)
sqlite3.OperationalError: near "#gmail": syntax error

What needs to be supplied to .format() is getting confused with what needs to be passed to c.execute().
Do it in two steps so it's easier to understand.
You need to tell us what rec_field should be. It's probably something like id or address_book_id or ?
rec_field = 'id' # you know what this should be...
qry = """UPDATE address_book
SET {0} = ?
WHERE {1} = ?;""".format(update_field, rec_field)
c.execute(qry, (update_txt,rec_no))

Related

Choose encoding when converting to Sqlite database

I am converting Mbox files to Sqlite db. I do not arrive to encode the db file into utf-8.
The Python console displays the following message when converting to db:
Error binding parameter 1 - probably unsupported type.
When I visualize my data on DB Browser for SQlite, special characters don't appear and the � symbol shows up instead.
I first convert .text files to Mbox files with the following function:
def makeMBox(fIn,fOut):
if not os.path.exists(fIn):
return False
if os.path.exists(fOut):
return False
out = open(fOut,"w")
lineNum = 0
# detect encoding
readsource = open(fIn,'rt').__next__
#fInCodec = tokenize.detect_encoding(readsource)[0]
fInCodec = 'UTF-8'
for line in open(fIn,'rt', encoding=fInCodec, errors="replace"):
if line.find("From ") == 0:
if lineNum != 0:
out.write("\n")
lineNum +=1
line = line.replace(" at ", "#")
out.write(line)
out.close()
return True
Then, I convert to sqlite db:
for k in dates:
db = sqlite_utils.Database("Courriels_Sqlite/Echanges_Discussion.db")
mbox = mailbox.mbox("Courriels_MBox/"+k+".mbox")
def to_insert():
for message in mbox.values():
Dionyversite = dict(message.items())
Dionyversite["payload"] = message.get_payload()
yield Dionyversite
try:
db["Dionyversite"].upsert_all(to_insert(), alter = True, pk = "Message-ID")
except sql.InterfaceError as e:
print(e)
Thank you for your help.
I found how to fix it:
def to_insert():
for message in mbox.values():
Dionyversite = dict(message.items())
Dionyversite["payload"] = message.get_payload(decode = True)
yield Dionyversite
``
As you can see, I add `decode = True` inside `get_payload`of the `to_insert`function.

I have to make a code taking a name and turning it into a last name, first initial and middle initial format

I have to make a code taking a name and turning it into a last name, first initial, middle initial format. My code works assuming there is a middle name but breaks if not provided a middle name. Is there a way to ignore not having a middle name and to just default to last name and first initial? I'm super new to python3 so I'm sorry if my code is uber bad.
Heres my code :
your_name = input()
broken_name = your_name.split()
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]
middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+',',first_in+'.'+middle_in+'.' )
You can use an if else statement to check how long broken_name is.
Try:
your_name = input()
broken_name = your_name.split()
if len(broken_name) > 2:
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]
middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+', ',first_in+'. '+middle_in+'.'
else:
first_name = broken_name[0]
last_name = broken_name[1]
first_in = first_name[0]
print(last_name+', ',first_in+'.')
Another option:
def get_pretty_name_str(names):
splited_names = names.split()
last_name = splited_names.pop(-1)
result = f'{last_name},'
while splited_names:
n = splited_names.pop(0)
result += f'{n}.'
return result
print(get_pretty_name_str('First Middle Last')) # Last,First.Middle.
print(get_pretty_name_str('First Last')) # Last,First.

Validate WTF Flask Form Input Values

I have the following form in my flask app. I'd like to ensure that the input value is actually an integer and also if the value entered in token > k here k can be some number it spits an error message to the screen. The IntegerField doesn't seem to enforce integer values, e.g., if the user enters 2.3 it passes that to my function which fails because it expects an integer.
Can this type of error message happen in the form or do I need to program that inside my flask app once the value is passed from the form to the server?
class Form(FlaskForm):
token = IntegerField('Token Size', [DataRequired()], default = 2)
submit = SubmitField('Submit')
EDIT
Per the comment below, updating this with my revised Form and the route
class Form(FlaskForm):
token = IntegerField('Token Size', validators=[DataRequired(), NumberRange(min=1, max=10, message='Something')], default = 2)
ngram_method = SelectField('Method', [DataRequired()],
choices=[('sliding', 'Sliding Window Method'),
('adjacent', 'Adjacent Text Method')])
rem_stop = BooleanField('Remove Stop Words', render_kw={'checked': True})
rem_punc = BooleanField('Remove Punctuation', default = True)
text2use = SelectField('Text To Use for Word Tree', [DataRequired()],
choices=[('clean', 'Clean/Processed Text'),
('original', 'Original Text String')])
pivot_word = TextField('Pivot Word for Word Tree', [DataRequired()])
submit = SubmitField('Submit')
And the route in which the form is used
#word_analyzer.route('/text', methods=('GET', 'POST'))
def text_analysis():
form = Form()
result = '<table></table>'
ngrams = '<table></table>'
orig_text = '<table></table>'
text = ""
if request.method == 'POST':
tmp_filename = tempfile.gettempdir()+'\\input.txt'
if request.files:
txt_upload = request.files.get('text_file')
if txt_upload:
f = request.files['text_file']
f.save(tmp_filename)
if os.path.exists(tmp_filename):
file = open(tmp_filename, 'r', encoding="utf8")
theText = [line.rstrip('\n') for line in file]
theText = str(theText)
token_size = form.token.data
stops = form.rem_stop.data
punc = form.rem_punc.data
ngram_method = form.ngram_method.data
text_result = text_analyzer(theText, token_size = token_size, remove_stop = stops, remove_punctuation = punc, method = ngram_method)
result = pd.DataFrame.from_dict(text_result, orient='index', columns = ['Results'])[:-3].to_html(classes='table table-striped table-hover', header = "true", justify = "center")
ngrams = pd.DataFrame.from_dict(text_result['ngrams'], orient='index', columns = ['Frequency']).to_html(classes='table table-striped table-hover', header = "true", justify = "center")
if form.pivot_word.data == None:
top_word = json.dumps(text_result['Top Word'])
else:
top_word = json.dumps(form.pivot_word.data)
if form.text2use.data == 'original':
text = json.dumps(text_result['original_text'])
else:
text = json.dumps(text_result['clean_text'])
if form.validate_on_submit():
return render_template('text.html', results = [result], ngrams = [ngrams], form = form, text=text, top_word = top_word)
return render_template('text.html', form = form, results = [result],ngrams = [ngrams], text=text, top_word='')
Use the NumberRange validator from wtforms.validators.NumberRange. You can pass an optional Min and Max value along with the error message. More info here
Update
# Form Class
class Form(FlaskForm):
token = FloatField('Token Size', validators=[DataRequired(), NumberRange(min=1, max=10, message='Something')])
# Route
if form.validate_on_submit():
print(form.name.data)
Here is an example that should work, make sure your form class field looks similar and also that in your route you use form.validate_on_submit():.

how can I have the different max of several lists in python

I want get different max from different list but the problem i get the same max,this is my code ,why problem in this code ,i have got the same max for the first list,what i do change for obtain a result max for different list:
def best(contactList_id,ntf_DeliveredCount):
maxtForEvryDay = []
yPredMaxForDay = 0
for day in range(1,8):
for marge in range(1,5):
result = predictUsingNewSample([[contactList_id,ntf_DeliveredCount,day,marge]])
if (result > yPredMaxForDay):
yPredMaxForDay = 0
yPredMaxForDay = result
maxtForEvryDay.append(yPredMaxForDay)
return maxtForEvryDay
best(contactList_id = 13.0,ntf_DeliveredCount = 5280.0)
result:
[1669.16010381]
[1708.32915255]
[1747.49820129]
[1786.66725003]
[1570.05500351]
[1609.22405225]
[1648.39310099]
[1687.56214973]
[1491.60792629]
[1510.11895195]
[1549.28800069]
[1588.45704943]
[1402.21845533]
[1420.73953501]
[1450.18290039]
[1489.35194913]
[1367.15490803]
[1356.21411426]
[1345.27532239]
[1390.24684884]
[1378.1190426]
[1367.17824883]
[1419.23588013]
[1486.78241686]
[1450.21261674]
[1516.04342599]
[1581.87423524]
[1647.7050445]
[array([1786.66725003]),
array([1786.66725003]),
array([1786.66725003]),
array([1786.66725003]),
array([1786.66725003]),
array([1786.66725003]),
array([1786.66725003])]
this is my fonction predictUsingNewSample(X_test)
def predictUsingNewSample(X_test):
#print(X_test)
# Load from file
with open("pickle_model.pkl", 'rb') as file:
pickle_model = pickle.load(file)
Ypredict = pickle_model.predict(X_test)
print(Ypredict)
return Ypredict
Try this:
def best(contactList_id,ntf_DeliveredCount):
maxtForEvryDay = []
for day in range(1,8):
yPredMaxForDay = 0
for marge in range(1,5):
result = predictUsingNewSample([[contactList_id,ntf_DeliveredCount,day,marge]])
if (result > yPredMaxForDay):
yPredMaxForDay = result
maxtForEvryDay.append(yPredMaxForDay)
return maxtForEvryDay
best(contactList_id = 13.0,ntf_DeliveredCount = 5280.0)
I think the problem actually comes from the fact that you never clean up your yPredMaxForDay variable for each day.

PyTest: fix repeating code and remove dependencies

I am writing tests for an API with pytest.
The tests are structured like that:
KEEP_BOX_IDS = ["123abc"]
#pytest.fixture(scope="module")
def s():
UID = os.environ.get("MYAPI_UID")
if UID is None:
raise KeyError("UID not set in environment variable")
PWD = os.environ.get("MYAPI_PWD")
if PWD is None:
raise KeyError("PWD not set in environment variable")
return myapi.Session(UID, PWD)
#pytest.mark.parametrize("name,description,count", [
("Normal Box", "Normal Box Description", 1),
("ÄäÖöÜüß!§", "ÄäÖöÜüß!§", 2),
("___--_?'*#", "\n\n1738\n\n", 3),
])
def test_create_boxes(s, name, description, count):
box_info_create = s.create_box(name, description)
assert box_info_create["name"] == name
assert box_info_create["desc"] == description
box_info = s.get_box_info(box_info_create["id"])
assert box_info["name"] == name
assert box_info["desc"] == description
assert len(s.get_box_list()) == count + len(KEEP_BOX_IDS)
def test_update_boxes(s):
bl = s.get_box_list()
for b in bl:
b_id = b['id']
if b_id not in KEEP_BOX_IDS:
new_name = b["name"] + "_updated"
new_desc = b["desc"] + "_updated"
s.update_box(b_id, new_name, new_desc)
box_info = s.get_box_info(b_id)
assert box_info["name"] == new_name
assert get_box_info["desc"] == new_desc
I use a fixture to set up the session (this will keep me connected to the API).
As you can see I am creating 3 boxes at the beginning.
All test that are following do some sort of operations on this 3 boxes. (Boxes are just spaces for folders and files)
For example: update_boxes, create_folders, rename_folders, upload_files, change_file names, etc..
I know it's not good, since all the tests are dependent from each other, but if I execute them in the right order the test is valid and thats enough.
The second issue, which borders me the most, is that all the following tests start with the same lines:
bl = s.get_box_list()
for b in bl:
b_id = b['id']
if b_id not in KEEP_BOX_IDS:
box_info = s.get_box_info(b_id)
I always need to call this for loop to get each boxs id and info.
I've tried to put it in a second fixture, but the problem is that then there will be two fixtures.
Is there a better way of doing this?
Thanks

Resources