Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Generalize: make gitbored work with other sites, apps
----------------------------------------------------- * relocate `gitbored/db.py` -> `gitbored/daemon/db.py`. It is only used by the daemon. * add magic to `db.py` to get `settings` based upon (required) `DJANGO_SETTINGS_MODULE`. * new `logger.py` module to "centralize" logging. * notes/docs describing the changes/hacks
- Loading branch information
Showing
with
67 additions
and 35 deletions.
- +3 −4 gitbored/daemon/base.py
- +49 −0 gitbored/daemon/db.py
- +0 −31 gitbored/db.py
- +15 −0 gitbored/logger.py
@@ -0,0 +1,49 @@ | ||
# -*- mode: python; coding: utf-8 -*- | ||
"""re-export `models.*` and make models (and ORM) usable outside of web framework. | ||
>>> import db | ||
>>> record = db.SomeTable(**kwargs) | ||
>>> record.save() | ||
et cetera. | ||
""" | ||
|
||
import os | ||
import importlib | ||
import django | ||
|
||
from gitbored import logger | ||
|
||
# There is a bit of hackery here. Read comments starting with 'HACK' | ||
|
||
try: | ||
# HACK -- we require that DJANGO_SETTINGS_MODULE be set to the the name | ||
# of the site's settings' module, e.g. `mysite.settings` | ||
django_settings_module_name = os.environ['DJANGO_SETTINGS_MODULE'] | ||
except KeyError: | ||
raise ImportError(""" | ||
The "DJANGO_SETTINGS_MODULE" environment must be set to the name of your site's setting's module. For example: | ||
export DJANGO_SETTINGS_MODULE="mysite.settings" | ||
""") | ||
|
||
# HACK -- this is magic for "from mysite.settings import *" | ||
globals().update(importlib.import_module( | ||
django_settings_module_name).__dict__) | ||
|
||
from django.conf import settings | ||
from django.db import connections | ||
import atexit | ||
|
||
# HACK -- note that the rhs "DATABASES" here comes from mysite.settings, above | ||
settings.configure(DATABASES=DATABASES) | ||
django.setup() | ||
|
||
#globals().update(importlib.import_module(app_models_module_name).__dict__) | ||
from gitbored.models import * | ||
|
||
def cleanup(): | ||
logger.info('closing all django database connections for this process') | ||
connections.close_all() | ||
|
||
atexit.register(cleanup) |
@@ -0,0 +1,15 @@ | ||
# -*- mode: python; coding: utf-8 -*- | ||
"""A small amount of justified magic: with this module, | ||
>>> import logger | ||
>>> logger.debug('yay!') | ||
""" | ||
|
||
import logging | ||
|
||
_logger = logging.getLogger(__name__) | ||
_logger.setLevel(logging.DEBUG) | ||
|
||
for level in 'debug', 'info', 'warning', 'error', 'exception', 'critical', 'addHandler': | ||
globals()[level] = getattr(_logger, level) | ||
|