diff --git a/controllers/appadmin.py b/controllers/appadmin.py deleted file mode 100644 index baf5bfbba17705ec08e93f51ee434d20ab44a6bf..0000000000000000000000000000000000000000 --- a/controllers/appadmin.py +++ /dev/null @@ -1,268 +0,0 @@ - -# ########################################################## -# ## make sure administrator is on localhost -# ########################################################### - -import os -import socket -import datetime -import copy -import gluon.contenttype -import gluon.fileutils - -# ## crytical --- make a copy of the environment - -global_env = copy.copy(globals()) -global_env['datetime'] = datetime - -http_host = request.env.http_host.split(':')[0] -remote_addr = request.env.remote_addr -try: - hosts = (http_host, socket.gethostbyname(remote_addr)) -except: - hosts = (http_host, ) -if remote_addr not in hosts: - raise HTTP(400) -if not gluon.fileutils.check_credentials(request): - redirect('/admin') - -response.view = 'appadmin.html' -response.menu = [[T('design'), False, URL('admin', 'default', 'design', - args=[request.application])], [T('db'), False, - URL(r=request, f='index')], [T('state'), False, - URL(r=request, f='state')]] - -# ########################################################## -# ## auxiliary functions -# ########################################################### - - -def get_databases(request): - dbs = {} - for (key, value) in global_env.items(): - cond = False - try: - cond = isinstance(value, GQLDB) - except: - cond = isinstance(value, SQLDB) - if cond: - dbs[key] = value - return dbs - - -databases = get_databases(None) - - -def eval_in_global_env(text): - exec ('_ret=%s' % text, {}, global_env) - return global_env['_ret'] - - -def get_database(request): - if request.args and request.args[0] in databases: - return eval_in_global_env(request.args[0]) - else: - session.flash = T('invalid request') - redirect(URL(r=request, f='index')) - - -def get_table(request): - db = get_database(request) - if len(request.args) > 1 and request.args[1] in db.tables: - return (db, request.args[1]) - else: - session.flash = T('invalid request') - redirect(URL(r=request, f='index')) - - -def get_query(request): - try: - return eval_in_global_env(request.vars.query) - except Exception: - return None - - -# ########################################################## -# ## list all databases and tables -# ########################################################### - - -def index(): - return dict(databases=databases) - - -# ########################################################## -# ## insert a new record -# ########################################################### - - -def insert(): - (db, table) = get_table(request) - form = SQLFORM(db[table]) - if form.accepts(request.vars, session): - response.flash = T('new record inserted') - return dict(form=form) - - -# ########################################################## -# ## list all records in table and insert new record -# ########################################################### - - -def download(): - import os - db = get_database(request) - filename = request.args[1] - - # ## for GAE only ### - - (table, field) = filename.split('.')[:2] - if table in db.tables and field in db[table].fields: - uploadfield = db[table][field].uploadfield - if isinstance(uploadfield, str): - from gluon.contenttype import contenttype - response.headers['Content-Type'] = contenttype(filename) - rows = db(db[table][field] == filename).select() - return rows[0][uploadfield] - - # ## end for GAE ### - - path = os.path.join(request.folder, 'uploads/', filename) - return response.stream(open(path, 'rb')) - - -def csv(): - import gluon.contenttype - response.headers['Content-Type'] = \ - gluon.contenttype.contenttype('.csv') - db = get_database(request) - query = get_query(request) - if not query: - return None - response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ - % tuple(request.vars.query.split('.')[:2]) - return str(db(query).select()) - - -def import_csv(table, file): - table.import_from_csv_file(file) - -def select(): - import re - db = get_database(request) - dbname = request.args[0] - regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') - if request.vars.query: - match = regex.match(request.vars.query) - if match: - request.vars.query = '%s.%s.%s==%s' % (request.args[0], - match.group('table'), match.group('field'), - match.group('value')) - else: - request.vars.query = session.last_query - query = get_query(request) - if request.vars.start: - start = int(request.vars.start) - else: - start = 0 - nrows = 0 - stop = start + 100 - table = None - rows = [] - orderby = request.vars.orderby - if orderby: - orderby = dbname + '.' + orderby - if orderby == session.last_orderby: - if orderby[0] == '~': - orderby = orderby[1:] - else: - orderby = '~' + orderby - session.last_orderby = orderby - session.last_query = request.vars.query - form = FORM(TABLE(TR('Query:', '', INPUT(_style='width:400px', - _name='query', _value=request.vars.query or '', - requires=IS_NOT_EMPTY())), TR('Update:', - INPUT(_name='update_check', _type='checkbox', - value=False), INPUT(_style='width:400px', - _name='update_fields', _value=request.vars.update_fields - or '')), TR('Delete:', INPUT(_name='delete_check', - _class='delete', _type='checkbox', value=False), ''), - TR('', '', INPUT(_type='submit', _value='submit'))), - _action=URL(r=request,args=request.args)) - if request.vars.csvfile != None: - try: - import_csv(db[request.vars.table], - request.vars.csvfile.file) - response.flash = T('data uploaded') - except: - response.flash = T('unable to parse csv file') - if form.accepts(request.vars, formname=None): - regex = re.compile(request.args[0] + '\.(?P<table>\w+)\.id\>0') - match = regex.match(form.vars.query.strip()) - if match: - table = match.group('table') - try: - nrows = db(query).count() - if form.vars.update_check and form.vars.update_fields: - db(query).update(**eval_in_global_env('dict(%s)' - % form.vars.update_fields)) - response.flash = T('%s rows updated', nrows) - elif form.vars.delete_check: - db(query).delete() - response.flash = T('%s rows deleted', nrows) - nrows = db(query).count() - if orderby: - rows = db(query).select(limitby=(start, stop), - orderby=eval_in_global_env(orderby)) - else: - rows = db(query).select(limitby=(start, stop)) - except: - (rows, nrows) = ([], 0) - response.flash = T('Invalid Query') - return dict( - form=form, - table=table, - start=start, - stop=stop, - nrows=nrows, - rows=rows, - query=request.vars.query, - ) - - -# ########################################################## -# ## edit delete one record -# ########################################################### - - -def update(): - (db, table) = get_table(request) - try: - id = int(request.args[2]) - record = db(db[table].id == id).select()[0] - except: - session.flash = T('record does not exist') - redirect(URL(r=request, f='select', args=request.args[:1], - vars=dict(query='%s.%s.id>0' - % tuple(request.args[:2])))) - form = SQLFORM(db[table], record, deletable=True, - linkto=URL(r=request, f='select', - args=request.args[:1]), upload=URL(r=request, - f='download', args=request.args[:1])) - if form.accepts(request.vars, session): - response.flash = T('done!') - redirect(URL(r=request, f='select', args=request.args[:1], - vars=dict(query='%s.%s.id>0' - % tuple(request.args[:2])))) - return dict(form=form) - - -# ########################################################## -# ## get global variables -# ########################################################### - - -def state(): - return dict() - - diff --git a/controllers/configuration.py b/controllers/configuration.py deleted file mode 100644 index ee3184643927e3baf62504496d641bb15ffd256c..0000000000000000000000000000000000000000 --- a/controllers/configuration.py +++ /dev/null @@ -1,92 +0,0 @@ -""" configuration.py - - Controllers/router for the web service cfgSVc - - Relies on Ext.Direct see specification: - http://www.extjs.com/products/extjs/direct.php - - Author: R. Le Gac - $Id$ - -""" - -__version__ = "$Revision$" - -import traceback -import sys - -from applications.mdvPostInstall.modules.cfgsvc import CfgSvc -from gluon.contrib import simplejson as json -from pprint import pprint - - -def index(): - """ controller handling application configuration object - - Act as a router for the cfgSvc service (see Ext;Direct Extjs 3.1.1) - Decode the raw HTTP post request: - {action: "cfgSvc", method: x, data: y, tip: i, type: "rpc"} - - Return a JSON string with the result of the request: - {action: "cfgSvc", method: x, result: y, tip: i, type: "rpc"} - - Otherwise return and HTTP error. - - For more detail on Ext.Direct see specification: - http://www.extjs.com/products/extjs/direct.php - - """ - - debug = False - - # NOTE: the server cfgSvc is start at the beginning - # when building the model (db.py) - - # decode the raw HTTP post - # ExtJs.3.1.1 {action: "xx", method: "y", data: [], type:"rpc", tid:2} - - req = json.loads(request.body.read()) - - if debug: - print "\nSTART CONFIGURATION CONTROLLER:" - pprint(req) - - # receive a list of dictionary for a multi-request - li = [] - if isinstance(req, list): - li.extend(req) - else: - li.append(req) - - for di in li: - # construct the command to be executed - args = di["data"] - cmd = "%s.%s(*args)" % (di["action"], di["method"]) - - if args == None: - cmd = "%s.%s()" % (di["action"], di["method"]) - - # execute the command and return HTTP exception - # when an internal error occurred - try: - res = eval(cmd) - except BaseException, e: - print "Exception in the configuration controller:" - print "-"*72 - traceback.print_exc(file=sys.stdout) - print "-"*72 - raise HTTP(500, e) - - # NOTE: the client expect the following object: - # ExtJs.3.1.1 {action: "xx", method: "y", result: [], type:"rpc", tid:2} - - del di["data"] - di["result"] = res - - if debug: - print "\nCONFIGURATION CONTROLLER RESPONSE IS:" - pprint(li) - print "\nEND OF CONFIGURATION CONTROLLER\n" - - # encode the data as a json string - return json.dumps(li) \ No newline at end of file diff --git a/controllers/database.py b/controllers/database.py deleted file mode 100644 index a35312510e36abcfc18e802251fa42f6e678671f..0000000000000000000000000000000000000000 --- a/controllers/database.py +++ /dev/null @@ -1,61 +0,0 @@ -""" database.py - - Controllers to perform operation on the database - and to retrieve information on the database model. - - Author: R. Le Gac - $Id$ - -""" - -__version__ = "$Revision$" - -import pprint -import traceback -import sys - -from gluon.contrib import simplejson as json -from gluon.http import HTTP - - -def index(): - """ controller to handle database operations. - - All information defining the operation are sent via the POST/GET methods. - It contains steering keyword defining the requested action. - - Return a JSON string when the action is successful. - Otherwise return and HTTP error - - """ - debug = "debug" in request.vars and (request.vars.debug == 'true') - - if debug: - print "\nSTART DATABASE CONTROLLER" - print "Method:", request.env.request_method - print "Arguments:", request.vars - - try: - - # decode the data dictionary - if "data" in request.vars and isinstance(request.vars.data, str): - request.vars.data = json.loads(request.vars.data) - - di = dbSvc.proceed(request.vars) - resp = json.dumps(di) - - except BaseException, e: - print "Exception in the database controller:" - print "-"*72 - traceback.print_exc(file=sys.stdout) - print "-"*72 - raise HTTP(500, e) - - if debug: - print "\nDATABASE CONTROLLER RESPONSE IS:" - pprint.pprint(di) - print "END OF DATABASE CONTROLLER\n" - - return resp - - diff --git a/controllers/default.py b/controllers/default.py deleted file mode 100644 index 9124b7d2ed968041f134047cae63cb86f871a3a3..0000000000000000000000000000000000000000 --- a/controllers/default.py +++ /dev/null @@ -1,109 +0,0 @@ -""" $Id$ """ -import os - -# # uncomment the following if you have defined "auth" and "crud" in models -# def user(): return dict(form=auth()) -# def data(): return dict(form=crud()) -# def download(): return response.download(request,db) -# # tip: use @auth.requires_login, requires_membership, requires_permission - - -def index(): - """Main Controller to run the application. - - SYNOPSIS - http://localhost:8000/application[?options] - - DESCRIPTION - Main controller to launch the application. - Load the extjs librairy and the associated css files. - Load the javascript librairy for the application. - Define the web2py view. - - OPTIONS - - debug - activate the debug mode on the server side. - - script foo - by default the javascript appmain.js is launch. - this option will launch the specified script, i.e. foo.js. - Useful to develop new features and components in the - application framework. - - EXAMPLES - - http://localhost:8000/mdvPostInstall - http://localhost:8000/mdvPostInstall?debug - - """ - - # option debug - debug = False - if "debug" in request.get_vars: - debug = True - - # option script - script = "main" - if "script" in request.get_vars: - script = request.get_vars.script - - if not script.endswith(".js"): - script = '%s.js' % script - - server_path = os.path.join('applications', request.application, 'static', 'script') - if script not in os.listdir(server_path): - return 'Request script "%s" does not exist !!!' % script - - # application path - base = os.path.join(os.path.sep, request.application) - - # css files - csslibs = [os.path.join(base, 'static', 'extjs', 'resources', 'css', 'ext-all.css'), - os.path.join(base, 'static', 'extjs', 'examples', 'shared', 'icons', 'silk.css'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'css', 'GridFilters.css'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'css', 'RangeMenu.css'), -# os.path.join(base, 'static', 'extjs', 'examples', 'shared', 'examples.css'), - ] - - # ext javascript libraries - if debug: - jslibs = [os.path.join(base, 'static', 'extjs', 'adapter', 'ext', 'ext-base-debug.js'), - os.path.join(base, 'static', 'extjs', 'ext-all-debug.js'), -# os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'ux-all-debug.js'), - ] - else: - jslibs = [os.path.join(base, 'static', 'extjs', 'adapter', 'ext', 'ext-base.js'), - os.path.join(base, 'static', 'extjs', 'ext-all.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'menu', 'RangeMenu.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'menu', 'ListMenu.js'), - - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'GridFilters.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'filter', 'Filter.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'filter', 'BooleanFilter.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'filter', 'DateFilter.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'filter', 'ListFilter.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'filter', 'NumericFilter.js'), - os.path.join(base, 'static', 'extjs', 'examples', 'ux', 'gridfilters', 'filter', 'StringFilter.js'), -# os.path.join(base, 'static', 'extjs', 'examples', 'shared', 'examples.js'), - ] - - # application javascript libraries - applibs = [] - server_path = os.path.join('applications', request.application, 'static', 'appjs') - for file in os.listdir(server_path): - if file.endswith(".js"): - applibs.append(os.path.join(base, 'static', 'appjs', file)) - - # main application script - applibs.sort() - applibs.append(os.path.join(base, 'static', 'script', script)) - - # page view - response.view = "applayout.html" - - return dict(clibs=csslibs,\ - jlibs=jslibs,\ - alibs= applibs,\ - appdebug=debug,\ - cfgSvcMethods=cfgSvc._getMethods()) \ No newline at end of file diff --git a/controllers/plugin_dbui.py b/controllers/plugin_dbui.py new file mode 100644 index 0000000000000000000000000000000000000000..a53a887a1eb9631a7ff793a97fcffaf3e2526545 --- /dev/null +++ b/controllers/plugin_dbui.py @@ -0,0 +1,244 @@ +""" plugin_dbui.py + + Controllers expose by the plugin: + + index + database + configuration + + Author: R. Le Gac + $Id$ + +""" + +__version__ = "$Revision$" + + +import os +import traceback +import sys + +from applications.mdvPostInstall.modules.plugin_dbui.cfgsvc import CfgSvc +from gluon.contrib import simplejson as json +from gluon.http import HTTP +from pprint import pprint + + +def index(): + """ Main Controller to run the plugin + + SYNOPSIS + http://localhost:8000/application/plugin_dbui[?options] + + DESCRIPTION + Main controller to launch the plugin. + Load the extjs librairy and the associated css files. + Load the javascript librairy for the plugin. + Define view. + + OPTIONS + + debug + activate the debug mode on the server side. + + script foo + run the javascript foo in the framework defined by the plugin. + The scripts are stored in the directory application/static/script + by default the javascript main.js is launch. + + EXAMPLES + + http://localhost:8000/application/plugin_dbui + http://localhost:8000/application/plugin_dbui?debug + http://localhost:8000/application/plugin_dbui?script=foo&debug + + """ + # paths + base = os.path.join(os.path.sep, request.application) + appjs = os.path.join(base, 'static', 'plugin_dbui', 'appjs') + extjs = os.path.join(base, 'static', 'plugin_dbui', 'extjs') + server_path = os.path.join('applications', request.application) + script_path = os.path.join(server_path, 'static', 'script') + + # option debug + debug = False + if "debug" in request.get_vars: + debug = True + + # option script + script = "main" + if "script" in request.get_vars: + script = request.get_vars.script + + if not script.endswith(".js"): + script = '%s.js' % script + + if script not in os.listdir(script_path): + return 'Request script "%s" does not exist !!!' % script + + # css files + csslibs = [os.path.join(extjs, 'resources', 'css', 'ext-all.css'), + os.path.join(extjs, 'examples', 'shared', 'icons', 'silk.css'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'css', 'GridFilters.css'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'css', 'RangeMenu.css'), +# os.path.join(extjs, 'examples', 'shared', 'examples.css'), + ] + + # javascript libraries + if debug: + jslibs = [os.path.join(extjs, 'adapter', 'ext', 'ext-base-debug.js'), + os.path.join(extjs, 'ext-all-debug.js'), +# os.path.joinextjs, 'examples', 'ux', 'ux-all-debug.js'), + ] + else: + jslibs = [os.path.join(extjs, 'adapter', 'ext', 'ext-base.js'), + os.path.join(extjs, 'ext-all.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'menu', 'RangeMenu.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'menu', 'ListMenu.js'), + + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'GridFilters.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'filter', 'Filter.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'filter', 'BooleanFilter.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'filter', 'DateFilter.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'filter', 'ListFilter.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'filter', 'NumericFilter.js'), + os.path.join(extjs, 'examples', 'ux', 'gridfilters', 'filter', 'StringFilter.js'), +# os.path.join(extjs, 'examples', 'shared', 'examples.js'), + ] + + # plugin javascript libraries + applibs = [] + for file in os.listdir(os.path.join(server_path, 'static', 'plugin_dbui', 'appjs')): + if file.endswith(".js"): + applibs.append(os.path.join(appjs, file)) + + # main application script + applibs.sort() + applibs.append(os.path.join(base, 'static', 'script', script)) + + # page view + response.view = "plugin_dbui.html" + + return dict(clibs=csslibs,\ + jlibs=jslibs,\ + alibs= applibs,\ + appdebug=debug,\ + cfgSvcMethods=cfgSvc._getMethods()) + + +def database(): + """ Controllers to perform operation on the database. + Act as a bridge between the web browser and the database service. + + All information defining the operation are sent via the POST/GET methods. + It contains steering keyword defining the requested action. + + Return a JSON string when the action is successful. + Otherwise return and HTTP error + + """ + debug = "debug" in request.vars and (request.vars.debug == 'true') + + if debug: + print "\nSTART DATABASE CONTROLLER" + print "Method:", request.env.request_method + print "Arguments:", request.vars + + try: + + # decode the data dictionary + if "data" in request.vars and isinstance(request.vars.data, str): + request.vars.data = json.loads(request.vars.data) + + di = dbSvc.proceed(request.vars) + resp = json.dumps(di) + + except BaseException, e: + print "Exception in the database controller:" + print "-"*72 + traceback.print_exc(file=sys.stdout) + print "-"*72 + raise HTTP(500, e) + + if debug: + print "\nDATABASE CONTROLLER RESPONSE IS:" + pprint(di) + print "END OF DATABASE CONTROLLER\n" + + return resp + + +def configuration(): + """ Controllers/router for the web service cfgSVc + Act as a bridge between the web browser and the configuration service. + + Relies on Ext.Direct see specification: + http://www.extjs.com/products/extjs/direct.php + + Act as a router for the cfgSvc service (see Ext.Direct Extjs 3.1.1) + Decode the raw HTTP post request: + {action: "cfgSvc", method: x, data: y, tip: i, type: "rpc"} + + Return a JSON string with the result of the request: + {action: "cfgSvc", method: x, result: y, tip: i, type: "rpc"} + + Otherwise return and HTTP error. + + For more detail on Ext.Direct see specification: + http://www.extjs.com/products/extjs/direct.php + + + """ + debug = "debug" in request.vars and (request.vars.debug == 'true') + + # NOTE: the server cfgSvc is start at the beginning + # when building the model (db.py) + + # decode the raw HTTP post + # ExtJs.3.1.1 {action: "xx", method: "y", data: [], type:"rpc", tid:2} + + req = json.loads(request.body.read()) + + if debug: + print "\nSTART CONFIGURATION CONTROLLER:" + pprint(req) + + # receive a list of dictionary for a multi-request + li = [] + if isinstance(req, list): + li.extend(req) + else: + li.append(req) + + for di in li: + # construct the command to be executed + args = di["data"] + cmd = "%s.%s(*args)" % (di["action"], di["method"]) + + if args == None: + cmd = "%s.%s()" % (di["action"], di["method"]) + + # execute the command and return HTTP exception + # when an internal error occurred + try: + res = eval(cmd) + except BaseException, e: + print "Exception in the configuration controller:" + print "-"*72 + traceback.print_exc(file=sys.stdout) + print "-"*72 + raise HTTP(500, e) + + # NOTE: the client expect the following object: + # ExtJs.3.1.1 {action: "xx", method: "y", result: [], type:"rpc", tid:2} + + del di["data"] + di["result"] = res + + if debug: + print "\nCONFIGURATION CONTROLLER RESPONSE IS:" + pprint(li) + print "\nEND OF CONFIGURATION CONTROLLER\n" + + # encode the data as a json string + return json.dumps(li) \ No newline at end of file