[파이썬] Psycopg2에서 NOTIFY events 수신

PostgreSQL is a popular and powerful open-source relational database management system. It provides various features to support real-time data communication and integration with other applications. One such feature is the ability to send notifications from the database to connected clients using the NOTIFY command.

In Python, Psycopg2 is the most commonly used PostgreSQL adapter. It allows you to interact with the PostgreSQL database using Python code. In this blog post, we will explore how to receive NOTIFY events in Python using Psycopg2.

Prerequisites

To follow along with this tutorial, you’ll need:

Setting up the Database

Before we can receive NOTIFY events, we need to have a PostgreSQL database set up with the necessary tables and functions. Let’s create a table for storing notification events and a trigger function that sends the notifications.

CREATE TABLE notification_events (
    id SERIAL PRIMARY KEY,
    event_name VARCHAR(100),
    event_data JSONB,
    created_at TIMESTAMPTZ DEFAULT now()
);

CREATE OR REPLACE FUNCTION notify_event(event_name VARCHAR, event_data JSONB)
RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO notification_events (event_name, event_data)
    VALUES (event_name, event_data);
    
    PERFORM pg_notify('event_notification', event_name);
    
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

Receiving NOTIFY events

To receive NOTIFY events in Python, we need to establish a connection to the PostgreSQL database using Psycopg2. Here’s an example code snippet that demonstrates how to receive NOTIFY events:

import psycopg2

conn = psycopg2.connect(
    host="your_host",
    port="your_port",
    database="your_database",
    user="your_user",
    password="your_password"
)

# Create a new database cursor
cur = conn.cursor()

# Listen for events
cur.execute("LISTEN event_notification")

while True:
    # Wait for notifications to arrive
    conn.poll()
    
    while conn.notifies:
        # Process each notification received
        notification = conn.notifies.pop(0)
        
        print(f"Received notification: {notification.channel} - {notification.payload}")

In the above code, we first establish a connection to the PostgreSQL database using the psycopg2.connect() function. Make sure to replace the placeholders with your actual database connection details.

Then, we create a database cursor and start listening for events using the LISTEN command. In this example, we’re listening for events on the channel called “event_notification”, which is the same channel we used in the trigger function.

We enter a while loop and call conn.poll() to wait for notifications to arrive. When a notification is received, we process it by getting the first notification from the conn.notifies list and printing its channel and payload to the console.

Conclusion

In this blog post, we learned how to receive NOTIFY events in Python using Psycopg2. This feature can be useful in various scenarios, such as real-time updates, event-driven architectures, and message passing systems. With Psycopg2 and PostgreSQL, you have the tools to build powerful and responsive applications that leverage the database’s notification capabilities.

Keep in mind that this is just a basic example, and you can extend it based on your specific use case. Happy coding!