class ExposingNewStyle(object): def base(self): return "expose works!" cherrypy.expose(base) cherrypy.expose(base, "1") cherrypy.expose(base, "2")
class Exposing: def base(self): return "expose works!" cherrypy.expose(base) cherrypy.expose(base, "1") cherrypy.expose(base, "2")
class ExposingNewStyle(object): @cherrypy.expose def base(self): return 'expose works!' cherrypy.expose(base, '1') cherrypy.expose(base, '2')
class Exposing: @cherrypy.expose def base(self): return 'expose works!' cherrypy.expose(base, '1') cherrypy.expose(base, '2')
def _action(fn): def fn2(self, *args, **kwargs): # check if this method is specifically allowed here if cherrypy.request.method not in allowed_methods: cherrypy.response.headers['Allow'] = ", ".join(allowed_methods) raise cherrypy.HTTPError(405) # prepares the HTTP response and the associated renderer cherrypy.response.headers['Content-Type'] = self.mime_type renderer = http_renderers.get(self.mime_type) # in case of cache, checks if the context is already present if use_cache: kwarg_only = map_method_to_dict(fn, args, kwargs) cache_key = cache.generate_key(self.__class__.__name__, fn.__name__, kwarg_only) cached_val = cache.get(cache_key) if cached_val: return renderer(self, cached_val) context = fn(self, *args, **kwargs) if use_cache: cache.set(cache_key, context) return renderer(self, context) return cherrypy.expose(fn2)
class Root: _cp_config = {'foo': 'this', 'bar': 'that'} def __init__(self): cherrypy.config.namespaces['db'] = self.db_namespace def db_namespace(self, k, v): if k == "scheme": self.db = v # @cherrypy.expose(alias=('global_', 'xyz')) def index(self, key): return cherrypy.request.config.get(key, "None") index = cherrypy.expose(index, alias=('global_', 'xyz')) def repr(self, key): return repr(cherrypy.request.config.get(key, None)) repr.exposed = True def dbscheme(self): return self.db dbscheme.exposed = True def plain(self, x): return x plain.exposed = True plain._cp_config = {'request.body.attempt_charsets': ['utf-16']} favicon_ico = cherrypy.tools.staticfile.handler( filename=os.path.join(localDir, '../favicon.ico'))
def __getattribute__(self, name): with cd(TEST_PATH): test_dirs = [x for x in os.listdir(".") if os.path.isdir(x)] logger.debug(f"Found tests {test_dirs}") if name in test_dirs: return cherrypy.expose(show_test_factory(name)) else: return super().__getattribute__(name)
def expose_json(func): '''Decorate a method to automatically return json''' @wraps(func) def wrapper(*a, **kw): serving.response.headers['Content-Type'] = 'application/json' raw = func(*a, **kw) return encode(raw) return expose(wrapper)
def expose_endpoint(func): """ Equivalent to @cherrypy.expose @check_kc_user """ func = check_kc_user(func) func = cherrypy.expose(func) return func
def json_expose(f): def decotared(*idx, **kw): for key in kw: if key.endswith('[]'): if isinstance(kw[key], basestring): kw[key] = [kw[key]] kw[key[:-2]] = kw[key] del kw[key] cherrypy.response.headers["content-type"] = "text/json" return json.dumps(f(*idx, **kw)) return cherrypy.expose(decotared)
def web(func): """ A decorator that enables cherrypy but also that enables filters """ def apply_before_filter(self, *args, **kwargs): self.before_filter() return func(self, *args, **kwargs) return_val = cherrypy.expose(apply_before_filter) return_val.expose_resource = True return return_val
def expose_json(func): """ Equivalent to @cherrypy.expose @handle_error(redirect=False) @jsonify @check_user """ func = check_user(func) func = jsonify(func) func = handle_error(redirect=False)(func) func = cherrypy.expose(func) return func
def expose_page(func): """ Equivalent to @cherrypy.expose @handle_error(redirect=True) @using_template2('base_template') @check_user """ func = check_user(func) func = using_template('base_template')(func) func = handle_error(redirect=True)(func) func = cherrypy.expose(func) return func
def expose(cls, func): def f(self, *args, **kwargs): json_data = getattr(cherrypy.request, 'json', kwargs) # Handle bin string translations json_data = decode_bin_strings(json_data) out_json = func(self, *args, **json_data) # Decode bin string translations out_json = encode_bin_strings(out_json) return out_json return cherrypy.expose(cherrypy.tools.json_in()(cherrypy.tools.json_out()(f)))
class Root: _cp_config = {'foo': 'this', 'bar': 'that'} # @cherrypy.expose(alias=('global_', 'xyz')) def index(self, key): return cherrypy.request.config.get(key, "None") index = cherrypy.expose(index, alias=('global_', 'xyz')) def repr(self, key): return repr(cherrypy.request.config.get(key, None)) repr.exposed = True
def get_cherrypy_server(): class Server(object): pass def call_me(cmd_class): @cp.tools.json_out() def do_call(self, opts): cmd = cmd_class.from_dict(json.loads(opts)) return cmd.execute() return do_call for call in APIMeta.all_classes(APICallBase): setattr(Server, call.name(), cp.expose(call_me(call))) return Server
def decoratorFunction(function): def toBeExecuted(self, *args, **kwargs): if requestClass != None: request = self._createRequest(requestClass, args, kwargs) response = function(self, request) else: response = function(self) if not response: raise cherrypy.HTTPError("404 Not found") if response[0]: # path to a file filePath, clientFilename, mimeType = response[1:] disposition = 'attachment' if mimeType in ('image/jpeg', 'text/html'): disposition = 'inline' return static.serve_file(filePath, mimeType, disposition = disposition, name = clientFilename) else: # ready data string, mimeType = response[1:3] disposition = None if len(response) >= 4: disposition = response[3] elif len(response) == 3 and mimeType in ('aplication/json', 'image/jpeg'): disposition = 'inline' if disposition != None: cherrypy.response.headers['Content-Disposition'] = disposition cherrypy.response.headers['Content-Type'] = mimeType return string if hasattr(function, '_cp_config'): toBeExecuted._cp_config = dict(function._cp_config) return cherrypy.expose(toBeExecuted)
def decorator(*args, **kwargs): if kwargs.pop('app_secret', False) != os.environ['APP_SECRET']: raise cherrypy.HTTPError(401) cursor = cherrypy.thread_data.db.cursor() data = cherrypy.request.json try: return staticmethod( cherrypy.expose( cherrypy.tools.json_in()( cherrypy.tools.json_out()( func(cursor, data, *args, **kwargs) ) ) ) ) finally: cursor.commit() cursor.close()
def deco(func): func = check_user(func) func = using_template(template_name)(func) func = handle_error(redirect=False)(func) func = cherrypy.expose(func) return func
def expose_anonymous_dont_jsonify(function): return cherrypy.expose(dont_jsonify(function))
def expose_decorator(func) : log.debug('Exposing %s' % str(func)) # Load a relative template if template_name and template_name[0] == "." : pers_tmpl = cherrypy.config.get("molotov.templates") if pers_tmpl : mod = func.__module__ real_tmpl = pers_tmpl + "." \ + mod[:mod.rfind(".")] + template_name else : mod = func.__module__ real_tmpl = mod[:mod.rfind(".")] + template_name else : real_tmpl = template_name if real_tmpl : tpath = find_template(real_tmpl) if tpath is None : print "Could find the template %s" % real_tmpl sys.exit(1) def exposed_func(*args, **kw) : # Get the dictionary d = func(*args, **kw) if not isinstance(d, dict) : log.debug("Not a dictionary: %s" % str(d.__class__)) if isinstance(d, str) : return d else : return d.encode('utf-8') # Given variables d['mltv'] = d['molotov'] = molotov d['molotov_title'] = cherrypy.config.get('molotov.title', 'Molotov') d['molotov_cocktails'] = molotov.running_cocktails # User usr = cherrypy.session.get('molotov.user', None) if usr : username = usr.name else : username = None d['molotov_user'] = d['mltv_user'] = username groups = [] if not usr is None : print usr.groups for grp in usr.groups : groups.append(grp.name) d['mltv_groups'] = d['molotov_groups'] = groups # Templatize tmpl_obj = kid.Template(name=real_tmpl) for(k, v) in d.iteritems() : setattr(tmpl_obj, k, v) tmpl_obj.assume_encoding = cherrypy.config.get('molotov.charset') return tmpl_obj.serialize(output=cherrypy.config.get('molotov.output')) if template_name : return cherrypy.expose(exposed_func) else : return cherrypy.expose(func)
def expose_numpy_array(func): func = check_user(func) func = ndarray_to_http_binary(func) func = handle_error(redirect=False)(func) func = cherrypy.expose(func) return func
print("Up to date") sys.exit(0) elif '--build' in sys.argv: # Do we need to compile? if not tryBuild(): cherrypy.log("Build skipped - up to date") root = MainRoot() # Disable caching - if we don't, then between built and development # versions the web browser won't re-send requests. Note that we could # also come up with a scheme where the URL changes when the version # changes. root._cp_config = { 'response.headers.Cache-Control': 'No-Cache' } if '--build' in sys.argv: # Running compiled version, redirect src to built version cherrypy.log("Using build/ rather than webapp/") root.src = StaticServer(_DIR + '/build') else: # Add the lib dir, rewrite src/require.js to lib/require.js root.lib = StaticServer(_DIR + '/../jsProject/lib') def serveRequire(): return cherrypy.lib.static.serve_file( root.lib._path + '/require.js') cherrypy.expose(serveRequire) root.src.require_js = serveRequire cherrypy.tree.mount(root, '/') cherrypy.engine.start() cherrypy.engine.block()
def expose_secure_dont_jsonify(function): return secure(cherrypy.expose(dont_jsonify(function)))
class GraphMixIn(Cache): # Done to make sure we don't execute arbitrary classes or functions... _usable_classes = [PieGraph, BarGraph, StackedBarGraph, CumulativeGraph, \ HorizontalBarGraph, QualityBarGraph, QualityMap, TimeBarGraph, \ TimeStackedBarGraph] _data_generators = {} _graph_registry = {} def __init__(self, *args, **kw): super(GraphMixIn, self).__init__(args, kw) self.use_cache = True self.mounted_url = None #cant set here as controller may not be inited yet def getBaseUrl(self): """ Find where the context is mounted """ # if cached return if self.mounted_url is not None: return self.mounted_url temp_url = '' # first check command line for where server mounted if self.context.CmdLineArgs().opts.baseUrl: temp_url = "%s%s" % (temp_url, self.context.CmdLineArgs().opts.baseUrl) #look to see if mounted with baseUrl param to DeclaePlugin if hasattr(self, 'context'): for plugin in self.context.PluginManager().plugins(): if plugin.name.endswith(self.__class__.__name__) and \ 'baseUrl' in plugin.options: temp_url = "%s%s" % (temp_url, plugin.options['baseUrl']) # set cached value and return self.mounted_url = temp_url return self.mounted_url def data_generator(self, func): _data_generators[func.__name__] = func return func def templateGraph(self, graphName, data, metadata): graph, coords = self._generate_graph(graphName, data, metadata) return graph def registerGraph(self, graphName, data_generator, graphClass, metadata): self._graph_registry[graphName] = (data_generator, graphClass, metadata) def lookupGraph(self, graphName): return self._graph_registry[graphName] def includeGraph(self, graphName, args={}): def grapher(): data_generator, graphClass, metadata = self.lookupGraph(graphName) graph, coords, data = self._generate_graph(graphName, graphClass, metadata, data_generator, args) url = self.getBaseUrl() + '/graph/' + str( graphName) + '?' + urllib.urlencode(args) im = ImageMapWriter() output = im(url, data, coords, metadata) return output return grapher def graph(self, graphName, **args): #TODO: Wrap with better error handling data_generator, graphClass, metadata = self.lookupGraph(graphName) graph, coords, data = self._generate_graph(graphName, graphClass, metadata, data_generator, args) return graph graph = expose(graph) def _generate_graph(self, *args, **kw): if self.use_cache: return self.cached_function(self._generate_uncached_graph, args, kw) else: return self._generate_uncached_graph(*args, **kw) def _generate_uncached_graph(self, graphName, graphClass, metadata, data_generator, args): if graphClass in self._usable_classes: my_class = graphClass else: my_class = None my_instance = my_class() data = data_generator(args) file = StringIO.StringIO() coords = my_instance(data, file, metadata) return file.getvalue(), coords, data def make_hash_str(self, function, args, **kwargs): graphName = args[0] metadata = args[2] args = args[4] std_hash_str = super(GraphMixIn, self).make_hash_str(graphName, **args) extd_hash_str = super(GraphMixIn, self).make_hash_str(graphName, **metadata) return std_hash_str + extd_hash_str
def publish(func=None, *args): return cherrypy.expose(func, *args)
def expose_anonymous(function): return cherrypy.expose(jsonify(function))
def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) for value in dct.values(): if isinstance(value, types.FunctionType): cherrypy.expose(value) setattr(root, name.lower(), cls())
def ajax(handler): return cherrypy.expose(cherrypy.tools.allow(methods=('POST',))(cherrypy.tools.json_out()(handler)))
def __init__(cls, name, bases, dct): type.__init__(cls, name, bases, dct) for value in itervalues(dct): if isinstance(value, types.FunctionType): cherrypy.expose(value) setattr(root, name.lower(), cls())