def run_controller_in(controller, function, environment): """ Runs the controller.function() (for the app specified by the current folder). It tries pre-compiled controller_function.pyc first before compiling it. """ # if compiled should run compiled! folder = environment["request"].folder path = pjoin(folder, "compiled") badc = "invalid controller (%s/%s)" % (controller, function) badf = "invalid function (%s/%s)" % (controller, function) if os.path.exists(path): filename = pjoin(path, "controllers.%s.%s.pyc" % (controller, function)) if not os.path.exists(filename): ### for backward compatibility filename = pjoin(path, "controllers_%s_%s.pyc" % (controller, function)) ### end for backward compatibility if not os.path.exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf) restricted(read_pyc(filename), environment, layer=filename) elif function == "_TEST": # TESTING: adjust the path to include site packages from settings import global_settings from admin import abspath, add_path_first paths = (global_settings.gluon_parent, abspath("site-packages", gluon=True), abspath("gluon", gluon=True), "") [add_path_first(path) for path in paths] # TESTING END filename = pjoin(folder, "controllers/%s.py" % controller) if not os.path.exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc) environment["__symbols__"] = environment.keys() code = read_file(filename) code += TEST_CODE restricted(code, environment, layer=filename) else: filename = pjoin(folder, "controllers/%s.py" % controller) if not os.path.exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc) code = read_file(filename) exposed = find_exposed_functions(code) if not function in exposed: raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf) code = "%s\nresponse._vars=response._caller(%s)\n" % (code, function) if is_gae: layer = filename + ":" + function code = getcfs(layer, filename, lambda: compile2(code, layer)) restricted(code, environment, filename) response = environment["response"] vars = response._vars if response.postprocessing: vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars) if isinstance(vars, unicode): vars = vars.encode("utf8") elif hasattr(vars, "xml") and callable(vars.xml): vars = vars.xml() return vars
def template(): if request.vars.py: filename = os.path.join(request.folder, 'static/resources/application/report/python/nerva2py', 'sample.py') return CODE(read_file(filename), language="python").xml() else: filename = os.path.join(request.folder, 'static/resources/application/report/python', 'sample.xml') xdata = read_file(filename) response.headers['Content-Type']='text/xml' return xdata
def fix_db(filename): params = dict(session.app['params']) content = read_file(filename, 'r') if 'auth_user' in session.app['tables']: auth_user = make_table('auth_user', session.app['table_auth_user']) content = content.replace('sqlite://storage.sqlite', params['database_uri']) content = content.replace('auth.define_tables()', auth_user + 'auth.define_tables(migrate = settings.migrate)') content += """ mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login """ if params['login_method'] == 'janrain': content += """ from gluon.contrib.login_methods.rpx_account import RPXAccount auth.settings.actions_disabled=['register','change_password', 'request_reset_password'] auth.settings.login_form = RPXAccount(request, api_key = settings.login_config.split(':')[-1], domain = settings.login_config.split(':')[0], url = "http://%s/%s/default/user/login" % (request.env.http_host,request.application)) """ write_file(filename, content, 'w')
def getResource(): if request.vars.file_name: rdir = str(request.vars.file_name).split("/")[0] if rdir=="backup": file_name = os.path.join(request.folder, 'static', str(request.vars.file_name)) elif rdir in("docs","download","report"): file_name = os.path.join(request.folder, 'static/resources', str(request.vars.file_name)) else: return "Valid directories: docs, download, report" if request.vars.lang and session._language and session._language!="en": file_name+='_'+str(session._language) if request.vars.file_type: file_name+='.'+str(request.vars.file_type) else: file_name+='.html' if not os.path.isfile(file_name): if request.vars.lang and session._language and session._language!="en": file_name = str(file_name).replace('_'+str(session._language), "") if not os.path.isfile(file_name): return T('Missing file...') else: return T('Missing file...') if request.vars.content: if request.vars.content=="view": response.view="../"+file_name[file_name.find("static"):] return dict() elif request.vars.content=="xml": response.headers['Content-Type']='text/xml' else: response.headers['Content-Type']=request.vars.content if request.vars.file_type: response.headers['Content-Disposition'] = 'attachment;filename="'+str(request.vars.file_name).split('/')[len(str(request.vars.file_name).split('/'))-1]+'.'+str(request.vars.file_type)+'"' return read_file(file_name) else: return T('Missing document...')
def show_codefile(): fpath = request.vars.fpath if request.vars.fpath else "controllers" lang = request.vars.language if request.vars.fpath else "python" if request.vars.fname: return CODE(read_file(os.path.join(request.folder, fpath, request.vars.fname)), language=lang).xml() else: return "Missing file..."
def getcfs(key, filename, filter=None): """ Caches the *filtered* file `filename` with `key` until the file is modified. Args: key(str): the cache key filename: the file to cache filter: is the function used for filtering. Normally `filename` is a .py file and `filter` is a function that bytecode compiles the file. In this way the bytecode compiled file is cached. (Default = None) This is used on Google App Engine since pyc files cannot be saved. """ try: t = stat(filename).st_mtime except OSError: return filter() if callable(filter) else '' cfs_lock.acquire() item = cfs.get(key, None) cfs_lock.release() if item and item[0] == t: return item[1] if not callable(filter): data = read_file(filename) else: data = filter() cfs_lock.acquire() cfs[key] = (t, data) cfs_lock.release() return data
def hash_file(filename): data = read_file(filename) file_hash = md5_hash(data) path = apath(filename, r=request) saved_on = os.stat(path)[stat.ST_MTIME] size = os.path.getsize(path) return dict(saved_on=saved_on, file_hash=file_hash, size=size)
def download(): """ used to download uploaded files """ import gluon.contenttype app = request.application filename = request.args[0] response.headers['Content-Type'] = \ gluon.contenttype.contenttype(filename) return read_file('applications/%s/uploads/%s' % (app, filename), 'rb')
def exec_template(self, path): """ Execute the template """ from gluon.fileutils import read_file from gluon.restricted import restricted code = read_file(path) restricted(code, layer=path) return
def app_create(app, request, force=False, key=None, info=False): """Create a copy of welcome.w2p (scaffolding) app Args: app(str): application name request: the global request object """ path = apath(app, request) if not os.path.exists(path): try: os.mkdir(path) except: if info: return False, traceback.format_exc(sys.exc_info) else: return False elif not force: if info: return False, "Application exists" else: return False try: w2p_unpack("welcome.w2p", path) for subfolder in [ "models", "views", "controllers", "databases", "modules", "cron", "errors", "sessions", "cache", "languages", "static", "private", "uploads", ]: subpath = os.path.join(path, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(path, "models", "db.py") if os.path.exists(db): data = read_file(db) data = data.replace("<your secret key>", "sha512:" + (key or web2py_uuid())) write_file(db, data) if info: return True, None else: return True except: rmtree(path) if info: return False, traceback.format_exc(sys.exc_info) else: return False
def read_pyc(filename): """ Read the code inside a bytecode compiled file if the MAGIC number is compatible :returns: a code object """ data = read_file(filename, 'rb') if not is_gae and data[:4] != imp.get_magic(): raise SystemError('compiled code is incompatible') return marshal.loads(data[8:])
def exec_template(self, path): """ Execute the template """ #from gluon.compileapp import build_environment from gluon.fileutils import read_file from gluon.restricted import restricted #environment = build_environment(request, response, session) code = read_file(path) #restricted(code, environment, layer=path) restricted(code, layer=path) return
def lay_content_id(): """ Layer content from as stored file for given id :return: layer """ from gluon import fileutils id = request.vars.id filename = db(db.layers.id == id).select('filename') content = fileutils.read_file(filename, mode='r') return dict(content=content)
def start(): if 'sdist' in sys.argv: tar('gluon/env.tar', ['applications', 'VERSION', 'extras/icons/splashlogo.gif']) setup( name='web2py', version=read_file("VERSION").split()[1], description="""full-stack framework for rapid development and prototyping of secure database-driven web-based applications, written and programmable in Python.""", long_description=""" Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, sybase and Google App Engine via a Database Abstraction Layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download streaming of very large files, and always backward compatible. """, author='Massimo Di Pierro', author_email='*****@*****.**', license='http://web2py.com/examples/default/license', classifiers=["Development Status :: 5 - Production/Stable"], url='http://web2py.com', platforms='Windows, Linux, Mac, Unix,Windows Mobile', packages=[ 'gluon', 'gluon/contrib', 'gluon/contrib/gateways', 'gluon/contrib/login_methods', 'gluon/contrib/markdown', 'gluon/contrib/markmin', 'gluon/contrib/memcache', 'gluon/contrib/fpdf', 'gluon/contrib/pymysql', 'gluon/contrib/pyrtf', 'gluon/contrib/pysimplesoap', 'gluon/contrib/plural_rules', 'gluon/contrib/minify', 'gluon/contrib/pyaes', 'gluon/contrib/pyuca', 'gluon/tests', ] + setuptools.find_packages(), package_data={'gluon': ['env.tar']}, cmdclass={'submodule': UpdateSubmodules}, # scripts=['w2p_apps', 'w2p_run', 'w2p_clone'], )
def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ request = current.request folder = request.folder c = request.controller # f = environment['request'].function response = current.response path = pjoin(folder, 'models') cpath = pjoin(folder, 'compiled') compiled = os.path.exists(cpath) if PY2: if compiled: models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0), model_cmp) else: models = sorted(listdir(path, '^\w+\.py$', 0, sort=False), model_cmp_sep) else: if compiled: models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0), key=lambda f: '{0:03d}'.format(f.count('.')) + f) else: models = sorted( listdir(path, '^\w+\.py$', 0, sort=False), key=lambda f: '{0:03d}'.format(f.count(os.path.sep)) + f) models_to_run = None for model in models: if response.models_to_run != models_to_run: regex = models_to_run = response.models_to_run[:] if isinstance(regex, list): regex = re_compile('|'.join(regex)) if models_to_run: if compiled: n = len(cpath) + 8 fname = model[n:-4].replace('.', '/') + '.py' else: n = len(path) + 1 fname = model[n:].replace(os.path.sep, '/') if not regex.search(fname) and c != 'appadmin': continue elif compiled: f = lambda: read_pyc(model) else: f = lambda: compile2(read_file(model), model) ccode = getcfs(model, model, f) restricted(ccode, environment, layer=model)
def read_pyc(filename): """ Read the code inside a bytecode compiled file if the MAGIC number is compatible Returns: a code object """ data = read_file(filename, 'rb') if not global_settings.web2py_runtime_gae and \ not data.startswith(imp.get_magic()): raise SystemError('compiled code is incompatible') return marshal.loads(data[MARSHAL_HEADER_SIZE:])
def compile_models(folder): """ Compiles all the models in the application specified by `folder` """ path = pjoin(folder, 'models') for fname in listdir(path, REGEX_MODEL_PATH, followlinks=True): data = read_file(pjoin(path, fname)) modelfile = 'models.' + fname.replace(os.sep, '.') filename = pjoin(folder, 'compiled', modelfile) mktree(filename) write_file(filename, data) save_pyc(filename) os.unlink(filename)
def compile_models(folder): """ Compiles all the models in the application specified by `folder` """ path = pjoin(folder, 'models') for fname in listdir(path, REGEX_MODEL_PATH): data = read_file(pjoin(path, fname)) modelfile = 'models.'+fname.replace(os.sep, '.') filename = pjoin(folder, 'compiled', modelfile) mktree(filename) write_file(filename, data) save_pyc(filename) os.unlink(filename)
def compile_models(folder): """ Compiles all the models in the application specified by `folder` """ path = pjoin(folder, 'models') for file in listdir(path, '.+\.py$'): data = read_file(pjoin(path, file)) filename = pjoin(folder, 'compiled', 'models', file) mktree(filename) write_file(filename, data) save_pyc(filename) os.unlink(filename)
def main(): usage = "python anyserver.py -s tornado -i 127.0.0.1 -p 8000 -l -P" try: version = read_file('VERSION') except IOError: version = '' parser = optparse.OptionParser(usage, None, optparse.Option, version) parser.add_option('-l', '--logging', action='store_true', default=False, dest='logging', help='log into httpserver.log') parser.add_option('-P', '--profiler', default=False, dest='profiler', help='profiler filename') servers = ', '.join(x for x in dir(Servers) if not x[0] == '_') parser.add_option('-s', '--server', default='rocket', dest='server', help='server name (%s)' % servers) parser.add_option('-i', '--ip', default='127.0.0.1', dest='ip', help='ip address') parser.add_option('-p', '--port', default='8000', dest='port', help='port number') parser.add_option('-w', '--workers', default='', dest='workers', help='number of workers number') (options, args) = parser.parse_args() print 'starting %s on %s:%s...' % (options.server, options.ip, options.port) run(options.server, options.ip, options.port, logging=options.logging, profiler=options.profiler)
def app_create(app, request, force=False, key=None, info=False): """ Create a copy of welcome.w2p (scaffolding) app Parameters ---------- app: application name request: the global request object """ path = apath(app, request) if not os.path.exists(path): try: os.mkdir(path) except: if info: return False, traceback.format_exc(sys.exc_info) else: return False elif not force: if info: return False, "Application exists" else: return False try: w2p_unpack('welcome.w2p', path) for subfolder in [ 'models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'cache', 'languages', 'static', 'private', 'uploads']: subpath = os.path.join(path, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(path, 'models', 'db.py') if os.path.exists(db): data = read_file(db) data = data.replace('<your secret key>', 'sha512:' + (key or web2py_uuid())) write_file(db, data) if info: return True, None else: return True except: rmtree(path) if info: return False, traceback.format_exc(sys.exc_info) else: return False
def compile_models(folder): """ Compiles all the models in the application specified by `folder` """ path = pjoin(folder, "models") for fname in listdir(path, ".+\.py$"): data = read_file(pjoin(path, fname)) modelfile = "models." + fname.replace(os.path.sep, ".") filename = pjoin(folder, "compiled", modelfile) mktree(filename) write_file(filename, data) save_pyc(filename) os.unlink(filename)
def start(): if 'sdist' in sys.argv: tar('gluon/env.tar', ['applications', 'VERSION', 'extras/icons/splashlogo.gif']) setup(name='web2py', version=read_file("VERSION").split()[1], description="""full-stack framework for rapid development and prototyping of secure database-driven web-based applications, written and programmable in Python.""", long_description=""" Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, sybase and Google App Engine via a Database Abstraction Layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download streaming of very large files, and always backward compatible. """, author='Massimo Di Pierro', author_email='*****@*****.**', license='http://web2py.com/examples/default/license', classifiers=["Development Status :: 5 - Production/Stable"], url='http://web2py.com', platforms='Windows, Linux, Mac, Unix,Windows Mobile', packages=['gluon', 'gluon/contrib', 'gluon/contrib/gateways', 'gluon/contrib/login_methods', 'gluon/contrib/markdown', 'gluon/contrib/markmin', 'gluon/contrib/memcache', 'gluon/contrib/fpdf', 'gluon/contrib/pymysql', 'gluon/contrib/pyrtf', 'gluon/contrib/pysimplesoap', 'gluon/contrib/pg8000', 'gluon/contrib/plural_rules', 'gluon/contrib/minify', 'gluon/contrib/pyaes', 'gluon/contrib/pyuca', 'gluon/tests', ], package_data={'gluon': ['env.tar']}, # scripts=['w2p_apps', 'w2p_run', 'w2p_clone'], )
def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ request = current.request folder = request.folder c = request.controller # f = environment['request'].function response = current.response path = pjoin(folder, 'models') cpath = pjoin(folder, 'compiled') compiled = exists(cpath) if PY2: if compiled: models = sorted(listdir(cpath, REGEX_COMPILED_MODEL, 0), model_cmp) else: models = sorted(listdir(path, REGEX_MODEL, 0, sort=False), model_cmp_sep) else: if compiled: models = sorted(listdir(cpath, REGEX_COMPILED_MODEL, 0), key=lambda f: '{0:03d}'.format(f.count('.')) + f) else: models = sorted(listdir(path, REGEX_MODEL, 0, sort=False), key=lambda f: '{0:03d}'.format(f.count(os.sep)) + f) models_to_run = None for model in models: if response.models_to_run != models_to_run: regex = models_to_run = response.models_to_run[:] if isinstance(regex, list): regex = re_compile('|'.join(regex)) if models_to_run: if compiled: n = len(cpath)+8 fname = model[n:-4].replace('.', '/')+'.py' else: n = len(path)+1 fname = model[n:].replace(os.sep, '/') if not regex.search(fname) and c != 'appadmin': continue elif compiled: f = lambda: read_pyc(model) else: f = lambda: compile2(read_file(model), model) ccode = getcfs(model, model, f) restricted(ccode, environment, layer=model)
def app_create(app, request, force=False, key=None, info=False): """Create a copy of welcome.w2p (scaffolding) app Args: app(str): application name request: the global request object """ path = apath(app, request) if not os.path.exists(path): try: os.mkdir(path) except: if info: return False, traceback.format_exc(sys.exc_info) else: return False elif not force: if info: return False, "Application exists" else: return False try: w2p_unpack('welcome.w2p', path) for subfolder in [ 'models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'cache', 'languages', 'static', 'private', 'uploads' ]: subpath = os.path.join(path, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(path, 'models', 'db.py') if os.path.exists(db): data = read_file(db) data = data.replace('<your secret key>', 'sha512:' + (key or web2py_uuid())) write_file(db, data) if info: return True, None else: return True except: rmtree(path) if info: return False, traceback.format_exc(sys.exc_info) else: return False
def compile_controllers(folder): """ Compiles all the controllers in the application specified by `folder` """ path = pjoin(folder, 'controllers') for fname in listdir(path, REGEX_CONTROLLER, followlinks=True): data = read_file(pjoin(path, fname)) exposed = find_exposed_functions(data) for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % \ function filename = pjoin(folder, 'compiled', 'controllers.%s.%s.py' % (fname[:-3], function)) write_file(filename, command) save_pyc(filename) os.unlink(filename)
def compile_controllers(folder): """ Compiles all the controllers in the application specified by `folder` """ path = pjoin(folder, 'controllers') for fname in listdir(path, REGEX_CONTROLLER): data = read_file(pjoin(path, fname)) exposed = find_exposed_functions(data) for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % \ function filename = pjoin(folder, 'compiled', 'controllers.%s.%s.py' % (fname[:-3], function)) write_file(filename, command) save_pyc(filename) os.unlink(filename)
def compile_controllers(folder): """ Compiles all the controllers in the application specified by `folder` """ path = pjoin(folder, "controllers") for fname in listdir(path, ".+\.py$"): ### why is this here? save_pyc(pjoin(path, file)) data = read_file(pjoin(path, fname)) exposed = find_exposed_functions(data) for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % function filename = pjoin(folder, "compiled", "controllers.%s.%s.py" % (fname[:-3], function)) write_file(filename, command) save_pyc(filename) os.unlink(filename)
def create_report(src, orient, output): rpt = Report(orientation=orient) if src=="xml": filename = os.path.join(request.folder, 'static/resources/application/report/python', 'sample.xml') xdata = read_file(filename) rpt.loadDefinition(xdata) else: rpt = sample_report(rpt) rpt.createReport() if output=="pdf": response.headers['Content-Type']='application/pdf' return rpt.save2Pdf() elif output=="html": return rpt.save2Html() else: response.headers['Content-Type']='text/xml' return rpt.save2Xml()
def deploy(): regex = re.compile('^\w+$') apps = sorted( file for file in os.listdir(apath(r=request)) if regex.match(file)) form = SQLFORM.factory( Field('appcfg', default=GAE_APPCFG, label=T('Path to appcfg.py'), requires=EXISTS(error_message=T('file not found'))), Field('google_application_id', requires=IS_MATCH( '[\w\-]+'), label=T('Google Application Id')), Field('applications', 'list:string', requires=IS_IN_SET(apps, multiple=True), label=T('web2py apps to deploy')), Field('email', requires=IS_EMAIL(), label=T('GAE Email')), Field('password', 'password', requires=IS_NOT_EMPTY(), label=T('GAE Password'))) cmd = output = errors = "" if form.accepts(request, session): try: kill() except: pass ignore_apps = [item for item in apps if not item in form.vars.applications] regex = re.compile('\(applications/\(.*') yaml = apath('../app.yaml', r=request) if not os.path.exists(yaml): example = apath('../app.example.yaml', r=request) shutil.copyfile(example, yaml) data = read_file(yaml) data = re.sub('application:.*', 'application: %s' % form.vars.google_application_id, data) data = regex.sub( '(applications/(%s)/.*)|' % '|'.join(ignore_apps), data) write_file(yaml, data) path = request.env.applications_parent cmd = '%s --email=%s --passin update %s' % \ (form.vars.appcfg, form.vars.email, path) p = cache.ram('gae_upload', lambda s=subprocess, c=cmd: s.Popen(c, shell=True, stdin=s.PIPE, stdout=s.PIPE, stderr=s.PIPE, close_fds=True), -1) p.stdin.write(form.vars.password + '\n') fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) fcntl.fcntl(p.stderr.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) return dict(form=form, command=cmd)
def compile_controllers(folder): """ Compiles all the controllers in the application specified by `folder` """ path = pjoin(folder, 'controllers') for fname in listdir(path, '.+\.py$'): ### why is this here? save_pyc(pjoin(path, file)) data = read_file(pjoin(path, fname)) exposed = regex_expose.findall(data) for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % \ function filename = pjoin(folder, 'compiled', 'controllers.%s.%s.py' % (fname[:-3], function)) write_file(filename, command) save_pyc(filename) os.unlink(filename)
def main(): usage = "python anyserver.py -s tornado -i 127.0.0.1 -p 8000 -l -P" try: version = read_file("VERSION") except IOError: version = "" parser = optparse.OptionParser(usage, None, optparse.Option, version) parser.add_option( "-l", "--logging", action="store_true", default=False, dest="logging", help="log into httpserver.log" ) parser.add_option("-P", "--profiler", default=False, dest="profiler", help="profiler filename") servers = ", ".join(x for x in dir(Servers) if not x[0] == "_") parser.add_option("-s", "--server", default="rocket", dest="server", help="server name (%s)" % servers) parser.add_option("-i", "--ip", default="127.0.0.1", dest="ip", help="ip address") parser.add_option("-p", "--port", default="8000", dest="port", help="port number") parser.add_option("-w", "--workers", default="", dest="workers", help="number of workers number") (options, args) = parser.parse_args() print "starting %s on %s:%s..." % (options.server, options.ip, options.port) run(options.server, options.ip, options.port, logging=options.logging, profiler=options.profiler)
def compile_controllers(folder): """ Compiles all the controllers in the application specified by `folder` """ path = pjoin(folder, 'controllers') for file in listdir(path, '.+\.py$'): ### why is this here? save_pyc(pjoin(path, file)) data = read_file(pjoin(path, file)) exposed = regex_expose.findall(data) for function in exposed: command = data + "\nresponse._vars=response._caller(%s)\n" % \ function filename = pjoin(folder, 'compiled', ('controllers/' + file[:-3]).replace('/', '_') + '_' + function + '.py') write_file(filename, command) save_pyc(filename) os.unlink(filename)
def getResource(): if request.vars.file_name: rdir = str(request.vars.file_name).split("/")[0] if rdir == "backup": file_name = os.path.join(request.folder, 'static', str(request.vars.file_name)) elif rdir in ("docs", "download", "report"): file_name = os.path.join(request.folder, 'static/resources', str(request.vars.file_name)) else: return "Valid directories: docs, download, report" if request.vars.lang and session._language and session._language != "en": file_name += '_' + str(session._language) if request.vars.file_type: file_name += '.' + str(request.vars.file_type) else: file_name += '.html' if not os.path.isfile(file_name): if request.vars.lang and session._language and session._language != "en": file_name = str(file_name).replace( '_' + str(session._language), "") if not os.path.isfile(file_name): return T('Missing file...') else: return T('Missing file...') if request.vars.content: if request.vars.content == "view": response.view = "../" + file_name[file_name.find("static"):] return dict() elif request.vars.content == "xml": response.headers['Content-Type'] = 'text/xml' else: response.headers['Content-Type'] = request.vars.content if request.vars.file_type: response.headers[ 'Content-Disposition'] = 'attachment;filename="' + str( request.vars.file_name).split('/')[ len(str(request.vars.file_name).split('/')) - 1] + '.' + str(request.vars.file_type) + '"' return read_file(file_name) else: return T('Missing document...')
def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ request = current.request folder = request.folder c = request.controller #f = environment['request'].function response = current.response path = pjoin(folder, 'models') cpath = pjoin(folder, 'compiled') compiled = os.path.exists(cpath) if compiled: models = sorted(listdir(cpath, '^models[_.][\w.]+\.pyc$', 0), model_cmp) else: models = sorted(listdir(path, '^\w+\.py$', 0, sort=False), model_cmp_sep) models_to_run = None for model in models: if response.models_to_run != models_to_run: regex = models_to_run = response.models_to_run[:] if isinstance(regex, list): regex = re_compile('|'.join(regex)) if models_to_run: if compiled: n = len(cpath)+8 fname = model[n:-4].replace('.','/')+'.py' else: n = len(path)+1 fname = model[n:].replace(os.path.sep,'/') if not regex.search(fname) and c != 'appadmin': continue elif compiled: code = read_pyc(model) elif is_gae: code = getcfs(model, model, lambda: compile2(read_file(model), model)) else: code = getcfs(model, model, None) restricted(code, environment, layer=model)
def fix_db(filename): params = dict(session.app["params"]) content = read_file(filename, "rb") if "auth_user" in session.app["tables"]: auth_user = make_table("auth_user", session.app["table_auth_user"]) content = content.replace("sqlite://storage.sqlite", params["database_uri"]) content = content.replace("auth.define_tables()", auth_user + "auth.define_tables(migrate = settings.migrate)") content += """ mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login """ if params["login_method"] == "janrain": content += """ from gluon.contrib.login_methods.rpx_account import RPXAccount auth.settings.actions_disabled=['register','change_password','request_reset_password'] auth.settings.login_form = RPXAccount(request, api_key = settings.login_config.split(':')[-1], domain = settings.login_config.split(':')[0], url = "http://%s/%s/default/user/login" % (request.env.http_host,request.application)) """ write_file(filename, content, "wb")
def __init__( self, payload, filename=None, content_id=None, content_type=None): if isinstance(payload, str): if filename is None: filename = os.path.basename(payload) payload = read_file(payload, 'rb') else: if filename is None: raise Exception('Missing attachment name') payload = payload.read() self.transmission_dict = { 'type': content_type or contenttype(filename), 'name': filename, 'data': base64.b64encode(payload).decode("ascii") } self.is_inline = False if content_id is not None: self.is_inline = True self.transmission_dict['name'] = content_id
def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ folder = environment['request'].folder c = environment['request'].controller f = environment['request'].function cpath = pjoin(folder, 'compiled') if os.path.exists(cpath): for model in listdir(cpath, '^models_\w+\.pyc$', 0): restricted(read_pyc(model), environment, layer=model) path = pjoin(cpath, 'models') models = listdir(path, '^\w+\.pyc$', 0, sort=False) compiled = True else: path = pjoin(folder, 'models') models = listdir(path, '^\w+\.py$', 0, sort=False) compiled = False n = len(path) + 1 for model in models: regex = environment['response'].models_to_run if isinstance(regex, list): regex = re_compile('|'.join(regex)) file = model[n:].replace(os.path.sep, '/').replace('.pyc', '.py') if not regex.search(file) and c != 'appadmin': continue elif compiled: code = read_pyc(model) elif is_gae: code = getcfs(model, model, lambda: compile2(read_file(model), model)) else: code = getcfs(model, model, None) restricted(code, environment, layer=model)
def run_models_in(environment): """ Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compiling them. """ folder = environment['request'].folder c = environment['request'].controller f = environment['request'].function cpath = pjoin(folder, 'compiled') if os.path.exists(cpath): for model in listdir(cpath, '^models_\w+\.pyc$', 0): restricted(read_pyc(model), environment, layer=model) path = pjoin(cpath, 'models') models = listdir(path, '^\w+\.pyc$', 0, sort=True) compiled = True else: path = pjoin(folder, 'models') models = listdir(path, '^\w+\.py$', 0, sort=True) compiled = False n = len(path) + 1 for model in models: regex = environment['response'].models_to_run if isinstance(regex, list): regex = re_compile('|'.join(regex)) file = model[n:].replace(os.path.sep, '/').replace('.pyc', '.py') if not regex.search(file) and c != 'appadmin': continue elif compiled: code = read_pyc(model) elif is_gae: code = getcfs(model, model, lambda: compile2(read_file(model), model)) else: code = getcfs(model, model, None) restricted(code, environment, layer=model)
def fix_db(filename): params = dict(session.app['params']) content = read_file(filename, 'rb') if 'auth_user' in session.app['tables']: auth_user = make_table('auth_user', session.app['table_auth_user']) content = content.replace('sqlite://storage.sqlite', params['database_uri']) content = content.replace('auth.define_tables()',\ auth_user+'auth.define_tables(migrate = settings.migrate)') content += """ mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login """ if params['login_method'] == 'janrain': content += """ from gluon.contrib.login_methods.rpx_account import RPXAccount auth.settings.actions_disabled=['register','change_password','request_reset_password'] auth.settings.login_form = RPXAccount(request, api_key = settings.login_config.split(':')[-1], domain = settings.login_config.split(':')[0], url = "http://%s/%s/default/user/login" % (request.env.http_host,request.application)) """ write_file(filename, content, 'wb')
def run(appname, plain=False, import_models=False, startfile=None, bpython=False, python_code=False, cronjob=False): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: - a : web2py application name - a/c : exec the controller c into the application environment """ (a, c, f, args, vars) = parse_path_info(appname, av=True) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg) adir = os.path.join('applications', a) if not os.path.exists(adir): if sys.stdin and not sys.stdin.name == '/dev/null': confirm = raw_input( 'application %s does not exist, create (y/n)?' % a) else: logging.warn('application does not exist and will not be created') return if confirm.lower() in ['y', 'yes']: os.mkdir(adir) w2p_unpack('welcome.w2p', adir) for subfolder in [ 'models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'languages', 'static', 'private', 'uploads' ]: subpath = os.path.join(adir, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(adir, 'models/db.py') if os.path.exists(db): data = fileutils.read_file(db) data = data.replace('<your secret key>', 'sha512:' + web2py_uuid()) fileutils.write_file(db, data) if c: import_models = True extra_request = {} if args: extra_request['args'] = args if vars: extra_request['vars'] = vars _env = env(a, c=c, f=f, import_models=import_models, extra_request=extra_request) if c: pyfile = os.path.join('applications', a, 'controllers', c + '.py') pycfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c, f)) if ((cronjob and os.path.isfile(pycfile)) or not os.path.isfile(pyfile)): exec read_pyc(pycfile) in _env elif os.path.isfile(pyfile): execfile(pyfile, _env) else: die(errmsg) if f: exec('print %s()' % f, _env) return _env.update(exec_pythonrc()) if startfile: try: ccode = None if startfile.endswith('.pyc'): ccode = read_pyc(startfile) exec ccode in _env else: execfile(startfile, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception, e: print traceback.format_exc() if import_models: BaseAdapter.close_all_instances('rollback')
def create_file(): """ Create files handler """ try: app = get_app(name=request.vars.location.split('/')[0]) path = apath(request.vars.location, r=request) filename = re.sub('[^\w./-]+', '_', request.vars.filename) if path[-11:] == '/languages/': # Handle language files if len(filename) == 0: raise SyntaxError if not filename[-3:] == '.py': filename += '.py' app = path.split('/')[-3] path = os.path.join(apath(app, r=request), 'languages', filename) if not os.path.exists(path): safe_write(path, '') findT(apath(app, r=request), filename[:-3]) session.flash = T('language file "%(filename)s" created/updated', dict(filename=filename)) redirect(request.vars.sender) elif path[-8:] == '/models/': # Handle python models if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = '# coding: utf8\n' elif path[-13:] == '/controllers/': # Handle python controllers if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = '# coding: utf8\n# %s\ndef index(): return dict(message="hello from %s")' text = text % (T('try something like'), filename) elif path[-7:] == '/views/': if request.vars.plugin and not filename.startswith( 'plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) # Handle template (html) views if filename.find('.') < 0: filename += '.html' extension = filename.split('.')[-1].lower() if len(filename) == 5: raise SyntaxError msg = T('This is the %(filename)s template', dict(filename=filename)) if extension == 'html': text = dedent(""" {{extend 'layout.html'}} <h1>%s</h1> {{=BEAUTIFY(response._vars)}}""" % msg) else: generic = os.path.join(path, 'generic.' + extension) if os.path.exists(generic): text = read_file(generic) else: text = '' elif path[-9:] == '/modules/': if request.vars.plugin and not filename.startswith( 'plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) # Handle python module files if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = dedent(""" #!/usr/bin/env python # coding: utf8 from gluon import *\n""") elif path[-8:] == '/static/': if request.vars.plugin and not filename.startswith( 'plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) text = '' else: redirect(request.vars.sender) full_filename = os.path.join(path, filename) dirpath = os.path.dirname(full_filename) if not os.path.exists(dirpath): os.makedirs(dirpath) if os.path.exists(full_filename): raise SyntaxError safe_write(full_filename, text) session.flash = T('file "%(filename)s" created', dict(filename=full_filename[len(path):])) redirect( URL('edit', args=[os.path.join(request.vars.location, filename)])) except Exception, e: if not isinstance(e, HTTP): session.flash = T('cannot create file')
def license(): import os filename = os.path.join(request.env.gluon_parent, 'LICENSE') return response.render(dict(license=MARKMIN(read_file(filename))))
session_db = DAL('gae') session.connect(request, response, db=session_db) hosts = (http_host, ) is_gae = True else: is_gae = False if request.is_https: session.secure() elif not request.is_local and not DEMO_MODE: raise HTTP(200, T('Admin is disabled because insecure channel')) try: _config = {} port = int(request.env.server_port or 0) exec read_file(apath('../parameters_%i.py' % port, request)) in _config if not 'password' in _config or not _config['password']: raise HTTP(200, T('admin disabled because no admin password')) except IOError: import gluon.fileutils if is_gae: if gluon.fileutils.check_credentials(request): session.authorized = True session.last_time = time.time() else: raise HTTP( 200, T('admin disabled because not supported on google app engine')) else: raise HTTP(200,
def run(appname, plain=False, import_models=False, startfile=None, bpython=False, python_code=False, cronjob=False): """ Start interactive shell or run Python script (startfile) in web2py controller environment. appname is formatted like: - a : web2py application name - a/c : exec the controller c into the application environment """ (a, c, f, args, vars) = parse_path_info(appname, av=True) errmsg = 'invalid application name: %s' % appname if not a: die(errmsg) adir = os.path.join('applications', a) if not os.path.exists(adir): if sys.stdin and not sys.stdin.name == '/dev/null': confirm = raw_input( 'application %s does not exist, create (y/n)?' % a) else: logging.warn('application does not exist and will not be created') return if confirm.lower() in ['y', 'yes']: os.mkdir(adir) w2p_unpack('welcome.w2p', adir) for subfolder in [ 'models', 'views', 'controllers', 'databases', 'modules', 'cron', 'errors', 'sessions', 'languages', 'static', 'private', 'uploads' ]: subpath = os.path.join(adir, subfolder) if not os.path.exists(subpath): os.mkdir(subpath) db = os.path.join(adir, 'models/db.py') if os.path.exists(db): data = fileutils.read_file(db) data = data.replace('<your secret key>', 'sha512:' + web2py_uuid()) fileutils.write_file(db, data) if c: import_models = True extra_request = {} if args: extra_request['args'] = args if vars: extra_request['vars'] = vars _env = env(a, c=c, f=f, import_models=import_models, extra_request=extra_request) if c: pyfile = os.path.join('applications', a, 'controllers', c + '.py') pycfile = os.path.join('applications', a, 'compiled', "controllers_%s_%s.pyc" % (c, f)) if ((cronjob and os.path.isfile(pycfile)) or not os.path.isfile(pyfile)): exec(read_pyc(pycfile), _env) elif os.path.isfile(pyfile): execfile(pyfile, _env) else: die(errmsg) if f: exec('print( %s())' % f, _env) return _env.update(exec_pythonrc()) if startfile: try: ccode = None if startfile.endswith('.pyc'): ccode = read_pyc(startfile) exec(ccode, _env) else: execfile(startfile, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception as e: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') elif python_code: try: exec(python_code, _env) if import_models: BaseAdapter.close_all_instances('commit') except Exception as e: print(traceback.format_exc()) if import_models: BaseAdapter.close_all_instances('rollback') else: if not plain: if bpython: try: import bpython bpython.embed(locals_=_env) return except: logger.warning('import bpython error; trying ipython...') else: try: import IPython if IPython.__version__ > '1.0.0': IPython.start_ipython(user_ns=_env) return elif IPython.__version__ == '1.0.0': from IPython.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return elif IPython.__version__ >= '0.11': from IPython.frontend.terminal.embed import InteractiveShellEmbed shell = InteractiveShellEmbed(user_ns=_env) shell() return else: # following 2 lines fix a problem with # IPython; thanks Michael Toomim if '__builtins__' in _env: del _env['__builtins__'] shell = IPython.Shell.IPShell(argv=[], user_ns=_env) shell.mainloop() return except: logger.warning( 'import IPython error; use default python shell') enable_autocomplete_and_history(adir, _env) code.interact(local=_env)
def verify_admin_password(password): _config = {} port = int(request.env.server_port or 0) restricted(read_file(apath('../parameters_%i.py' % port, request)), _config) return _config['password'] == CRYPT()(password)[0]
session.connect(request, response, db=session_db) hosts = (http_host, ) is_gae = True else: is_gae = False if request.is_https: session.secure() elif not request.is_local and not DEMO_MODE: raise HTTP(200, T('Admin is disabled because insecure channel')) try: _config = {} port = int(request.env.server_port or 0) restricted( read_file(apath('../parameters_%i.py' % port, request)), _config) if not 'password' in _config or not _config['password']: raise HTTP(200, T('admin disabled because no admin password')) except IOError: import gluon.fileutils if is_gae: if gluon.fileutils.check_credentials(request): session.authorized = True session.last_time = time.time() else: raise HTTP(200, T('admin disabled because not supported on google app engine')) else: raise HTTP( 200, T('admin disabled because unable to access password file'))
def match(filename, keywords): filename = os.path.join(apath(app, r=request), filename) if keywords in read_file(filename, 'rb'): return True return False
from gluon.validators import CRYPT from gluon.html import URL, xmlescape from gluon.utils import is_valid_ip_address, getipaddrinfo from gluon.rewrite import load as load_routes, url_in, THREAD_LOCAL as rwthread, \ try_rewrite_on_error, fixup_missing_path_info from gluon import newcron __all__ = ['wsgibase', 'save_password', 'appfactory', 'HttpServer'] requests = 0 # gc timer # Security Checks: validate URL and session_id here, # accept_language is validated in languages try: version_info = read_file(pjoin(global_settings.gluon_parent, 'VERSION')) web2py_version = global_settings.web2py_version = version_info.split( )[-1].strip() except: raise RuntimeError("Cannot determine web2py version") # do not need rocket nor HttpServer when served by handler # (e.g. apache + mod_wsgi), speed up execution and save memory if not global_settings.web2py_runtime_handler: from gluon import rocket load_routes() HTTPS_SCHEMES = set(('https', 'HTTPS')) # pattern used to match client IP address
import signal import math import logging import getpass from gluon import main, newcron from gluon.fileutils import read_file, create_welcome_w2p from gluon.console import console from gluon.settings import global_settings from gluon.shell import die, run, test from gluon.utils import is_valid_ip_address, is_loopback_ip_address, getipaddrinfo ProgramName = 'web2py Web Framework' ProgramAuthor = 'Created by Massimo Di Pierro, Copyright 2007-' + str( time.localtime().tm_year) ProgramVersion = read_file('VERSION').rstrip() if sys.version_info < (2, 7) or (3, 0) < sys.version_info < (3, 5): from platform import python_version sys.stderr.write("Warning: web2py requires at least Python 2.7/3.5" " but you are running %s\n" % python_version()) def run_system_tests(options): """ Runs unittests for gluon.tests """ # see "python -m unittest -h" for unittest options help # NOTE: someone might be interested either in using the # -f (--failfast) option to stop testing on first failure, or # in customizing the test selection, for example to run only
def run_controller_in(controller, function, environment): """ Runs the controller.function() (for the app specified by the current folder). It tries pre-compiled controller.function.pyc first before compiling it. """ # if compiled should run compiled! folder = current.request.folder cpath = pjoin(folder, 'compiled') badc = 'invalid controller (%s/%s)' % (controller, function) badf = 'invalid function (%s/%s)' % (controller, function) if exists(cpath): filename = pjoin(cpath, 'controllers.%s.%s.pyc' % (controller, function)) try: ccode = getcfs(filename, filename, lambda: read_pyc(filename)) except IOError: raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf) elif function == '_TEST': # TESTING: adjust the path to include site packages paths = (global_settings.gluon_parent, abspath('site-packages', gluon=True), abspath('gluon', gluon=True), '') [add_path_first(path) for path in paths] # TESTING END filename = pjoin(folder, 'controllers/%s.py' % controller) if not exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc) environment['__symbols__'] = list(environment.keys()) code = read_file(filename) code += TEST_CODE ccode = compile2(code, filename) else: filename = pjoin(folder, 'controllers/%s.py' % controller) try: code = getcfs(filename, filename, lambda: read_file(filename)) except IOError: raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc) exposed = find_exposed_functions(code) if function not in exposed: raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf) code = "%s\nresponse._vars=response._caller(%s)" % (code, function) layer = "%s:%s" % (filename, function) ccode = getcfs(layer, filename, lambda: compile2(code, filename)) restricted(ccode, environment, layer=filename) response = environment["response"] vars = response._vars if response.postprocessing: vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars) if isinstance(vars, unicodeT): vars = to_native(vars) elif hasattr(vars, 'xml') and callable(vars.xml): vars = vars.xml() return vars
session_db = DAL('gae') session.connect(request, response, db=session_db) hosts = (http_host, ) is_gae = True else: is_gae = False if request.is_https: session.secure() elif not request.is_local and not DEMO_MODE: raise HTTP(200, T('Admin is disabled because insecure channel')) try: _config = {} port = int(request.env.server_port or 0) restricted(read_file(apath('../parameters_%i.py' % port, request)), _config) if not 'password' in _config or not _config['password']: raise HTTP(200, T('admin disabled because no admin password')) except IOError: import gluon.fileutils if is_gae: if gluon.fileutils.check_credentials(request): session.authorized = True session.last_time = time.time() else: raise HTTP( 200, T('admin disabled because not supported on google app engine')) else:
def run_controller_in(controller, function, environment): """ Runs the controller.function() (for the app specified by the current folder). It tries pre-compiled controller_function.pyc first before compiling it. """ # if compiled should run compiled! folder = current.request.folder path = pjoin(folder, 'compiled') badc = 'invalid controller (%s/%s)' % (controller, function) badf = 'invalid function (%s/%s)' % (controller, function) if os.path.exists(path): filename = pjoin(path, 'controllers.%s.%s.pyc' % (controller, function)) if not os.path.exists(filename): ### for backward compatibility filename = pjoin(path, 'controllers_%s_%s.pyc' % (controller, function)) ### end for backward compatibility if not os.path.exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf) restricted(read_pyc(filename), environment, layer=filename) elif function == '_TEST': # TESTING: adjust the path to include site packages from settings import global_settings from admin import abspath, add_path_first paths = (global_settings.gluon_parent, abspath('site-packages', gluon=True), abspath('gluon', gluon=True), '') [add_path_first(path) for path in paths] # TESTING END filename = pjoin(folder, 'controllers/%s.py' % controller) if not os.path.exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc) environment['__symbols__'] = environment.keys() code = read_file(filename) code += TEST_CODE restricted(code, environment, layer=filename) else: filename = pjoin(folder, 'controllers/%s.py' % controller) if not os.path.exists(filename): raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badc, web2py_error=badc) code = read_file(filename) exposed = find_exposed_functions(code) if not function in exposed: raise HTTP(404, rewrite.THREAD_LOCAL.routes.error_message % badf, web2py_error=badf) code = "%s\nresponse._vars=response._caller(%s)\n" % (code, function) if is_gae: layer = filename + ':' + function code = getcfs(layer, filename, lambda: compile2(code, layer)) restricted(code, environment, filename) response = current.response vars = response._vars if response.postprocessing: vars = reduce(lambda vars, p: p(vars), response.postprocessing, vars) if isinstance(vars, unicode): vars = vars.encode('utf8') elif hasattr(vars, 'xml') and callable(vars.xml): vars = vars.xml() return vars
def changelog(): import os filename = os.path.join(request.env.gluon_parent, 'CHANGELOG') return response.render(dict(changelog=MARKMIN(read_file(filename))))
# -*- coding: utf-8 -*- from cStringIO import StringIO from gluon.fileutils import read_file from gluon.storage import Storage import os, re def index(): return dict() bridge.testdata = read_file("C:\\YandexDisk\\PycharmProjects\\asstireports\\responsepage268.xml") def report(): args = request.args if args: response.headers['Content-Type'] = 'text/xml' param = Storage(request.vars) if args[0] == 'view': stream = StringIO( re.sub("\$\$tag[^<>]+", "", read_file(os.path.join(request.folder, 'static', 'reports', request.args[1])) )) elif args[0] == 'load': stream = StringIO(bridge.getreport(args[1], param.type, param.startdate, param.enddate)) else: stream = StringIO(read_file(os.path.join(request.folder, 'static', 'reports', request.args[1]))) if param.htmldata: import win32com.client as wc xlApp = wc.Dispatch('OWC11.Spreadsheet.11') xlApp.DataType = "XMLData" xlApp.load(stream.getvalue())