Exemple #1
0
    def setup(self):
        # The only reason this method isn't in __init__ is so that
        # "import cherrypy" can create an Engine() without a circular ref.
        conf = cherrypy.config.get

        # Output config options to log
        if conf("server.log_config_options", True):
            cherrypy.config.outputConfigMap()

        # Hmmm...we *could* check config in _start instead, but I think
        # most people would like CP to fail before autoreload kicks in.
        err = cherrypy.WrongConfigValue
        for name, section in cherrypy.config.configs.iteritems():
            for k, v in section.iteritems():
                if k == "server.environment":
                    if v and v not in cherrypy.config.environments:
                        raise err("'%s' is not a registered environment." % v)

        if cherrypy.codecoverage:
            from cherrypy.lib import covercp

            covercp.start()

        # If sessions are stored in files and we
        # use threading, we need a lock on the file
        if conf("server.thread_pool") > 1 and conf("session.storage_type") == "file":
            cherrypy._sessionFileLock = threading.RLock()

        # set cgi.maxlen which will limit the size of POST request bodies
        cgi.maxlen = conf("server.max_request_size")

        # Set up the profiler if requested.
        if conf("profiling.on", False):
            ppath = conf("profiling.path", "")
            cherrypy.profiler = profiler.Profiler(ppath)
        else:
            cherrypy.profiler = None

        # Initialize the built in filters
        filters.init()
def setup_server():

    class Numerify(BaseFilter):
        
        def on_start_resource(self):
            m = cherrypy.config.get("numerify_filter.map", {})
            cherrypy.request.numerify_map = m.items()
        
        def before_finalize(self):
            if not cherrypy.config.get("numerify_filter.on", False):
                return
            
            def number_it(body):
                for chunk in body:
                    for k, v in cherrypy.request.numerify_map:
                        chunk = chunk.replace(k, v)
                    yield chunk
            cherrypy.response.body = number_it(cherrypy.response.body)
    
    
    # It's not mandatory to inherit from BaseFilter.
    class NadsatFilter:
        
        def __init__(self):
            self.counter = 0
            self.ended = {}
        
        def before_main(self):
            cherrypy.request.counter = self.counter = self.counter + 1
            self.ended[cherrypy.request.counter] = False
        
        def before_finalize(self):
            def nadsat_it_up(body):
                for chunk in body:
                    chunk = chunk.replace("good", "horrorshow")
                    chunk = chunk.replace("piece", "lomtick")
                    yield chunk
            cherrypy.response.body = nadsat_it_up(cherrypy.response.body)
        
        def on_end_request(self):
            # This runs after the request has been completely written out.
            cherrypy.response.body = "razdrez"
            self.ended[cherrypy.request.counter] = True



    class Root:
        def index(self):
            return "Howdy earth!"
        index.exposed = True

    cherrypy.root = Root()


    class TestType(type):
        """Metaclass which automatically exposes all functions in each subclass,
        and adds an instance of the subclass as an attribute of cherrypy.root.
        """
        def __init__(cls, name, bases, dct):
            type.__init__(name, bases, dct)
            for value in dct.itervalues():
                if isinstance(value, types.FunctionType):
                    value.exposed = True
            setattr(cherrypy.root, name.lower(), cls())
    class Test(object):
        __metaclass__ = TestType


    class CPFilterList(Test):
        
        # METHOD ONE:
        # Use _cp_filters (old name: _cpFilterList)
        _cp_filters = [NadsatFilter()]
        
        def index(self):
            return "A good piece of cherry pie"
        
        def ended(self, id):
            return repr(self._cp_filters[0].ended[int(id)])
        
        def err(self):
            raise ValueError()
        
        def errinstream(self):
            raise ValueError()
            yield "confidential"
        
        def restricted(self):
            return "Welcome!"
        
        def err_in_onstart(self):
            return "success!"


    cherrypy.config.update({
        'global': {
            # METHOD TWO:
            # Declare a classname in server.input_filters.
            'server.input_filters': ["cherrypy.test.test_custom_filters.AccessFilter"],
            'server.log_to_screen': False,
            'server.environment': 'production',
            'server.show_tracebacks': True,
        },
        '/cpfilterlist': {
            'numerify_filter.on': True,
            'numerify_filter.map': {"pie": "3.14159"}
        },
        '/cpfilterlist/restricted': {
            'access_filter.on': True,
            'server.show_tracebacks': False,
        },
        '/cpfilterlist/errinstream': {
            'stream_response': True,
        },
        '/cpfilterlist/err_in_onstart': {
            # Because this isn't a dict, on_start_resource will error.
            'numerify_filter.map': "pie->3.14159"
        },
    })

    # METHOD THREE:
    # Insert a class directly into the filters.output_filters chain.
    # You can also insert a string, but we're effectively testing
    # using-a-string via the config file.
    filters.input_filters.insert(0, Numerify)
    filters.output_filters.insert(0, Numerify)

    # We have to call filters.init() here (if we want methods #2 and #3
    # to work), because the test suite may already have run server.start()
    # (which is where filters.init() is usually called).
    filters.init()