Python cherrypy.config() Examples
The following are 30
code examples of cherrypy.config().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cherrypy
, or try the search function
.
Example #1
Source File: _cpchecker.py From opsbro with MIT License | 6 votes |
def _known_types(self, config): msg = ("The config entry %r in section %r is of type %r, " "which does not match the expected type %r.") for section, conf in config.items(): if isinstance(conf, dict): for k, v in conf.items(): if v is not None: expected_type = self.known_config_types.get(k, None) vtype = type(v) if expected_type and vtype != expected_type: warnings.warn(msg % (k, section, vtype.__name__, expected_type.__name__)) else: k, v = section, conf if v is not None: expected_type = self.known_config_types.get(k, None) vtype = type(v) if expected_type and vtype != expected_type: warnings.warn(msg % (k, section, vtype.__name__, expected_type.__name__))
Example #2
Source File: test_etags.py From bazarr with GNU General Public License v3.0 | 6 votes |
def setup_server(): class Root: @cherrypy.expose def resource(self): return 'Oh wah ta goo Siam.' @cherrypy.expose def fail(self, code): code = int(code) if 300 <= code <= 399: raise cherrypy.HTTPRedirect([], code) else: raise cherrypy.HTTPError(code) @cherrypy.expose # In Python 3, tools.encode is on by default @cherrypy.config(**{'tools.encode.on': True}) def unicoded(self): return ntou('I am a \u1ee4nicode string.', 'escape') conf = {'/': {'tools.etags.on': True, 'tools.etags.autotags': True, }} cherrypy.tree.mount(Root(), config=conf)
Example #3
Source File: _cpchecker.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_site_config_entries_in_app_config(self): """Check for mounted Applications that have site-scoped config.""" for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue msg = [] for section, entries in app.config.items(): if section.startswith('/'): for key, value in entries.items(): for n in ('engine.', 'server.', 'tree.', 'checker.'): if key.startswith(n): msg.append('[%s] %s = %s' % (section, key, value)) if msg: msg.insert(0, 'The application mounted at %r contains the ' 'following config entries, which are only allowed ' 'in site-wide config. Move them to a [global] ' 'section and pass them to cherrypy.config.update() ' 'instead of tree.mount().' % sn) warnings.warn(os.linesep.join(msg))
Example #4
Source File: test_core.py From bazarr with GNU General Public License v3.0 | 6 votes |
def setup_server(): def break_header(): # Add a header after finalize that is invalid cherrypy.serving.response.header_list.append((2, 3)) cherrypy.tools.break_header = cherrypy.Tool( 'on_end_resource', break_header) class Root: @cherrypy.expose def index(self): return 'hello' @cherrypy.config(**{'tools.break_header.on': True}) def start_response_error(self): return 'salud!' @cherrypy.expose def stat(self, path): with cherrypy.HTTPError.handle(OSError, 404): st = os.stat(path) root = Root() cherrypy.tree.mount(root)
Example #5
Source File: test_config.py From bazarr with GNU General Public License v3.0 | 6 votes |
def test_call_with_kwargs(self): from textwrap import dedent conf = dedent(""" [my] value = dict(foo="buzz", **cherrypy._test_dict) """) test_dict = { 'foo': 'bar', 'bar': 'foo', 'fizz': 'buzz' } cherrypy._test_dict = test_dict fp = StringIOFromNative(conf) cherrypy.config.update(fp) test_dict['foo'] = 'buzz' self.assertEqual(cherrypy.config['my']['value']['foo'], 'buzz') self.assertEqual(cherrypy.config['my']['value'], test_dict) del cherrypy._test_dict
Example #6
Source File: test_iterator.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setup_server(): class Root(object): @cherrypy.expose def count(self, clsname): cherrypy.response.headers['Content-Type'] = 'text/plain' return str(globals()[clsname].created) @cherrypy.expose def getall(self, clsname): cherrypy.response.headers['Content-Type'] = 'text/plain' return globals()[clsname]() @cherrypy.expose @cherrypy.config(**{'response.stream': True}) def stream(self, clsname): return self.getall(clsname) cherrypy.tree.mount(Root())
Example #7
Source File: test_core.py From bazarr with GNU General Public License v3.0 | 6 votes |
def test_bind_ephemeral_port(self): """ A server configured to bind to port 0 will bind to an ephemeral port and indicate that port number on startup. """ cherrypy.config.reset() bind_ephemeral_conf = { 'server.socket_port': 0, } cherrypy.config.update(bind_ephemeral_conf) cherrypy.engine.start() assert cherrypy.server.bound_addr != cherrypy.server.bind_addr _host, port = cherrypy.server.bound_addr assert port > 0 cherrypy.engine.stop() assert cherrypy.server.bind_addr == cherrypy.server.bound_addr
Example #8
Source File: test_iterator.py From bazarr with GNU General Public License v3.0 | 6 votes |
def setup_server(): class Root(object): @cherrypy.expose def count(self, clsname): cherrypy.response.headers['Content-Type'] = 'text/plain' return six.text_type(globals()[clsname].created) @cherrypy.expose def getall(self, clsname): cherrypy.response.headers['Content-Type'] = 'text/plain' return globals()[clsname]() @cherrypy.expose @cherrypy.config(**{'response.stream': True}) def stream(self, clsname): return self.getall(clsname) cherrypy.tree.mount(Root())
Example #9
Source File: test_config.py From bazarr with GNU General Public License v3.0 | 6 votes |
def test_config(self): from textwrap import dedent # variable substitution with [DEFAULT] conf = dedent(""" [DEFAULT] dir = "/some/dir" my.dir = %(dir)s + "/sub" [my] my.dir = %(dir)s + "/my/dir" my.dir2 = %(my.dir)s + '/dir2' """) fp = StringIOFromNative(conf) cherrypy.config.update(fp) self.assertEqual(cherrypy.config['my']['my.dir'], '/some/dir/my/dir') self.assertEqual(cherrypy.config['my'] ['my.dir2'], '/some/dir/my/dir/dir2')
Example #10
Source File: test_conn.py From bazarr with GNU General Public License v3.0 | 6 votes |
def setup_upload_server(): class Root: @cherrypy.expose def upload(self): if not cherrypy.request.method == 'POST': raise AssertionError("'POST' != request.method %r" % cherrypy.request.method) return "thanks for '%s'" % tonative(cherrypy.request.body.read()) cherrypy.tree.mount(Root()) cherrypy.config.update({ 'server.max_request_body_size': 1001, 'server.socket_timeout': 10, 'server.accepted_queue_size': 5, 'server.accepted_queue_timeout': 0.1, })
Example #11
Source File: test_core.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setup_server(): def break_header(): # Add a header after finalize that is invalid cherrypy.serving.response.header_list.append((2, 3)) cherrypy.tools.break_header = cherrypy.Tool( 'on_end_resource', break_header) class Root: @cherrypy.expose def index(self): return 'hello' @cherrypy.config(**{'tools.break_header.on': True}) def start_response_error(self): return 'salud!' @cherrypy.expose def stat(self, path): with cherrypy.HTTPError.handle(OSError, 404): os.stat(path) root = Root() cherrypy.tree.mount(root)
Example #12
Source File: _cpchecker.py From bazarr with GNU General Public License v3.0 | 6 votes |
def _known_types(self, config): msg = ('The config entry %r in section %r is of type %r, ' 'which does not match the expected type %r.') for section, conf in config.items(): if isinstance(conf, dict): for k, v in conf.items(): if v is not None: expected_type = self.known_config_types.get(k, None) vtype = type(v) if expected_type and vtype != expected_type: warnings.warn(msg % (k, section, vtype.__name__, expected_type.__name__)) else: k, v = section, conf if v is not None: expected_type = self.known_config_types.get(k, None) vtype = type(v) if expected_type and vtype != expected_type: warnings.warn(msg % (k, section, vtype.__name__, expected_type.__name__))
Example #13
Source File: _cpchecker.py From bazarr with GNU General Public License v3.0 | 6 votes |
def check_app_config_brackets(self): """Check for Application config with extraneous brackets in section names. """ for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: continue for key in app.config.keys(): if key.startswith('[') or key.endswith(']'): warnings.warn( 'The application mounted at %r has config ' 'section names with extraneous brackets: %r. ' 'Config *files* need brackets; config *dicts* ' '(e.g. passed to tree.mount) do not.' % (sn, key))
Example #14
Source File: _cpchecker.py From bazarr with GNU General Public License v3.0 | 6 votes |
def check_site_config_entries_in_app_config(self): """Check for mounted Applications that have site-scoped config.""" for sn, app in iteritems(cherrypy.tree.apps): if not isinstance(app, cherrypy.Application): continue msg = [] for section, entries in iteritems(app.config): if section.startswith('/'): for key, value in iteritems(entries): for n in ('engine.', 'server.', 'tree.', 'checker.'): if key.startswith(n): msg.append('[%s] %s = %s' % (section, key, value)) if msg: msg.insert(0, 'The application mounted at %r contains the ' 'following config entries, which are only allowed ' 'in site-wide config. Move them to a [global] ' 'section and pass them to cherrypy.config.update() ' 'instead of tree.mount().' % sn) warnings.warn(os.linesep.join(msg))
Example #15
Source File: test_config.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_call_with_kwargs(self): from textwrap import dedent conf = dedent(""" [my] value = dict(foo="buzz", **cherrypy._test_dict) """) test_dict = { 'foo': 'bar', 'bar': 'foo', 'fizz': 'buzz' } cherrypy._test_dict = test_dict fp = StringIOFromNative(conf) cherrypy.config.update(fp) test_dict['foo'] = 'buzz' self.assertEqual(cherrypy.config['my']['value']['foo'], 'buzz') self.assertEqual(cherrypy.config['my']['value'], test_dict) del cherrypy._test_dict
Example #16
Source File: _cpchecker.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_app_config_entries_dont_start_with_script_name(self): """Check for App config with sections that repeat script_name.""" for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: continue if sn == '': continue sn_atoms = sn.strip('/').split('/') for key in app.config.keys(): key_atoms = key.strip('/').split('/') if key_atoms[:len(sn_atoms)] == sn_atoms: warnings.warn( 'The application mounted at %r has config ' 'entries that start with its script name: %r' % (sn, key))
Example #17
Source File: _cpchecker.py From opsbro with MIT License | 6 votes |
def check_app_config_brackets(self): """Check for Application config with extraneous brackets in section names. """ for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: continue for key in app.config.keys(): if key.startswith("[") or key.endswith("]"): warnings.warn( "The application mounted at %r has config " "section names with extraneous brackets: %r. " "Config *files* need brackets; config *dicts* " "(e.g. passed to tree.mount) do not." % (sn, key))
Example #18
Source File: _cpconfig.py From opsbro with MIT License | 6 votes |
def merge(base, other): """Merge one app config (from a dict, file, or filename) into another. If the given config is a filename, it will be appended to the list of files to monitor for "autoreload" changes. """ if isinstance(other, basestring): cherrypy.engine.autoreload.files.add(other) # Load other into base for section, value_map in reprconf.as_dict(other).items(): if not isinstance(value_map, dict): raise ValueError( "Application config must include section headers, but the " "config you tried to merge doesn't have any sections. " "Wrap your config in another dict with paths as section " "headers, for example: {'/': config}.") base.setdefault(section, {}).update(value_map)
Example #19
Source File: _cpchecker.py From opsbro with MIT License | 6 votes |
def check_site_config_entries_in_app_config(self): """Check for mounted Applications that have site-scoped config.""" for sn, app in iteritems(cherrypy.tree.apps): if not isinstance(app, cherrypy.Application): continue msg = [] for section, entries in iteritems(app.config): if section.startswith('/'): for key, value in iteritems(entries): for n in ("engine.", "server.", "tree.", "checker."): if key.startswith(n): msg.append("[%s] %s = %s" % (section, key, value)) if msg: msg.insert(0, "The application mounted at %r contains the " "following config entries, which are only allowed " "in site-wide config. Move them to a [global] " "section and pass them to cherrypy.config.update() " "instead of tree.mount()." % sn) warnings.warn(os.linesep.join(msg))
Example #20
Source File: _cpchecker.py From opsbro with MIT License | 6 votes |
def check_app_config_entries_dont_start_with_script_name(self): """Check for Application config with sections that repeat script_name. """ for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: continue if sn == '': continue sn_atoms = sn.strip("/").split("/") for key in app.config.keys(): key_atoms = key.strip("/").split("/") if key_atoms[:len(sn_atoms)] == sn_atoms: warnings.warn( "The application mounted at %r has config " "entries that start with its script name: %r" % (sn, key))
Example #21
Source File: _cpconfig.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _server_namespace_handler(k, v): """Config handler for the "server" namespace.""" atoms = k.split('.', 1) if len(atoms) > 1: # Special-case config keys of the form 'server.servername.socket_port' # to configure additional HTTP servers. if not hasattr(cherrypy, 'servers'): cherrypy.servers = {} servername, k = atoms if servername not in cherrypy.servers: from cherrypy import _cpserver cherrypy.servers[servername] = _cpserver.Server() # On by default, but 'on = False' can unsubscribe it (see below). cherrypy.servers[servername].subscribe() if k == 'on': if v: cherrypy.servers[servername].subscribe() else: cherrypy.servers[servername].unsubscribe() else: setattr(cherrypy.servers[servername], k, v) else: setattr(cherrypy.server, k, v)
Example #22
Source File: _cpconfig.py From opsbro with MIT License | 6 votes |
def __call__(self, *args, **kwargs): """Decorator for page handlers to set _cp_config.""" if args: raise TypeError( "The cherrypy.config decorator does not accept positional " "arguments; you must use keyword arguments.") def tool_decorator(f): if not hasattr(f, "_cp_config"): f._cp_config = {} for k, v in kwargs.items(): f._cp_config[k] = v return f return tool_decorator # Sphinx begin config.environments
Example #23
Source File: _cpchecker.py From bazarr with GNU General Public License v3.0 | 6 votes |
def check_app_config_entries_dont_start_with_script_name(self): """Check for Application config with sections that repeat script_name. """ for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue if not app.config: continue if sn == '': continue sn_atoms = sn.strip('/').split('/') for key in app.config.keys(): key_atoms = key.strip('/').split('/') if key_atoms[:len(sn_atoms)] == sn_atoms: warnings.warn( 'The application mounted at %r has config ' 'entries that start with its script name: %r' % (sn, key))
Example #24
Source File: test_etags.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def setup_server(): class Root: @cherrypy.expose def resource(self): return 'Oh wah ta goo Siam.' @cherrypy.expose def fail(self, code): code = int(code) if 300 <= code <= 399: raise cherrypy.HTTPRedirect([], code) else: raise cherrypy.HTTPError(code) @cherrypy.expose # In Python 3, tools.encode is on by default @cherrypy.config(**{'tools.encode.on': True}) def unicoded(self): return ntou('I am a \u1ee4nicode string.', 'escape') conf = {'/': {'tools.etags.on': True, 'tools.etags.autotags': True, }} cherrypy.tree.mount(Root(), config=conf)
Example #25
Source File: test_params.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_syntax(self): if sys.version_info < (3,): return self.skip('skipped (Python 3 only)') code = textwrap.dedent(""" class Root: @cherrypy.expose @cherrypy.tools.params() def resource(self, limit: int): return type(limit).__name__ conf = {'/': {'tools.params.on': True}} cherrypy.tree.mount(Root(), config=conf) """) exec(code) self.getPage('/resource?limit=0') self.assertStatus(200) self.assertBody('int')
Example #26
Source File: jsontools.py From opsbro with MIT License | 5 votes |
def json_out(content_type='application/json', debug=False, handler=json_handler): """Wrap request.handler to serialize its output to JSON. Sets Content-Type. If the given content_type is None, the Content-Type response header is not set. Provide your own handler to use a custom encoder. For example cherrypy.config['tools.json_out.handler'] = <function>, or @json_out(handler=function). You must be using Python 2.6 or greater, or have the 'simplejson' package importable; otherwise, ValueError is raised during processing. """ request = cherrypy.serving.request # request.handler may be set to None by e.g. the caching tool # to signal to all components that a response body has already # been attached, in which case we don't need to wrap anything. if request.handler is None: return if debug: cherrypy.log('Replacing %s with JSON handler' % request.handler, 'TOOLS.JSON_OUT') request._json_inner_handler = request.handler request.handler = handler if content_type is not None: if debug: cherrypy.log('Setting Content-Type to %s' % content_type, 'TOOLS.JSON_OUT') cherrypy.serving.response.headers['Content-Type'] = content_type
Example #27
Source File: _cpconfig.py From opsbro with MIT License | 5 votes |
def update(self, config): """Update self from a dict, file or filename.""" if isinstance(config, basestring): # Filename cherrypy.engine.autoreload.files.add(config) reprconf.Config.update(self, config)
Example #28
Source File: _cpchecker.py From opsbro with MIT License | 5 votes |
def check_config_types(self): """Assert that config values are of the same type as default values.""" self._known_types(cherrypy.config) for sn, app in cherrypy.tree.apps.items(): if not isinstance(app, cherrypy.Application): continue self._known_types(app.config) # -------------------- Specific config warnings -------------------- #
Example #29
Source File: test_params.py From bazarr with GNU General Public License v3.0 | 5 votes |
def setup_server(): class Root: @cherrypy.expose @cherrypy.tools.params() def resource(self, limit=None, sort=None): return type(limit).__name__ # for testing on Py 2 resource.__annotations__ = {'limit': int} conf = {'/': {'tools.params.on': True}} cherrypy.tree.mount(Root(), config=conf)
Example #30
Source File: test_config.py From bazarr with GNU General Public License v3.0 | 5 votes |
def testConfig(self): tests = [ ('/', 'nex', 'None'), ('/', 'foo', 'this'), ('/', 'bar', 'that'), ('/xyz', 'foo', 'this'), ('/foo/', 'foo', 'this2'), ('/foo/', 'bar', 'that'), ('/foo/', 'bax', 'None'), ('/foo/bar', 'baz', "'that2'"), ('/foo/nex', 'baz', 'that2'), # If 'foo' == 'this', then the mount point '/another' leaks into # '/'. ('/another/', 'foo', 'None'), ] for path, key, expected in tests: self.getPage(path + '?key=' + key) self.assertBody(expected) expectedconf = { # From CP defaults 'tools.log_headers.on': False, 'tools.log_tracebacks.on': True, 'request.show_tracebacks': True, 'log.screen': False, 'environment': 'test_suite', 'engine.autoreload.on': False, # From global config 'luxuryyacht': 'throatwobblermangrove', # From Root._cp_config 'bar': 'that', # From Foo._cp_config 'baz': 'that2', # From Foo.bar._cp_config 'foo': 'this3', 'bax': 'this4', } for key, expected in expectedconf.items(): self.getPage('/foo/bar?key=' + key) self.assertBody(repr(expected))