Trouble with data manipulation from tkinter - python

Problem
I cannot manipulate (insert, delete, update) data on a mysql table from tkinter. EDIT: I have been trying to insert/change data on mysql tables using tkinter. Although there's no error when I run this code, I cannot see any changes made in the table on mysql.
Code
def delete_record():
code=tcode.get('1.0',END)
#DATABASE CONNECTION
if code.isdigit()==True:
import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",user="root",passwd=" ",database="iv")
tkcursor=connection.cursor(prepared=True)
tkcursor.executed("delete from salesperson where code=%s,(code)")
mycon.commit()
tkinter.messagebox.showinfo("Record Deleted")
tkcursor.close()

Your two errors are the use of get() with Text widget and also your sql command seems incorrect. So try this out:
def delete_record():
code=tcode.get('1.0','end-1c') #change made here
#DATABASE CONNECTION
if code.isdigit()==True:
import mysql.connector as sqltor
mycon=sqltor.connect(host="localhost",user="root",passwd=" ",database="iv")
tkcursor=connection.cursor(prepared=True)
tkcursor.execute("delete from salesperson where code=%s",(code,)) #also change made here
mycon.commit()
tkinter.messagebox.showinfo("Record Deleted",'The records have been successfully deleted') #also addded message into the messagebox
tkcursor.close()
Also its a good practice to do all the imports on top of your code. Why to use end-1c ? Bryan Oakley has explained it below, take a look there. You were not getting any errors because the if statement never got executed, so also make sure to say print(code) and make sure it is a digit.

code isn't going to be what you think it is, and will never pass the isdigit test. Because you are getting to the END index, the data will have a trailing newline because the tkinter widget guarantees that there will always be a trailing newline.
When you want to get out of the text widget exactly what the user entered, you need to use "end-1c" ("end" minus one character). That, or strip off the trailing newline after you get it.
code = tcode.get('1.0', 'end-1c')
The first step in debugging should always be to examine variables to see if they are what you're assuming they are.

Related

Program doesn't append file using variables, but no error message appears

Using Python 3.4.2
I'm working on a quiz system using python. Though it hasn't been efficient, it has been working till now.
Currently, I have a certain user log in, take a quiz, and the results of the quiz get saved to a file for that users results. I tried adding in so that it also saves to a file specific to the subject being tested, but that's where the problem appears.
user_score = str(user_score)
user_score_percentage_str = str(user_score_percentage)
q = open('user '+(username)+' results.txt','a')
q.write(test_choice)
q.write('\n')
q.write(user_score+'/5')
q.write('\n')
q.write(user_score_percentage_str)
q.write('\n')
q.write(user_grade)
q.write('\n')
q.close()
fgh = open(test_choice+'results.txt' ,'a')
fgh.write(username)
fgh.write('\n')
fgh.write(user_score_percentage_str)
fgh.write('\n')
fgh.close
print("Your result is: ", user_score , "which is ", user_score_percentage,"%")
print("Meaning your grade is: ", user_grade)
Start()
Everything for q works (this saves to the results of the user)
However, once it comes to the fgh, the thing doesn't work at all. I receive no error message, however when I go the file, nothing ever appears.
The variables used in the fgh section:
test_choice this should work, since it worked for the q section
username, this should also work since it worked for the q section
user_score_percentage_str and this, once more, should work since it worked for the q section.
I receive no errors, and the code itself doesn't break as it then correctly goes on to print out the last lines and return to Start().
What I would have expected in the file is to be something like:
TestUsername123
80
But instead, the file in question remains blank, leading me to believe there must be something I'm missing regarding working the file.
(Note, I know this code is unefficient, but except this one part it all worked.)
Also, apologies if there's problem with my question layout, it's my first time asking a question.
And as MooingRawr kindly pointed out, it was indeed me being blind.
I forgot the () after the fgh.close.
Problem solved.

How to disable query cache?

First of all, sorry for not 100% clearly questions title.
It is easier to explain with few lines of code:
query = {...}
while True:
elastic_response = elastic_client.search(elastic_index, body=query, request_cache=False)
if elastic_response["hits"]["total"]) == 0:
break
else:
for doc in elastic_response["hits"]["hits"]:
print("delete {}".format(doc["_id"]))
elastic_client.delete(index=elastic_index, doc_type=doc["_type"], id=doc["_id"])
I make a search, then delete all the docs and then do the search again to get the next bunch.
BUT the search query gives me the same docs! And this results in 404 exception on delete. It has to be some kind of cache, but i does not found anything, "request_cache" doesn't help.
I can probably refactor this code to use batch delete, but i want to understand what is wrong here
P.S. i'm using the official python client
If using a sleep() after the deletes makes the documents go away, then it's not about cache. It's about the refresh_interval and the near real timeness or Elasticsearch.
So, call _refresh after your code leaves the for loop. Also, don't delete document by document, but create a _bulk request where you delete all your documents in batches, depending on how many they are.

Escaping characters for instance query matching in webpy

(The title may be in error here, but I believe that the problem is related to escaping characters)
I'm using webpy to create a VERY simple todo list using peewee with Sqlite to store simple, user submitted todo list items, such as "do my taxes" or "don't forget to interact with people", etc.
What I've noticed is that the DELETE request fails on certain inputs that contain specific symbols. For example, while I can add the following entries to my Sqlite database that contains all the user input, I cannot DELETE them:
what?
test#
test & test
This is a test?
Any other user input with any other symbols I'm able to DELETE with no issues. Here's the webpy error message I get in the browser when I try to DELETE the inputs list above:
<class 'peewee.UserInfoDoesNotExist'> at /del/test
Instance matching query does not exist: SQL: SELECT "t1"."id", "t1"."title" FROM "userinfo" AS t1 WHERE ("t1"."title" = ?) PARAMS: [u'test']
Python /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/peewee.py in get, line 2598
Web POST http://0.0.0.0:7700/del/test
When I view the database file (called todoUserList.db) in sqlitebrowser, I can see that these entries do exist with the symbols, they're all there.
In my main webpy app script, I'm using a regex to search through the db to make a DELETE request, it looks like this:
urls = (
'/', 'Index',
'/del/(.*?)', 'Delete'
)
I've tried variations of the regex, such as '/del/(.*)', but still get the same error, so I don't think that's the problem.
Given the error message above, is webpy not "seeing" certain symbols in the user input because they're not being escaped properly?
Confused as to why it seems to only happen with the select symbols listed above.
Depending on how the URL escaping is functioning it could be an issue in particular with how "?" and "&" are interpreted by the browser (in a typical GET style request & and ? are special character used to separate query string parameters)
Instead of passing those in as part of the URL itself you should pass them in as an escaped querystring. As far as I know, no web server is going to respect wacky values like that as part of a URL. If they are escaped and put in the querystring (or POST body) you'll be fine, though.

How to create an ldif from a python dict

i want to write a lot of data to an LDAP-Server (preferably using an ldif), but i also want that every insert/modify/delete in the ldif will be rolled back if there is an error. So basically, i need a function, that creates an ldif from a dict and then get the following behaviour.
Lets assume i have an ldif like this:
dn: uid=user,cn=testing,dc=foobar #Existing and valid entry so it should work
changeType: modify
replace: sn
sn: Alfred
dn: uid=user2,cn=testing,dc=foobar #Non-existent entry so it should fail
changeType: modify #Now because this fails, the first change
replace: sn #should be rolled back...
sn: Carl
So if the second ldif entry fails, i want to rollback the changes that were made previously to only create entries, if the whole ldif is correct.
There seems to be no kind of transactions for ldap which would be exactly what i am looking for. Till now i only found the deprecated ldif parser for python...but since its deprecated i do not want to use it anymore. So if any of you know an alternative please tell me.
Any help would be greatly appreciated
The LDAP client should consider using LDAP transactions as specified in RFC5805.

server-side scripting for web pages with Python: nothing happens

I'm trying to learn to use Python to create dynamic web content. Problem I'm having right out the door, though, is that when I try to do a mySQL query, absolutely nothing happens. There's no error message... it looks like the script simply stops running when I import the module that enables connection to the database.
This does do exactly what I'd expect when I try to run it from the command line.
#!/usr/bin/python
print "Content-Type: text/xml"
print
#if I type, for example, print "<b>test</b>" here, it appears in the browser window
#msql contains the credentials for connecting to database
#it is NOT in public_html
import msql
#no print instructions after this point are followed
connex=msql.msqlConn()
db=msql.MySQLdb
cursor=connex.cursor(db.cursors.DictCursor)
cursor.execute("SELECT * FROM userActions")
#run the query
xmlOutput=""
rows=cursor.fetchall()
#output the results
for row in rows:
xmlOutput+="<action>"
xmlOutput+="<actionId>"+str(row["actionId"])+"</actionId>"
xmlOutput+="<userId>"+str(row["userId"])+"</userId>"
xmlOutput+="<actText>"+str(row["action"])+"</actText>"
xmlOutput+="<date>"+str(row["dateStamp"])+"</date>"
xmlOutput+="</action>"
xmlOutput="<list>"+xmlOutput+"</list>"
print xmlOutput
This would be my first stab at this, so it merely stands to reason that this should work. I've found nothing online that would suggest otherwise, though.
Please, take 24h to learn something like Django. Django has an ORM and a XML serializer that will make your life easier ensuring proper (and legal) xml, it really pays up.
You can enable cgi traceback to see what happens:
import cgitb
cgitb.enable()
(I don't think it causes your problem, and clients understand \n as well but it is better to use sys.write("...\r\n") instead of print to print HTTP headers)
Edited: try to add Content-length: XXXX\r\n to the header.

Categories

Resources