Created
February 1, 2016 10:50
-
-
Save boblefrag/95f4d48c72f6bcd1ca14 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import importlib | |
import select | |
import json | |
import logging | |
from django.db import connection | |
from django.conf import settings | |
from django.core.management.base import BaseCommand | |
logger = logging.getLogger(__name__) | |
""" | |
Command used to listen for events in the database about badges | |
""" | |
class Command(BaseCommand): | |
def handle(self, *args, **options): | |
channels = settings.BADGES_CHANNEL | |
cur = connection.cursor() | |
for chan in channels: | |
print chan | |
cur.execute("LISTEN %s;" % chan) | |
epoll = select.epoll() | |
conn = connection.connection | |
epoll.register(conn, select.EPOLLIN) | |
while True: | |
try: | |
epoll.poll() | |
conn.poll() | |
while conn.notifies: | |
notify = conn.notifies.pop() | |
print notify | |
parse_payload(notify.payload) | |
except BaseException as e: | |
print e | |
for chan in channels: | |
cur.execute("UNLISTEN %s;" % chan) | |
break | |
def parse_payload(payload): | |
""" | |
when a new message is posted by postgreSQL, we have to parse | |
it. | |
The message is a json payload with 2 mandatory keys: "module" and | |
"function". | |
And Two optional keys: args and kwargs | |
""" | |
print payload | |
try: | |
callback = json.loads(payload) | |
except Exception as e: | |
logger.warning(e) | |
return | |
if not "module" in callback or not "function" in callback: | |
logger.warning( | |
"payload does not contains a 'module or function' key: %s" | |
% payload) | |
return | |
try: | |
mod = importlib.import_module(callback["module"]) | |
func = getattr(mod, callback["function"]) | |
results = func(*callback.get("args", []), | |
**callback.get("kwargs", {})) | |
if results: | |
print results | |
logger.info(results) | |
except Exception as e: | |
print e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment