コード例 #1
0
def init_cherrypy(arguments=None):
    #### Mount static folders from modules marked for introspection
    arguments = arguments or []
    CONFIGUER = TvbProfile.current.web.CHERRYPY_CONFIGURATION
    for module in arguments:
        module_inst = importlib.import_module(str(module))
        module_path = os.path.dirname(os.path.abspath(module_inst.__file__))
        CONFIGUER["/static_" + str(module)] = {'tools.staticdir.on': True,
                                               'tools.staticdir.dir': '.',
                                               'tools.staticdir.root': module_path}

    #### Mount controllers, and specify the root URL for them.
    cherrypy.tree.mount(BaseController(), "/", config=CONFIGUER)
    cherrypy.tree.mount(UserController(), "/user/", config=CONFIGUER)
    cherrypy.tree.mount(ProjectController(), "/project/", config=CONFIGUER)
    cherrypy.tree.mount(FigureController(), "/project/figure/", config=CONFIGUER)
    cherrypy.tree.mount(FlowController(), "/flow/", config=CONFIGUER)
    cherrypy.tree.mount(SettingsController(), "/settings/", config=CONFIGUER)
    cherrypy.tree.mount(HelpController(), "/help/", config=CONFIGUER)
    cherrypy.tree.mount(SimulatorController(), "/burst/", config=CONFIGUER)
    cherrypy.tree.mount(ParameterExplorationController(), "/burst/explore/", config=CONFIGUER)
    cherrypy.tree.mount(DynamicModelController(), "/burst/dynamic/", config=CONFIGUER)
    cherrypy.tree.mount(SpatioTemporalController(), "/spatial/", config=CONFIGUER)
    cherrypy.tree.mount(RegionsModelParametersController(), "/burst/modelparameters/regions/", config=CONFIGUER)
    cherrypy.tree.mount(SurfaceModelParametersController(), "/spatial/modelparameters/surface/", config=CONFIGUER)
    cherrypy.tree.mount(RegionStimulusController(), "/spatial/stimulus/region/", config=CONFIGUER)
    cherrypy.tree.mount(SurfaceStimulusController(), "/spatial/stimulus/surface/", config=CONFIGUER)
    cherrypy.tree.mount(LocalConnectivityController(), "/spatial/localconnectivity/", config=CONFIGUER)
    cherrypy.tree.mount(NoiseConfigurationController(), "/burst/noise/", config=CONFIGUER)
    cherrypy.tree.mount(HPCController(), "/hpc/", config=CONFIGUER)

    cherrypy.config.update(CONFIGUER)

    # ----------------- Register additional request handlers -----------------
    # This tool checks for MAX upload size
    cherrypy.tools.upload = Tool('on_start_resource', RequestHandler.check_upload_size)
    # This tools clean up files on disk (mainly after export)
    cherrypy.tools.cleanup = Tool('on_end_request', RequestHandler.clean_files_on_disk)
    # ----------------- End register additional request handlers ----------------

    # Register housekeeping job
    if TvbProfile.current.hpc.IS_HPC_RUN and TvbProfile.current.hpc.CAN_RUN_HPC:
        cherrypy.engine.housekeeper = cherrypy.process.plugins.BackgroundTask(
            TvbProfile.current.hpc.BACKGROUND_JOB_INTERVAL, HPCOperationService.check_operations_job)
        cherrypy.engine.housekeeper.start()

    # HTTP Server is fired now ######
    cherrypy.engine.start()
コード例 #2
0
ファイル: buffet.py プロジェクト: BSierakowski/personal_code
    def __init__(self, engine_name, template_root=None, config_section=None):
        if template_root:
            self.template_root = template_root
        else:
            self.template_root = '.'
        if not config_section:
            config_section = engine_name + '_settings'
        engine_opts = cherrypy.config.get(config_section, {})
        Engine = available_engines.get(engine_name, None)
        if not Engine:
            msg = 'Please install a plugin for "%s" to use its functionality'
            raise TemplateEngineMissing(msg % engine_name)
        self.engine = Engine(cherrypy_vars, engine_opts)

        #initialize the parent, hooking before_finalize to our before_finalize
        #method
        Tool.__init__(self, 'before_finalize', self.before_finalize)
コード例 #3
0
ファイル: buffet.py プロジェクト: thor509/personal_code
    def __init__(self, engine_name, template_root=None, config_section=None):
        if template_root:
            self.template_root = template_root
        else:
            self.template_root = '.'
        if not config_section:
            config_section = engine_name + '_settings'
        engine_opts = cherrypy.config.get(config_section, {})
        Engine = available_engines.get(engine_name, None)
        if not Engine:
            msg = 'Please install a plugin for "%s" to use its functionality'
            raise TemplateEngineMissing(msg % engine_name)
        self.engine = Engine(cherrypy_vars, engine_opts)

        #initialize the parent, hooking before_finalize to our before_finalize
        #method
        Tool.__init__(self, 'before_finalize', self.before_finalize)
コード例 #4
0
ファイル: webgate.py プロジェクト: bharathi26/cape
    def _start_Engine(self):
        logger = cherrypy.log
        logger.logger_root = ''

        cherrypy.config.update({
            'server.socket_port': self.Configuration['port'],
            'server.socket_host': '0.0.0.0',
        })

        if self.Configuration['debug']:
            self.loginfo(
                "Enabling debug (autoreload) mode for staticdir '%s'" %
                self.Configuration['staticdir'])

            for folder, subs, files in os.walk(
                    self.Configuration['staticdir']):
                for filename in files:
                    self.logdebug("Autoreload enabled for: '%s'" %
                                  str(filename))
                    cherrypy.engine.autoreload.files.add(filename)

        cherrypy.tools.clientconnect = Tool('on_start_resource',
                                            self._ev_client_connect)
        config = {
            '/static': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': self.Configuration['staticdir']
            },
        }

        self._readTemplates()

        self.webclient = self.WebClient(gateway=self,
                                        loader=self.loader,
                                        header=self.header)

        cherrypy.tree.mount(self.webclient, "/", config=config)

        cherrypy.engine.start()
        return True  # TODO: Make sure we really started it..
コード例 #5
0
    try:
        uid = int(uid)
        user = Backend('user').find(uid)
        if not user:
            user = _guest
    except TypeError:
        user = _guest
    request.user = user


def clear_user():
    """Clear user in current request session"""
    del request.user


tools.init_user = Tool('before_request_body', init_user)
tools.clear_user = Tool('before_finalize', clear_user)


def jsonify(f):
    @wraps(f)
    def _jsonify(*args, **kw):
        data = f(*args, **kw)
        data = json_encode(data)
        response.headers['Content-Type'] = 'application/json'
        return data

    return _jsonify


def set_secure_cookie(name, value, max_age_days=30, **kwargs):
コード例 #6
0
    UNIQUE(Name)
)""" % globals())
        c.execute(
            """
INSERT INTO Clicks(Name,NumClicks)
    SELECT %s,0
    WHERE NOT EXISTS (SELECT 1 FROM Clicks WHERE Name=%s)
""", (name, name))
        c.execute("UPDATE Clicks SET NumClicks=NumClicks+1 WHERE Name=%s",
                  (name, ))
        c.execute("COMMIT")
    except:
        c.execute("ROLLBACK")


cherrypy.tools.click_count = Tool('on_end_request', click_count)


class WwwServer(Thread):
    cp_config = {
        '/images': {
            'tools.expires.on':
            True,
            'tools.expires.secs':
            3600 * 24 * 7,
            'tools.staticdir.on':
            True,
            'tools.staticdir.dir':
            abspath(os.path.join(static_base_dir, "images")),
        },
        '/bootstrap': {
コード例 #7
0
 def __init__(self):
     Tool.__init__(self, 'before_request_body', self.upgrade)
コード例 #8
0
 def __init__(self):
     Tool.__init__(self, 'before_request_body', self.upgrade)
コード例 #9
0
ファイル: Utils.py プロジェクト: mbandrews/dqmgui
 def __init__(self):
   Tool.__init__(self, 'before_handler',
                 self.load, priority=10)
コード例 #10
0
def init_cherrypy(arguments=None):
    #### Mount static folders from modules marked for introspection
    arguments = arguments or []
    CONFIGUER = TVBSettings.CHERRYPY_CONFIGURATION
    for module in arguments:
        module_inst = __import__(str(module), globals(), locals(),
                                 ["__init__"])
        module_path = os.path.dirname(os.path.abspath(module_inst.__file__))
        CONFIGUER["/static_" + str(module)] = {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': '.',
            'tools.staticdir.root': module_path
        }

    #### Mount controllers, and specify the root URL for them.
    cherrypy.tree.mount(BaseController(), "/", config=CONFIGUER)
    cherrypy.tree.mount(UserController(), "/user/", config=CONFIGUER)
    cherrypy.tree.mount(ProjectController(), "/project/", config=CONFIGUER)
    cherrypy.tree.mount(FigureController(),
                        "/project/figure/",
                        config=CONFIGUER)
    cherrypy.tree.mount(FlowController(), "/flow/", config=CONFIGUER)
    cherrypy.tree.mount(SettingsController(), "/settings/", config=CONFIGUER)
    cherrypy.tree.mount(DTIPipelineController(),
                        "/pipeline/",
                        config=CONFIGUER)
    cherrypy.tree.mount(HelpController(), "/help/", config=CONFIGUER)
    cherrypy.tree.mount(BurstController(), "/burst/", config=CONFIGUER)
    cherrypy.tree.mount(ParameterExplorationController(),
                        "/burst/explore/",
                        config=CONFIGUER)
    cherrypy.tree.mount(SpatioTemporalController(),
                        "/spatial/",
                        config=CONFIGUER)
    cherrypy.tree.mount(RegionsModelParametersController(),
                        "/spatial/modelparameters/regions/",
                        config=CONFIGUER)
    cherrypy.tree.mount(SurfaceModelParametersController(),
                        "/spatial/modelparameters/surface/",
                        config=CONFIGUER)
    cherrypy.tree.mount(RegionStimulusController(),
                        "/spatial/stimulus/region/",
                        config=CONFIGUER)
    cherrypy.tree.mount(SurfaceStimulusController(),
                        "/spatial/stimulus/surface/",
                        config=CONFIGUER)
    cherrypy.tree.mount(LocalConnectivityController(),
                        "/spatial/localconnectivity/",
                        config=CONFIGUER)
    cherrypy.config.update(CONFIGUER)

    #----------------- Register additional request handlers -----------------
    # This tool checks for MAX upload size
    cherrypy.tools.upload = Tool('on_start_resource',
                                 RequestHandler.check_upload_size)
    # This tools clean up files on disk (mainly after export)
    cherrypy.tools.cleanup = Tool('on_end_request',
                                  RequestHandler.clean_files_on_disk)
    #----------------- End register additional request handlers ----------------

    #### HTTP Server is fired now ######
    cherrypy.engine.start()
コード例 #11
0
 def __init__(self):
     Tool.__init__(self, 'before_handler', self.load, priority=10)
コード例 #12
0
ファイル: Tools.py プロジェクト: tsarangi/WMCore
    """Utility to time stamp the start of HTTP request handling."""
    request.start_time = time.time()


def set_proxy_base(base=None):
    """Utility to correctly handle requests behind a proxy."""
    scheme = request.headers.get('X-Forwarded-Proto',
                                 request.base[:request.base.find("://")])
    base = request.headers.get('X-Forwarded-Host', base)
    if not base:
        port = cherrypy.request.local.port
        if port == 80:
            base = 'localhost'
        else:
            base = 'localhost:%s' % port

    base = base.split(',')[0].strip()
    if base.find("://") == -1:
        base = scheme + "://" + base
    request.base = base

    xff = request.headers.get('X-Forwarded-For')
    if xff:
        xff = xff.split(',')[0].strip()
        request.remote.ip = xff


tools.cms_auth = RESTAuth()
tools.time = Tool('on_start_resource', set_request_time)
tools.proxy = Tool('before_request_body', set_proxy_base, priority=30)
コード例 #13
0
ファイル: render.py プロジェクト: dichodaemon/hatajo
    params = oldHandler( *args, **kargs ) 
    
    if template and type( params ) != list:
      params["_js"] = []
      params["_css"] = []
      params["_code"] = []
      params["_head"] = []
      params["user"] = cherrypy.session.get( "user" )
      t = lookup.get_template( template )
      t.output_encoding = 'utf-8'
      result = t.render_unicode( **params )
      if template[-5:] == ".html":
        return str( tidy.parseString( 
          result.encode( "utf-8" ), 
          output_xhtml = True, 
          indent = True, 
          tidy_mark = 0, 
          char_encoding = "utf8",
          output_encoding = "utf8",
          wrap = 120
        ) )
      else:
        return result


  cherrypy.request.handler = wrapper

#-------------------------------------------------------------------------------

tools.render = Tool( "before_handler", transform )