I am connecting, or trying to, MySQL and Python via PyCharm and I input the code that I was given and I am getting several errors that I am unable to resolve. Is there a pro out there that can assist?
Here is the code:
import mysql.connector
from mysql.connector import errorcode
config = {
"user": "movies_user",
"password": "popcorn",
"host": "127.0.0.1",
"database": "movies",
"raise on warnings": True
}
try:
db = mysql.connector.connect(**config)
print("\n Database user {} connected to MySQL on host {} with database {}".format(config["user"], config["host"],
config["database"]))
input("\n\n Press any key to continue...")
except mysql.connector as Error:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print(" The supplied username or password are invalid")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print(" The supplied database does not exist")
else:
print(err)
finally:
db.close()
And here are the errors:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 353, in config
DEFAULT_CONFIGURATION[key]
KeyError: 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 14, in <module>
db = mysql.connector.connect(**config)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\__init__.py", line 159, in connect
return MySQLConnection(*args, **kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 129, in __init__
self.connect(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 449, in connect
self.config(**kwargs)
File "C:\Users\Ryan\PycharmProjects\CSD_310\venv\lib\site-packages\mysql\connector\connection.py", line 355, in config
raise AttributeError("Unsupported argument '{0}'".format(key))
AttributeError: Unsupported argument 'raise on warnings'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 20, in <module>
except mysql.connector as Error:
TypeError: catching classes that do not inherit from BaseException is not allowed
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Ryan\PycharmProjects\CSD_310\mysql_test.py", line 30, in <module>
db.close()
NameError: name 'db' is not defined
Process finished with exit code 1
I feel like I have tried everything that I can possibly find on Google. Any help is much appreciated!
I have tried the above code and I have tried resolving the errors to no avail.
Related
I have written a client and a server-side code to set a P2P type system with a server as a middleman to distribute a file to N clients.
I am getting this error OSError: [WinError 10022] An invalid argument was supplied in this chunk of my code on the server side
try:
for i in l:
print(i)
x = random.randint(0,N-1)
print(x,"Index")
serverSocketTCPRequest = serverSocketTCPList[x]
serverSocketTCPRequest.settimeout(2)
serverSocketTCPRequest.connect((i[0],i[1]))
serverSocketTCPRequest.send("SEND".encode())
serverSocketTCPRequest.send(str(chunkID).encode())
data = serverSocketTCPRequest.recv(1024)
serverSocketTCPRequest.close()
b = False
return data
except Exception as ex:
print(traceback.format_exc())
time.sleep(1)
# print(l)
pass
I am getting the following error:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 149, in getChunks
serverSocketTCPRequest.connect((i[0],i[1]))
OSError: [WinError 10022] An invalid argument was supplied
Traceback (most recent call last):
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 198, in sendChunkRequest
checkMessage, serverAddress = serverSocketUDPRequest.recvfrom(1024)
socket. Timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\IITD\5th Sem\COL334\Assignment 2\server.py", line 149, in getChunks
serverSocketTCPRequest.connect((i[0],i[1]))
OSError: [WinError 10022] An invalid argument was supplied
My client side code for the same is
def handleTCP(client:Client):
global N
while(True):
try:
# print(clientList.index(client), client.clientSocketTCPRequest.getsockname())
client.clientSocketTCPRequest.listen(2*N)
client.clientSocketTCPRequest.settimeout(2)
connectionSocket, addr = client.clientSocketTCPRequest.accept()
print("Connected")
message = connectionSocket.recv(1024).decode()
if message.decode() == "SEND":
i = connectionSocket.recv(1024).decode()
connectionSocket.send(client.dict[int(i)])
connectionSocket.close()
elif message.decode() == "GET":
i = connectionSocket.recv(1024).decode()
client.dict[int(i)] = connectionSocket.recv(1024)
connectionSocket.close()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
m = template.format(type(ex).__name__, ex.args)
print(m,client.clientSocketTCPRequest.getsockname())
# print(traceback.format_exc())
continue
I can't think of a reason this is occurring. The client side shows just a timeout error on each of the N ports.
I have attached the entire client and server side codes and the file I'm trying to send.
furthering my question here, I am trying to put this question in a simpler way.
Following this tutorial, I am trying to start a connection to my Mariadb database in my NAS with SQLalchemy remotely. Here is the code:
# Module Imports
import mariadb
import sys
user = "my_name"
passwd = "my_pass"
host = "192.168.1.111"
db = "test"
port= "3307"
# Connect to MariaDB Platform
try:
conn = mariadb.connect(
user=user,
password=passwd,
host=host,
port=3307,
database=db
)
except mariadb.Error as e:
print(f"Error connecting to MariaDB Platform: {e}")
sys.exit(1)
# Get Cursor
cur = conn.cursor()
then I get this error:
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
Error connecting to MariaDB Platform: Can't connect to server on '192.168.1.111' (36)
Traceback (most recent call last):
File "/var/folders/r5/wq0wq8mx0d56rbrbs38jt94w0000gn/T/ipykernel_39174/3834131737.py", line 14, in <module>
conn = mariadb.connect(
mariadb.OperationalError: Can't connect to server on '192.168.1.111' (36)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3444, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "/var/folders/r5/wq0wq8mx0d56rbrbs38jt94w0000gn/T/ipykernel_39174/3834131737.py", line 24, in <module>
sys.exit(1)
SystemExit: 1
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 1101, in get_records
return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 248, in wrapped
return f(*args, **kwargs)
File "/Users/user/miniforge3/lib/python3.9/site-packages/IPython/core/ultratb.py", line 281, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/Users/user/miniforge3/lib/python3.9/inspect.py", line 1541, in getinnerframes
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
AttributeError: 'tuple' object has no attribute 'tb_frame'
I have brew installed mariadb-connector-cand ;
brew installed mariadb; and
pip installed PyMySQL.
Would anyone please help?
I echo with #Tim Roberts. Go to your NAS "Installed Package", click the MariaDB 10 app. In it please make sure the databases are sharable over the intranet or internet. It is called TCP/IP connection. Check it and your connection will be working.
This is a point lots of people forget about when they first start up Mariadb.
I am using Python3.7
I am trying to email an error in the except condition to the user if the code is not working and following is my code:
except Exception as e:
logging.basicConfig(filename='logfile.log',format='%(asctime)s %(message)s',filemode='w')
logger=logging.getLogger()
logger.setLevel(logging.ERROR)
logger.error(e)
print("ERROR MESSAGE",e)
MY_ADDRESS = '*****#gmail.com'
PASSWORD = '*******'
MY_ADDRESS1 = '****#gmail.com'
s = smtplib.SMTP(host='smtp.gmail.com', port=***)
s.starttls()
s.login(MY_ADDRESS, PASSWORD)
print("login")
msg = MIMEMultipart() # create a message
msg['From']=MY_ADDRESS
msg['To']=MY_ADDRESS1
msg['Subject']="ERROR MESSAGE"
message="ERROR"
msg.attach.as_string(MIMEText(e))
print("ERROR MAILED")
s.send_message(msg)
s.quit()
I want to send the error message in variable 'e' which is being printed
But I am unable to do so
Following is the error:
This is the error which i want to print and mail:
ERROR MESSAGE [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'
This is the error shown on the python shell:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 30, in <module>
wb.save(workbook_name)
File "C:\Python37\lib\site-packages\openpyxl\workbook\workbook.py", line 408, in save
save_workbook(self, filename)
File "C:\Python37\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Python37\lib\zipfile.py", line 1207, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Python37\\Processed\\Invoice.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 88, in <module>
msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python37\Sopan.py", line 88, in <module>
msg.attach.as_string(MIMEText(e))
AttributeError: 'function' object has no attribute 'as_string'
How do i send the error message being printed in variable 'e' by email to someone
THANK YOU
The logging module itself has smtp handler you can do something like this:
import logging
import logging.handlers
smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),
fromaddr="someone#something.com",
toaddrs="receiver#mail.com",
subject=u"ERROR IN YOURAPP!")
logger = logging.getLogger()
logger.addHandler(smtp_handler)
try:
raise Exception
except Exception as e:
logger.exception('Unhandled Exception')
for more info see doc
I am new to network automation, and trying to use pyntc to ssh to the device. I am not sure how to write the code correctly to handle the ssh timeout or authentication error, etc.
My code is as below:
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios$
try:
DEVICE.open()
except Exception:
print('Error')
continue
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
I manually turned off this device, and then I found python code was quit:
root#Network-Automation:~/Pyntc# python3 pyntc_error_handling.py
Backing up ESW1
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 884, in establish_connection
self.remote_conn_pre.connect(**ssh_connect_params)
File "/usr/local/lib/python3.5/dist-packages/paramiko/client.py", line 368, in connect
raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect to port 22 on 192.168.122.72
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pyntc_error_handling.py", line 8, in <module>
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios_ssh')
File "/usr/local/lib/python3.5/dist-packages/pyntc/__init__.py", line 38, in ntc_device
return device_class(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 42, in __init__
self.open()
File "/usr/local/lib/python3.5/dist-packages/pyntc/devices/ios_device.py", line 300, in open
verbose=False,
File "/usr/local/lib/python3.5/dist-packages/netmiko/ssh_dispatcher.py", line 246, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 317, in __init__
self._open()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 322, in _open
self.establish_connection()
File "/usr/local/lib/python3.5/dist-packages/netmiko/base_connection.py", line 890, in establish_connection
raise NetMikoTimeoutException(msg)
netmiko.ssh_exception.NetMikoTimeoutException: Connection to device timed-out: cisco_ios 192.168.122.72:22
Looks like there are more than 1 errors ...
You are doing a minor mistake here, you are expecting an error than trying to same the output. In case of error, the script will through an error. Try it this way.
from pyntc import ntc_device as NTC
from pyntc_devices_list import Get_Devices_List
all_devices = Get_Devices_List()
try:
for device in all_devices:
print('Backing up ' + device['name'])
DEVICE = NTC(host=device['ip'], username=device['username'], password=device['password'], device_type='cisco_ios')
DEVICE.open()
back_config = DEVICE.backup_running_config(device['name'] + '.cfg')
DEVICE.close()
except Exception as Err:
print(Err)
I want to return an error code when the following error gets raised:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 202, in create_group
ssh.connect(hostname, username=user, password=remotepass)
File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 290, in connect
sock.connect(addr)
File "<string>", line 1, in connect
socket.error: [Errno 113] No route to host
>>>
But I'm currently having trouble catching the error raised.
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=user, password=remotepass)
except paramiko.AuthenticationException:
return 259
except socket.error:
return 261
chan = ssh.get_transport().open_session()
chan.exec_command(command)
codest = chan.recv_exit_status()
ssh.close()
return codest
Resulting on this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "UserManagementRemote.py", line 207, in create_group
except socket.error:
NameError: global name 'socket' is not defined
>>>
Any ideas?
Do
import socket
in the module where you do the exception handling.
To prevent this problem in the future, run pyflakes on all your source files. That will catch a lot of other errors as well.