AssertRaises Doesn't Work with PsycoPg2 - python

I am trying to test that an error is thrown in unittest with Python 3.6 when working with psycopg2. In this case, the database named foo does not existm, and it should throw an OperationalError because the database is not a valid one.
Here is a sample test case:
# -*- coding: utf-8 -*-
import unittest
import psycopg2
import logging
def pull_pg_data(conn, cursor, first, last):
try:
cursor.execute('SELECT first_name, last_name, email, street FROM user_data WHERE first_name =%s AND last_name=%s',(first, last))
except psycopg2.OperationalError as msg:
logging.error(msg)
raise
conn.commit()
result = cursor.fetchall()
return result
class SampleTestCases(unittest.TestCase):
def setUp(self):
try:
self.conn = psycopg2.connect(dbname='postgres', user='postgres', host='localhost', port=5432,
connect_timeout=10)
except psycopg2.OperationalError as msg:
logging.critical(msg)
raise
self.conn.autocommit = True
self.cursor = self.conn.cursor()
self.cursor.execute('DROP TABLE IF EXISTS user_data', [])
self.cursor.execute('CREATE TABLE user_data (first_name TEXT, last_name TEXT, email TEXT, street TEXT)', [])
self.cursor.execute("INSERT INTO user_data(first_name, last_name, email, street) VALUES('someFirstName', 'someLastName', 'some#example.com', '123 road')",[])
def test_pull_pg_data_fail(self):
conn = psycopg2.connect(dbname='foo', user='postgres', host='localhost', port=5432, connect_timeout=10)
cursor = conn.cursor()
self.assertRaises(psycopg2.OperationalError, pull_pg_data, conn, cursor, 'someFirstName', 'someLastName')
if __name__ == '__main__':
unittest.main()
When I run the test, it does indeed throw an error, but it fails the test. I don't know what I am doing incorrectly with assertRaises, because I do want to test that the error is thrown when I try to connect to a database that does not exist.

Related

ImportError: cannot import name 'config' & 'module' object is not callable using PostgreSQL & Python

Hey I am having trouble connecting to my PostgreSQL DB through Python. I am following this tutorial However when I attempt to run the code I return the following error:
Traceback (most recent call last):
File "/Users/username/Desktop/Coding/anybody/postgresqltest.py", line 2, in <module>
from config import config
ImportError: cannot import name 'config'
[Finished in 0.201s]
However, I have pip installed config (I am using a virtual environment) and verified using pip list
When I remove from config import config and replace with just import config I receive this error:
module' object is not callable [Finished in 0.127s]
Here is the code I have written, I am a bit stuck on what to do next (the actual database I am connecting to isn't called test btw, this is a different one):
import psycopg2
from configparser import ConfigParser
def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)
# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
return db
from config import config
def connect():
conn = None
try:
params = config()
print('Connecting to the PostgreSQL DB')
conn = psycopg2.connect(**params)
cur = conn.cursor()
print('PostgreSQL database version:')
cur.execute('Select version()')
db_version = cur.fetchnone()
print(db_version)
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
connect()
Put the config function into a separate .py file.
actually you don't need the config module at all in case you have the DB connection parameters:
here's the code that worked for my connection to DB hosted by Elephant (https://api.elephantsql.com/):
import psycopg2
#from config import config
conn = None
conn = psycopg2.connect(
host="your DB host",
database="DB NAME",
user="USER NAME",
password="DB PASSWORD")
try:
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
# create a cursor
cur = conn.cursor()
# execute a statement with cur.execute()
# in this case we get the version
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
if __name__ == '__main__':
main()
also, the docs by psycopg don't mention "config" module:
https://www.psycopg.org/docs/usage.html

How to trigger 'return' when specific output given

I'm developing a authentication script in Python. I need PyMySQL to check if user exists, how can I do that?
I read the documention but didn't find answer to my question.
def check():
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
userexist = # PyMySQL check code here
if userexist=='True':
return 'good'
It's not clear whether you want to check for the pymysql user or a user from the database. This code will address both instances.
pymysql will raise an exception: pymysql.err.OperationalError if the user does not exist. You therefore need a try, except clause like this:
def check():
try:
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
except pymysql.err.OperationalError:
print('User with entered connection credentials does not exists')
return False
try:
with connection.cursor() as cursor:
cursor.execute("select...") # Fill with your select statement
result = cursor.fetchone()
if result is None:
connection.close()
return False
finally:
connection.close()
return 'good'

python mysql connection auto connect on error

I have a problem with my python mysql connection which I need help with.
My setup is two Pi's running servers on each one. One Pi (SolartPi) has Mysql database collecting data. The other pi (OfficePi) is connecting to the solarPi database to retrieve and update data over a network connection.
My main script works all ok until I have to reboot the SolarPi for a maintenance or power problem and the connection to the OfficePi is lost. The python script on the officePi then goes into a fault loop "2006, MYSQL Server has gone away" Below is a sample of this script.
import MySQLdb
connSolar = MySQLdb.connect("192.xxx.x.x", "external", "xxxxx", "xxxxx")
#eternal connection to solar pi database
cursSolar = connSolar.cursor()
while 1:
try:
cursSolar.execute("SELECT * FROM dashboard")
connSolar.commit()
for reading in cursSolar.fetchall():
heatingDemand = reading[2] #get heating demand from dB
print heatingDemand
except (MySQLdb.Error, MySQLdb.Warning) as e:
print (e)
connSolar.close()
So I tried rewriting this with the script from stackoverflow and a web site as shown below, but this now terminates the program when SolarPi is rebooted with the following error
_mysql_exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on \'192.xxx.x.x' (111 "Connection refused")')
import MySQLdb
class DB:
con = None
def connect(self):
self.conn = MySQLdb.connect("192.xxx.x.x", "xxxxx", "xxxxxx", "house") #eternal connection to solar pi database
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
while 1:
db = DB()
sql = "SELECT * FROM dashboard"
cur = db.query(sql)
for reading in cur.fetchall():
heatingDemand = reading[2] #get heating demand from dB
print heatingDemand
Is there a way for the OfficePi to keep trying to connect to SolarPi mysql database when it has shut down.
Change your code to check a valid connection each loop otherwise pass:
import MySQLdb
class DB:
def connect(self):
try:
self.conn = MySQLdb.connect("192.xxx.x.x", "xxxxx", "xxxxxx", "house")
except (MySQLdb.Error, MySQLdb.Warning) as e:
print (e)
self.conn = None
return self.conn
def query(self, sql):
try:
cursor = self.conn.cursor()
cursor.execute(sql)
except (AttributeError, MySQLdb.OperationalError):
self.connect()
cursor = self.conn.cursor()
cursor.execute(sql)
return cursor
while 1:
db = DB()
conn = db.connect()
if conn:
sql = "SELECT * FROM dashboard"
cur = db.query(sql)
for reading in cur.fetchall():
heatingDemand = reading[2] #get heating demand from dB
print heatingDemand

PyMySQL Error inserting values into table. - Python

I am trying to make a login system with python and mysql. I connected to the database, but when I try to insert values into a table, it fails. I'm not sure what's wrong. I am using python 3.5 and the PyMySQL module.
#!python3
import pymysql, sys, time
try:
print('Connecting.....')
time.sleep(1.66)
conn = pymysql.connect(user='root', passwd='root', host='127.0.0.1', port=3306, database='MySQL')
print('Connection suceeded!')
except:
print('Connection failed.')
sys.exit('Error.')
cursor = conn.cursor()
sql = "INSERT INTO login(USER, PASS) VALUES('test', 'val')"
try:
cursor.execute(sql)
conn.commit()
except:
conn.rollback()
print('Operation failed.')
conn.close()
I think it may have to do with the order of the statements in the connection. According to the PyMySQL github (found here) the correct order is host, port, user, passwd, db.
Like this :
user = input("User: ")
pass = input("Pass: ")
sql = "INSERT INTO login(USER, PASS) VALUES('%s', '%s')"%(user, pass)
btw you should connect like this :
conn = pymysql.connect(
host='127.0.0.1',
user='root',
passwd='root',
db='MySQL
)

Python to MySQL Database: What exception handling

for a project at uni i need to insert different kinds of variables into a MySql Database. Connecting and Inserting the data so far works fine. I don't know how to handle potential errors though. Which potential mistakes and exceptions do i need to catch and take care of ?
In my code i used a main method to just test the program. In the final version just the connection and the SQL queries are copied into the main script. I am open to use either the MySQL or the mysql.connector. Also: Do i need to put the query into a try block aswell ? Here is my code so far:
import mysql.connector
import time
from mysql.connector import errorcode
try:
con = mysql.connector.connect(
user= 'root',
password= '',
host='localhost',
database= 'testdb')
print("Connected.")
cursor = con.cursor()
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Passwort // Username")
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print("DataBase does not exist")
else:
print(e)
def insert_temp(Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID):
query = "INSERT INTO Temperatur (Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID)" \
"VALUES(%s, %s, %s, %s)"
args= (Temperatur_ID, Zeitpunkt, Wert, Thermometer_ID)
cursor.execute(query, args)
con.commit()
def main():
# just test values so far
value = 18.5;
insert_temp(' ', time.strftime('%Y-%m-%d %H:%M:%S'), value, '1');
cursor.close()
con.close()
if __name__ == '__main__':
main()
please note that i have very little experience in python programming

Categories