Skip to content

Commit

Permalink
make gengine pluggable into other pyramid projects
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcel committed Apr 1, 2015
1 parent 895661b commit a181814
Show file tree
Hide file tree
Showing 10 changed files with 164 additions and 71 deletions.
6 changes: 5 additions & 1 deletion alembic/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@

# add your model's MetaData object here
# for 'autogenerate' support
from gengine.models import Base
from gengine.metadata import init_session,init_declarative_base
init_session()
init_declarative_base()

from gengine.metadata import Base
target_metadata = Base.metadata
# target_metadata = None

Expand Down
4 changes: 3 additions & 1 deletion gengine/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ def main(global_config, **settings):

config.include("pyramid_tm")

from gengine.models import init_db
from gengine.metadata import init_session, init_declarative_base, init_db
init_session()
init_declarative_base()
init_db(engine)

config.include('pyramid_chameleon')
Expand Down
39 changes: 39 additions & 0 deletions gengine/flask_static/admin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
jQuery().ready(function($) {
var defaultcall = "progress";

var fields=["userid","variable","value","key","achievementid","level",
"lat","lon","friends","groups","timezone","country","region","city"];

var api_funcs = {
"progress" : {
"fields":["userid"],
"url":"/progress/{userid}",
"method":"GET"
},
"increase_value" : {
"fields":["variable","userid","value","key"],
"url":"/increase_value/{variable}/{userid}{/key}",
"method":"POST",
"postparams":["value"]
},
"add_or_update_user" : {
"fields":["userid","lat","lon","friends","groups","timezone","country","region","city"],
"url":"/add_or_update_user/{userid}",
"method":"POST",
"postparams":["lat","lon","friends","groups","timezone","country","region","city"]
},
"delete_user" : {
"fields":["userid"],
"url":"/delete_user/{userid}",
"method":"DELETE"
},
"achievement_level" : {
"fields":["achievementid","level"],
"url":"/achievement/{achievementid}/level/{level}",
"method":"GET"
}
};

setupAPIForm($,defaultcall,fields,api_funcs);

});
File renamed without changes.
40 changes: 9 additions & 31 deletions gengine/static/admin.js → gengine/flask_static/api.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
jQuery().ready(function($) {
var setupAPIForm = function($, defaultcall, fields, api_funcs) {

var defaultcall = "progress";
var fields=["userid","variable","value","key","achievementid","level",
"lat","lon","friends","groups","timezone","country","region","city"];
var container_fields = {};

for(var i=0; i<fields.length; i++) {
Expand Down Expand Up @@ -48,30 +45,13 @@ jQuery().ready(function($) {
api_settings_postparams = postparams;
};

var activationfuncs = {
"progress" : function() {
setActiveFields(["userid"]);
setURL("/progress/{userid}","GET");
},
"increase_value" : function() {
setActiveFields(["variable","userid","value","key"]);
setURL("/increase_value/{variable}/{userid}{/key}","POST",["value"]);
},
"add_or_update_user" : function() {
setActiveFields(["userid","lat","lon","friends","groups","timezone","country","region","city"]);
setURL("/add_or_update_user/{userid}",
"POST",
["lat","lon","friends","groups","timezone","country","region","city"]);
},
"delete_user" : function() {
setActiveFields(["userid"]);
setURL("/delete_user/{userid}","DELETE",[]);
},
"achievement_level" : function() {
setActiveFields(["achievementid","level"]);
setURL("/achievement/{achievementid}/level/{level}","GET");
},
};
var activationfuncs = {};
$.each(api_funcs,function(k,f) {
activationfuncs[k] = function() {
setActiveFields(f["fields"]);
setURL(f["url"],f["method"],f["postparams"]);
};
});

//from http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
var syntaxHighlight = function(json) {
Expand Down Expand Up @@ -140,6 +120,4 @@ jQuery().ready(function($) {
//activate default api call
call_select.val(defaultcall);
activationfuncs[defaultcall]();


});
};
68 changes: 53 additions & 15 deletions gengine/flaskadmin.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,66 @@
from flask.globals import request
from wtforms.form import Form
import pkg_resources
from flask.helpers import send_from_directory
import jinja2

flaskadminapp=None
admin=None

def get_package_folder(uri):
from pyramid.path import AssetResolver
project,folder = uri.split(":",1)
a = AssetResolver(project)
resolver = a.resolve(folder)
folder = resolver.abspath()
return folder

def init_flaskadmin(urlprefix="",secret="fKY7kJ2xSrbPC5yieEjV"):
def get_static_view(folder,flaskadminapp):
folder=get_package_folder(folder)

def send_static_file(filename):
cache_timeout = flaskadminapp.get_send_file_max_age(filename)
return send_from_directory(folder, filename, cache_timeout=cache_timeout)

return send_static_file

def init_flaskadmin(urlprefix="",secret="fKY7kJ2xSrbPC5yieEjV",override_admin=None,override_flaskadminapp=None):
global flaskadminapp, admin
flaskadminapp = Flask(__name__)
flaskadminapp.debug=True
flaskadminapp.secret_key = secret
flaskadminapp.config.update(dict(
PREFERRED_URL_SCHEME = 'https'
))

if not override_flaskadminapp:
flaskadminapp = Flask(__name__)
flaskadminapp.debug=True
flaskadminapp.secret_key = secret
flaskadminapp.config.update(dict(
PREFERRED_URL_SCHEME = 'https'
))
else:
flaskadminapp = override_flaskadminapp

# lets add our template directory
my_loader = jinja2.ChoiceLoader([
flaskadminapp.jinja_loader,
jinja2.FileSystemLoader(get_package_folder("gengine:templates")),
])
flaskadminapp.jinja_loader = my_loader

flaskadminapp.add_url_rule('/static_gengine/<path:filename>',
endpoint='static_gengine',
view_func=get_static_view('gengine:flask_static',flaskadminapp))

@flaskadminapp.context_processor
def inject_version():
return { "gamification_engine_version" : pkg_resources.get_distribution("gamification-engine").version }

admin = Admin(flaskadminapp,
name="Gamification Engine - Admin Control Panel",
base_template='admin_layout.html',
url=urlprefix+"/admin"
)

if not override_admin:
admin = Admin(flaskadminapp,
name="Gamification Engine - Admin Control Panel",
base_template='admin_layout.html',
url=urlprefix+"/admin"
)
else:
admin = override_admin

admin.add_view(ModelViewAchievement(DBSession, category="Rules"))
admin.add_view(ModelViewGoal(DBSession, category="Rules"))
admin.add_view(ModelView(AchievementProperty, DBSession, category="Rules"))
Expand Down Expand Up @@ -136,7 +175,6 @@ class ClearCacheForm(Form):
clear_check = BooleanField(label="Delete all caches?")

class MaintenanceView(BaseView):

@expose('/',methods=('GET','POST',))
def index(self):
self._template_args['msgs'] = []
Expand All @@ -148,4 +186,4 @@ def index(self):
clear_all_caches()
self._template_args['msgs'].append("All caches cleared!")
return self.render(template="admin_maintenance.html")


37 changes: 37 additions & 0 deletions gengine/metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from sqlalchemy.orm.session import Session, sessionmaker
import transaction
from sqlalchemy.orm.scoping import scoped_session
from zope.sqlalchemy.datamanager import ZopeTransactionExtension
from sqlalchemy.ext.declarative.api import declarative_base

class MySession(Session):
"""This allow us to use the flask-admin sqla extension, which uses DBSession.commit() rather than transaction.commit()"""
def commit(self,*args,**kw):
transaction.commit(*args,**kw)

def rollback(self,*args,**kw):
transaction.abort(*args,**kw)

DBSession=None

def init_session(override_session=None):
global DBSession
if override_session:
DBSession = override_session
else:
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension(), class_=MySession))

Base=None

def init_declarative_base(override_base=None):
global Base
if override_base:
Base=override_base
else:
Base = declarative_base()

def init_db(engine):
DBSession.configure(bind=engine)
Base.metadata.bind = engine


17 changes: 1 addition & 16 deletions gengine/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,7 @@
import hashlib
import warnings


class MySession(Session):
"""This allow us to use the flask-admin sqla extension, which uses DBSession.commit() rather than transaction.commit()"""
def commit(self,*args,**kw):
transaction.commit(*args,**kw)

def rollback(self,*args,**kw):
transaction.abort(*args,**kw)

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension(), class_=MySession))
Base = declarative_base()
from gengine.metadata import Base, DBSession

try:
cache_general = get_region('general')
Expand All @@ -63,10 +53,6 @@ def rollback(self,*args,**kw):

warnings.warn("Warning: cache objects are in memory, are you creating docs?")

def init_db(engine):
DBSession.configure(bind=engine)
Base.metadata.bind = engine

t_users = Table("users", Base.metadata,
Column('id', ty.BigInteger, primary_key = True),
Column("lat", ty.Float(Precision=64), nullable=True),
Expand Down Expand Up @@ -1167,7 +1153,6 @@ def insert_variable_for_property(mapper,connection,target):
variable.group = "day"
DBSession.add(variable)


#some query helpers

def calc_distance(latlong1, latlong2):
Expand Down
21 changes: 15 additions & 6 deletions gengine/scripts/initializedb.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@
from pyramid.scripts.common import parse_vars
import pyramid_dogpile_cache
from pyramid.config import Configurator
from gengine.models import AchievementProperty, AchievementReward




def usage(argv):
Expand Down Expand Up @@ -45,9 +42,19 @@ def main(argv=sys.argv):
config = Configurator(settings=settings)
pyramid_dogpile_cache.includeme(config)

from ..models import (
DBSession,
from ..metadata import (
init_session,
init_declarative_base
)
init_session()
init_declarative_base()

from ..metadata import (
Base,
DBSession
)

from ..models import (
Achievement,
Goal,
Variable,
Expand All @@ -56,7 +63,9 @@ def main(argv=sys.argv):
TranslationVariable,
Translation,
Property,
Reward
Reward,
AchievementProperty,
AchievementReward
)

DBSession.configure(bind=engine)
Expand Down
3 changes: 2 additions & 1 deletion gengine/templates/admin_layout.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,6 @@
{% block tail %}
{{ super() }}
<div class="container" id="footer">Gamification-Engine {{gamification_engine_version}} - Built with &#9825; at Gamification-Software.com &copy; 2015</div>
<script type="text/javascript" src="{{ url_for('static', filename='admin.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static_gengine', filename='api.js') }}"></script>
<script type="text/javascript" src="{{ url_for('static_gengine', filename='admin.js') }}"></script>
{% endblock %}

0 comments on commit a181814

Please sign in to comment.