When I try connect to mysql with user "root", my application returns "Access denied for user *"ODBC"#"localhost" (using password:NO)"*. I dnt know why this appear.
Im using Tkinter like GUI, I tested only Connection's script, its Okay.
Code Connection
import MySQLdb
class Conexao():
def __init__(self, host,user,passwd,db):
self.host = host
self.user = user
self.passwd = passwd
self.db = db
def getconnection(self):
try:
self.conn = MySQLdb.connect(host=self.host,
user = self.user,
passwd = self.passwd,
db = self.db)
print "Connected"
return self.conn.cursor()
except MySQLdb.Error,e:
print " error "+ str(e[1])
return e
Code App
from Tkinter import *
import sys
sys.path.insert(0,'C:\\Users\\felipe.cunha\\Documents\\project')
from conexao.conexao import Conexao
"""
b.execute("select * from setor")
>>> b.fetchall()
"""
class View(Frame):
def __init__(self,master = None):
Frame.__init__(self)
self.master.title("teste")
self.create_menu()
def create_menu(self):#,width = self.width,height = self.height):
host = "localhost"
label_menu = Label(self.master,text = 'Login')
label_menu.pack()
entrada_menu_login = Entry(self.master)# user
entrada_menu_senha = Entry(self.master, show = "*")# passwd
conn = Conexao(host,entrada_menu_login.get(),entrada_menu_senha.get(),"dsti")
#conn = Conexao(host,"root","d04m10","dsti")
btn_login = Button(self.master,text="Logar",command = conn.getConnection)#self.show_entry_fields)
entrada_menu_login.pack()
entrada_menu_senha.pack()
btn_login.pack()
def show_entry_fields(self):
print(self.entrada_menu_login.get(), self.entrada_menu_senha.get())
app = View()
app.mainloop()
Like Bryan said, that may be the issue with your code, instead of making the button call conn.getConnection() directly, try an approach, where you save the entry variables into 'self' and then when the button is invoked, you create the connection at that time.
The code would look something like -
class View(Frame):
def __init__(self,master = None):
Frame.__init__(self)
self.master.title("teste")
self.create_menu()
def create_menu(self):#,width = self.width,height = self.height):
host = "localhost"
label_menu = Label(self.master,text = 'Login')
label_menu.pack()
self.entrada_menu_login = Entry(self.master)# user
self.entrada_menu_senha = Entry(self.master, show = "*")# passwd
btn_login = Button(self.master,text="Logar",command = self.buttonListener) #self.show_entry_fields
entrada_menu_login.pack()
entrada_menu_senha.pack()
btn_login.pack()
def buttonListener(self):
conn = Conexao(host,self.entrada_menu_login.get(),self.entrada_menu_senha.get(),"dsti")
#conn = Conexao(host,"root","d04m10","dsti")
dbcursor = conn.getConnection()
#Do the rest of the logic you want to do.
The problem is that you are creating the connection when your GUI starts up, before the user has the ability to type in a username or password. Both entrada_menu_login and entrada_menu_senha are blank at the time you create the connection.
The solution is to not create the connection until after the user has clicked the button.
Related
I am receiving an error
this is my code block (simplified, but still demonstrates error)
import neo4j
import sys
import uuid
from neo4j import GraphDatabase
def create_population_point(tx, _point, _uuid, _tl, _tr, _ll, _lr, _band):
print("Add a record block A")
tx.run("CREATE (n:Population_Point
{point:$point,uuid:$uuid,TL:$tl,TR:$tr,BL:$bl,BR:$br,Band_1:$band}),"
"point=_point,uuid=_uuid,tl=_tl,tr=_tr,ll=_ll,lr=_lr,band=_band")
def main():
uri = "neo4j://localhost:7687"
username = "neo4j"
password = "P#ssword2"
databaseConnection = GraphDatabase.driver(uri, auth=(username, password))
databaseSession = databaseConnection.session()
print("Connection established")
print("Variables assigned values")
_point = "D007_S001_T001"
_uuid = uuid.uuid4()
_tl = "28.27291"
_tr = "-81.65765"
_ll = "28.27291"
_lr = "-81.65765"
_band = "455"
print("Ready to execute")
with databaseSession.session() as session:
result = session.write_transaction(create_population_point, _point, _uuid, _tl, _tr, _ll,
_lr, _band)
databaseConnection.close()
print("Connection closed")
if __name__ == "__main__":
main()
This is the line that is throwing the error
with databaseSession.session() as session:
running python 3.10.4
First you create
databaseSession = databaseConnection.session()
next you use
with databaseSession.session() as session:
so finally you try to use
databaseConnection.session().session()
and this is wrong.
You could use directly
result = databaseSession.write_transaction(..)
or use databaseConnection instead of databaseSession in
with databaseConnection.session() as session:
result = session.write_transaction(..)
(and remove databaseSession = databaseConnection.session() because you don't use it)
I'm working on a project very similar to this one: GitHub
I have a class:
class DBfunctions:
def __init__(self, dbname = '../example.db'):
self.debname = dbname
self.conn = sqlite3.connect(dbname)
def search_db(self, telegram_id):
telegram_id = (telegram_id,)
sql = 'SELECT * FROM user WHERE id = ?;'
row = self.conn.execute(sql,telegram_id)
return row
def newuser_db(self, tele_id, name, nick):
par = (tele_id, name, nick, 0)
sql = 'INSERT INTO user VALUES(?,?,?,?);'
self.conn.execute(sql, par)
self.conn.commit()
than i have the main project:
from file import DBfunctions
db = DBfunction()
def start(update: Update, context: CallbackContext): #befor edit: somethingtodo
flag = db.search_db(update.effective_user.id) # here problems start
if flag == None:
db.newuser_db(update.effective_user.id, update.effective_user.first_name, update.effective_user.username)
update.message.reply_text(
'Hi!',
reply_markup=markup,
)
else:
update.message.reply_text(
'Hey! Welcome back!',
reply_markup=markup,
)
def main():
db.setup() # this function is to create tables if not exist yet
dispatcher.add_handler(CommandHandler('start', start))
# other function but nothing correlated
if __name__ == '__main__':
main()
And than the error appears:
File "filefolder/file.py", line 29, in search_db
row = self.conn.execute(sql,telegram_id)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 15004 and this is thread id 11036.
I can't figure out what i can do to fix it... and don't understand what is different from the project that I find on github (linked)
I want to have a MongoDB operation in a celery task but im facing some issues while accessing the instance variables.
Heres the code
app = CeleryConnector().app
class CeleryTasks:
def __init__(self, port, docID, dbName, collName, data):
self.port = port
self.docID = docID
self.dbName = dbName
self.collName = collName
self.data = data
self.client = MongoClient(host='localhost', port=port, username='admin', password='password')
self.db = self.client[dbName]
print ("CeleryTasks:init")
#app.task
def createDoc(dbName, collName, data):
print ("CeleryTasks:CreateDoc")
if 'refs' not in data:
return
# Here is the error I dont know how to access the client variable here.
#db = client[dbName]
print(data['refs'])
for id in data['refs']:
doc = db[collName].find_one({'_id': id})
if doc is None:
insertedID = db[collName].insert_one({
"_id": id
})
print (insertedID)
#app.task(bind=True)
def createDoc(self, dbName, collName, data):
print ("CeleryTasks:CreateDoc")
if 'refs' not in data:
return
print(data['refs'])
for id in data['refs']:
doc = self.db[collName].find_one({'_id': id})
if doc is None:
insertedID = self.db[collName].insert_one({
"_id": id
})
print (insertedID)
As we cannot pass non JSON serializable objects to a Task so passing db or client is not an option.
Problem with the first function
I dont know how to access client inside it. Tried a few things but failed.
Problem with the second function
It gives an error doc = self.db[collName].find_one({'_id': id})
AttributeError: 'createDoc' object has no attribute 'db'
etc etc
How to make this work or how to access instance variables inside celery tasks?
I wanna call an Oracle function returning an objectby using cx_Oracle`s cursor.callfunc(). But this is not working
Here you can see my code:
import cx_Oracle
import json
import web
urls = (
"/", "index",
"/grid", "grid",
)
app = web.application(urls, globals(),web.profiler )
web.config.debug = True
connection = cx_Oracle.Connection("TEST_3D/limo1013#10.40.33.160:1521/sdetest")
typeObj = connection.gettype("MDSYS.SDO_GEOMETRY")
class index:
def GET(self):
return "hallo moritz "
class grid:
def GET(self):
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
web.header('Content-Type', 'application/json')
cursor = connection.cursor()
cursor.arraysize = 10000 # default = 50
cursor.execute("""SELECT a.id AS building_nr, c.Geometry AS geometry, d.Classname FROM building a, THEMATIC_SURFACE b, SURFACE_GEOMETRY c, OBJECTCLASS d WHERE a.grid_id_400 = 4158 AND a.id = b.BUILDING_ID AND b.LOD2_MULTI_SURFACE_ID = c.ROOT_ID AND c.GEOMETRY IS NOT NULL AND b.OBJECTCLASS_ID = d.ID""")
obj = cursor.fetchone()
obj = obj[1]
print obj
cursor.callfunc("SDO2GEOJSON", cx.Oracle.OBJECT, [obj])
# Aufruf der App
if __name__ == "__main__":
app.run(web.profiler)
Error message:
at /grid
global name 'cx' is not defined
But I am sure that cx_Oracle is correct installed. Furthermore I use import cx_Oracle at the beginning and this is working.
What is wrong?
Simple typo. In the line
cursor.callfunc("SDO2GEOJSON", cx.Oracle.OBJECT, [obj])
You should use cx_Oracle.OBJECT
I have a little problem with web.py. Exacly I have problem with sessions.
Link to my app:
http://len.iem.pw.edu.pl/~witkowr1/apps/demo/
Login/password: wtq/wtq
Code:
# -*- coding: utf-8 -*-
import web
import json
from web.contrib.template import render_jinja
import datetime
prefix = '/~witkowr1/apps/demo'
urls = (
prefix + '/login','Login',
prefix + '/logout','Logout',
prefix + '/', 'Index',
)
app = web.application(urls, globals())
wsgi = app.wsgifunc()
session = web.session.Session(app, web.session.DiskStore('sessions'),initializer={'time':datetime.datetime.now()})
render = render_jinja('static', encoding = 'utf-8')
render._lookup.globals.update(assets=prefix+'/static')
class Login:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
login = web.input().login
password = web.input().passwd
if login == 'wtq' and password == 'wtq':
session.logged_in = True
session.time = datetime.datetime.now()
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=login, date_last_login=last_login_data)
else:
session.logged_in = False
error=u'Niepoprawne dane. SprĂłbuj jeszcze raz.'
return render.login(error_msg=error)
class Logout:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
session.logged_in = False
web.setcookie('time',session.time)
message = u'Zostałeś poprawnie wylogowany.'
session.kill()
return render.login(error_msg=message)
class Index:
def GET(self):
return render.login()
if __name__ == "__main__":
app.run()
I would like to verify session and if I login early, I see site with latest login date.
Now, when I refresh the site, I must login again.
I think, that I check session, when I rendering HTML site, but I don't know, what I do it.
Please help!
The problem here is that you are not checking whether they are logged in if they access the page with GET method.
You would need to make a change like:
def GET(self):
if session.logged_in:
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=login, date_last_login=last_login_data)
else:
web.seeother(prefix+'/')
But you should rewrite this, a lot, so that you are taken to another page once you are logged in, and that page is responsible for rendering this information. There is a lot of room for improvement in the structure of your application.
That said, the simple answer is - even though you store the session, the "GET" method of login is entirely unaware of sessions, and will always return the login prompt.
Not sure if you solved your problem already but since it looks like there are often some problems with sessions in web.py I pushed a small and crude demo of it to bitbucket. Works fine for me so hope this works for you.
You can get it via:
git clone https://victorkohler#bitbucket.org/victorkohler/webpy-login.git
I solved my problem.
Very stupid mistakes :)
Code:
# -*- coding: utf-8 -*-
import web
from web.contrib.template import render_jinja
import datetime
prefix = ''
urls = (
prefix + '/', 'Index',
prefix + '/login','Login',
prefix + '/logout','Logout',
)
app = web.application(urls, globals())
wsgi = app.wsgifunc()
web.config.debug = False
session = web.session.Session(app, web.session.DiskStore('sessions'),initializer={'time':datetime.datetime.now()})
render = render_jinja('static', encoding = 'utf-8')
render._lookup.globals.update(assets=prefix+'/static')
allowed = (
('user','user'),
)
class Login:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
login = web.input().login
passwd = web.input().passwd
if(login,passwd) in allowed:
session.logged_in = True
session.login = login
session.time = datetime.datetime.now()
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=login, date_last_login = last_login_data)
else:
session.logged_in = False
error=u'Niepoprawne dane. Spróbuj jeszcze raz.'
return render.login(error_msg=error)
class Logout:
def GET(self):
web.seeother(prefix+'/')
def POST(self):
session.logged_in = False
web.setcookie('time',session.time)
message = u'Zostałeś poprawnie wylogowany.'
session.kill()
return render.login(error_msg=message)
class Index:
def GET(self):
if session.get ('logged_in') == True:
last_login = web.cookies().get('time')
if last_login == None:
last_login_data = u'Zalogowałeś się pierwszy raz.'
else:
last_login_data = last_login
return render.logged(name=session.get ('login'), date_last_login = last_login_data)
else:
return render.login()
if __name__ == "__main__":
app.run()
This is not an answer to your question but an extension of the question. I have a similar solution to the login from the webpy cookbook (http://webpy.org/cookbook/userauthbasic) but would like to load the variable allowed from a database.
allowed = (
('user','user'),
)
When I tried a read to assign the value to the variable it comes out as "None" when executed in the login class.
def readUsersDb():
def POST(self):
# load user data into allowed variable
usersDbFilePath = 'userdata/irf/default/'
usersDbFile = 'usersDb.db'
usersDbFilePath = usersDbFilePath + usersDbFile
conn = sqlite3.connect(usersDbFilePath)
c = conn.cursor()
c.execute('SELECT * FROM users')
output = c.fetchall()
conn.close()
global allowed
allowed = output
readUsersDb()
The login functions when the variable allowed is hard coded. I used the format from the database read and it still functions as expected so it is not a format issue.
#response: [(u'user1', 'user1'), (u'user2', 'user2'), (u'user3', 'user3')]
Hopefully someone has tried to do this previously. If it is a faux pas to add a question as an answer I apologize ahead of time.