Skip to content

Instantly share code, notes, and snippets.

Created August 24, 2012 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/3451422 to your computer and use it in GitHub Desktop.
Save anonymous/3451422 to your computer and use it in GitHub Desktop.
BrubeckMySQL Implementation Details
## Just the relevant parts here
...
project_dir = '.'
config = {
...
'settings_file': project_dir + '/config/salesbus/settings.py',
...
}
app = SalesBus(**config)
## start our server to handle requests
if __name__ == "__main__":
app.run()
#!/usr/bin/env python
from brubeckmysql.base import create_db_conn
import time
import datetime
import logging
from gevent.queue import Queue
from gevent.greenlet import Greenlet
from gevent.event import Event
from brubeck.request_handling import Brubeck
import logging
import imp
def lazyprop(method):
""" A nifty wrapper to only load preoperties when accessed
uses the lazyProperty pattern from:
http://j2labs.tumblr.com/post/17669120847/lazy-properties-a-nifty-decorator
inspired by a stack overflow question:
http://stackoverflow.com/questions/3012421/python-lazy-property-decorator
This is to replace initializing common variable from cookies, query string, etc ..
that would be in the prepare() method.
"""
attr_name = '_' + method.__name__
@property
def _lazyprop(self):
if not hasattr(self, attr_name):
attr = method(self)
setattr(self, attr_name, method(self))
# filter out our javascript nulls
if getattr(self, attr_name) == 'undefined':
setattr(self, attr_name, None)
return getattr(self, attr_name)
return _lazyprop
class BrooklynCodeBrubeck(Brubeck):
"""our main application, extending Brubeck
This is not application specific,
but general stuff that maybe shoud be in Brubeck someday"""
def __init__(self, settings_file, project_dir,
*args, **kwargs):
""" Most of the parameters are dealt with by Brubeck,
do a little before call to super
"""
if project_dir == None:
raise Exception('missing project_dir from config')
else:
self.project_dir = project_dir
"""load our settings"""
if settings_file != None:
self.settings = self.get_settings_from_file(settings_file)
else:
self.settings = {}
# we may have overriden default mongrel2_pairs in settings
#if 'mongrel2_pair' in self.settings:
# kwargs['mongrel2_pair'] = self.settings['mongrel2_pair']
Brubeck.__init__(self, **kwargs)
def get_settings(self, setting_name, file_name=None):
""" This is an attempt at providing a possible
external location for settings to overide any
settings in the settings file that was passed
to the application during initialization.
"""
try:
if hasattr(self, 'settings'):
if hasattr(self.settings, setting_name):
# we had our settings loaded already
return getattr(self.settings, setting_name)
if file_name == None:
# create default file name
file_name = self.project_dir + '/conf/' + setting_name + '.py'
# try to load our file
settings = self.get_settings_from_file(file_name)
if hasattr(settings, setting_name):
# load us in self.settings
# so we don't need to read from file next time
self.settings.append({setting_name:settings[settings_name]})
return settings[settings_name]
raise Exception("Unable to load settings from file %s: %s " % (file_name, setting_name))
except:
# raise our error
raise
def get_settings_from_file(self, file_name):
settings = None
logging.debug ('loading settings from %s' % file_name)
try:
settings = imp.load_source('settings', file_name)
except:
raise #Exception("unknown error getting file: " + file_name)
return settings
class SalesBus(BrooklynCodeBrubeck):
"""Custom application class for SalesBus."""
def __init__(self, settings_file=None, project_dir=None,
*args, **kwargs):
""" Most of the parameters are dealt with by Brubeck,
Additional functionality follow call to super
"""
super(SalesBus, self).__init__(settings_file, project_dir, **kwargs)
# init our MySQL DB pool
pool_size = 10
if self.db_conn == None:
# create our db_conn pool if we have the settings to
if settings_file != None:
mysql_settings = self.get_settings('mysql')
if mysql_settings != None:
logging.debug("creating application db_conn pool")
self.db_conn = Queue()
for i in range(pool_size):
self.db_conn.put_nowait(create_db_conn(mysql_settings))
# our mysql settings
# a connection with just a user table defined
mysql = {
"DEBUG": False, ## Not using yet
"CONNECTION": {
"HOST": "127.0.0.1", ## MySQL Host
"PORT": 3306, ## MySQL Post
"USER": "username", ## MySQL User
"PASSWORD": "password", ## MySQL Password
"DATABASE": "database", ## Database Name
"COLLATION": 'utf8', ## Database Collation
},
"TABLES": {
"USER": {
"TABLE_NAME": "user",
"FIELDS": [
'id',
'role',
'email',
'oauth_provider',
'oauth_uid',
'username',
'fullname',
'location',
'change_date',
'create_date',
'thumbnail',
'oauth_session_id',
'oauth_access_token',
'oauth_data',
],
"FIELDS_MUTEABLE": [
'role',
'email',
'oauth_provider',
'oauth_uid',
'username',
'fullname',
'location',
'change_date',
'thumbnail',
'oauth_session_id',
'oauth_access_token',
'oauth_data',
], },
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment