Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

The assignment is in Pycharm. The assignment asks to convert the username and password to being entered by the user, add the ability to let

The assignment is in Pycharm. The assignment asks to convert the username and password to being entered by the user, add the ability to let the user enter a username to check with the is_admin method, and add exception handling and logging to the count_rows method

import psycopg2
from psycopg2 import sql
import logging
import getpass

# Set up logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)

# Accept user input for database connection
db_username = input("Enter database username: ")
db_password = getpass.getpass("Enter database password: ")

# Connect to the PostgreSQL database
try:
   connection = psycopg2.connect(
       host='localhost',
       database='postgres',
       user=db_username,
       password=db_password
   )
   connection.set_session(autocommit=True)

except psycopg2.Error as e:
   logging.error(f"Error connecting to the database: {e}")
   exit(1)

def is_admin(username: str) -> bool:
   try:
       with connection.cursor() as cursor:
           cursor.execute("""
               SELECT
                   admin
               FROM
                   users
               WHERE
                   username = %(username)s
           """, {'username': username})
           result = cursor.fetchone()

       if result is None:
           # User does not exist
           return False
       else:
           admin, = result
           return admin

   except psycopg2.Error as e:
       logging.exception(f"Error in is_admin(): {e}")
       return False

def count_rows(table_name: str, limit: int) -> int:
   try:
       with connection.cursor() as cursor:
           stmt = sql.SQL("""
               SELECT
                   COUNT(*)
               FROM (
                   SELECT
                       1
                   FROM
                       {table_name}
                   LIMIT
                       {limit}
               ) AS limit_query
           """).format(
               table_name=sql.Identifier(table_name),
               limit=sql.Literal(limit),
           )
           cursor.execute(stmt)
           result = cursor.fetchone()

       rowcount, = result
       return rowcount

   except psycopg2.Error as e:
       logging.exception(f"Error in count_rows(): {e}")
       return 0

# User input loop
while True:
   username_to_check = input("Enter username to check (press 'q' to quit): ")

   if username_to_check.lower() == 'q':
       break

   print(is_admin(username_to_check))

   table_name = input("Enter table name: ")
   limit = int(input("Enter limit: "))
   print(count_rows(table_name, limit))

# Close the database connection
connection.close()

 


Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Income Tax Fundamentals 2013

Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill

31st Edition

1111972516, 978-1285586618, 1285586611, 978-1285613109, 978-1111972516

More Books

Students also viewed these Databases questions