Source Code Snippets of "Connect.py"

Mike Dinder

The entire contents of the "Connect.py" file as code examples with syntax highlighting

Auto Generated Using Generate_HTML.py script to auto format each of these pages in a standardized template.

On smaller viewports/windows, please scroll or use your touch/finger to scroll left to right to view all the code displayed.

Connect Python Home
                                        # General Connection Function (Default Practice Database)
import os
import psycopg2

from dotenv import load_dotenv
from psycopg2 import OperationalError
from typing import Union


# Load Environment Variables
load_dotenv()


def connect() -> Union[object, None]:
    """
    Connect to the PostgreSQL database server

    :returns: Connection object or None
    :rtype: Object or None
    """
    conn = None
    try:
        conn = psycopg2.connect(
            dbname=os.getenv('DB_NAME'),
            user=os.getenv('DB_USER'),
            password=os.getenv('DB_PASSWORD'),
            host=os.getenv('DB_HOST'),
            port=os.getenv('DB_PORT')
        )
        print('Connection Successful!')
        return conn
    except OperationalError as e:
        print(f'Error Connecting to the Database: {e}')
        return None


if __name__ == '__main__':
    print('Practice Connecting...')
    connection = connect()

    if connection:
        print('Connected...')
        connection.close()
        print('Connection Closed!')


                                        

Runs the entire script above. Open your Console Window in Inspect Code to view the output of the script above.

A prompt popup will ask you for various input() commands.

Python in Your Browser

Client-side execution via Pyodide · No server · Full stdlib · numpy, pandas, matplotlib available via micropip

Mobile users will want to use this method. Copy snippets or the entire script from above. You may also copy this script exactly as it is shown and you can run it on your own machine using the Command-Line Interface (CLI).

Loading Pyodide...
>>>
Enter run Shift+Enter new line ↑↓ history