Example #1
0
 def load_config(filename):
     filename = os.path.normpath(os.path.abspath(filename))
     config = appconfig('config:' + filename)
     # Load the logging options
     # (must be done before environment is loaded or sqlalchemy won't log)
     logging_config.fileConfig(filename)
     return config
 def load_config(filename):
     filename = os.path.normpath(os.path.abspath(filename))
     config = appconfig('config:'+filename)
     # Load the logging options
     # (must be done before environment is loaded or sqlalchemy won't log)
     logging_config.fileConfig(filename)
     return config
    def __init__(self,
                 app=None,
                 cfgFilePath=None,
                 port=7443,
                 host='0.0.0.0',
                 ssl_context=None):
        """Load an application configuration from cfgFilePath ini file and 
        instantiate Paste server object
        """
        self.__thread = None

        if cfgFilePath:
            if app:
                raise KeyError('Set either the "cfgFilePath" or "app" keyword '
                               'but not both')

            fileConfig(cfgFilePath,
                       defaults={'here': path.dirname(cfgFilePath)})
            app = loadapp('config:%s' % cfgFilePath)

        elif app is None:
            raise KeyError('Either the "cfgFilePath" or "app" keyword must be '
                           'set')

        self.__pasteServer = paste.httpserver.serve(app,
                                                    host=host,
                                                    port=port,
                                                    start_loop=False,
                                                    ssl_context=ssl_context)
def test5():
    loggerDict = logging.getLogger().manager.loggerDict
    logging._acquireLock()
    try:
        saved_handlers = logging._handlers.copy()
        if hasattr(logging, '_handlerList'):
            saved_handler_list = logging._handlerList[:]
        saved_loggers = loggerDict.copy()
    finally:
        logging._releaseLock()
    try:
        fn = tempfile.mktemp(".ini")
        f = open(fn, "w")
        f.write(test5_config)
        f.close()
        logging_config.fileConfig(fn)
        try:
            raise KeyError
        except KeyError:
            logging.exception("just testing")
        os.remove(fn)
        hdlr = logging.getLogger().handlers[0]
        logging.getLogger().handlers.remove(hdlr)
    finally:
        logging._acquireLock()
        try:
            logging._handlers.clear()
            logging._handlers.update(saved_handlers)
            if hasattr(logging, '_handlerList'):
                logging._handlerList[:] = saved_handler_list
            loggerDict = logging.getLogger().manager.loggerDict
            loggerDict.clear()
            loggerDict.update(saved_loggers)
        finally:
            logging._releaseLock()
def test5():
    loggerDict = logging.getLogger().manager.loggerDict
    logging._acquireLock()
    try:
        saved_handlers = logging._handlers.copy()
        if hasattr(logging, '_handlerList'):
            saved_handler_list = logging._handlerList[:]
        saved_loggers = loggerDict.copy()
    finally:
        logging._releaseLock()
    try:
        fn = tempfile.mktemp(".ini")
        f = open(fn, "w")
        f.write(test5_config)
        f.close()
        logging_config.fileConfig(fn)
        try:
            raise KeyError
        except KeyError:
            logging.exception("just testing")
        os.remove(fn)
        hdlr = logging.getLogger().handlers[0]
        logging.getLogger().handlers.remove(hdlr)
    finally:
        logging._acquireLock()
        try:
            logging._handlers.clear()
            logging._handlers.update(saved_handlers)
            if hasattr(logging, '_handlerList'):
                logging._handlerList[:] = saved_handler_list
            loggerDict = logging.getLogger().manager.loggerDict
            loggerDict.clear()
            loggerDict.update(saved_loggers)
        finally:
            logging._releaseLock()
Example #6
0
    def __init__(self, *args, **kwargs):
        TestCase.__init__(self, *args, **kwargs)

        fileConfig(test_file)
        if pylons.test.pylonsapp:
            wsgiapp = pylons.test.pylonsapp
        else:
            wsgiapp = loadapp('config:test.ini', relative_to=conf_dir)
        self.app = paste.fixture.TestApp(wsgiapp)
Example #7
0
 def logging_file_config(self, config_file):
     """
     Setup logging via the logging module's fileConfig function with the
     specified ``config_file``, if applicable.
     """
     parser = ConfigParser.ConfigParser()
     parser.read([config_file])
     if parser.has_section('loggers'):
         fileConfig(config_file)
Example #8
0
 def logging_file_config(self, config_file):
     """
     Setup logging via the logging module's fileConfig function with the
     specified ``config_file``, if applicable.
     """
     parser = ConfigParser.ConfigParser()
     parser.read([config_file])
     if parser.has_section('loggers'):
         fileConfig(config_file)
Example #9
0
 def _load_config(self):
     from paste.deploy import appconfig
     if not self.options.config:
         msg = 'No config file supplied'
         raise self.BadCommand(msg)
     self.filename = os.path.abspath(self.options.config)
     try:
         fileConfig(self.filename)
     except Exception: pass
     self.config = appconfig('config:' + self.filename)
Example #10
0
 def _app_config(self):
     """
     This is the first part of CkanCommand._load_config()
     """
     from paste.deploy import appconfig
     if not self.options.config:
         msg = 'No config file supplied'
         raise self.BadCommand(msg)
     self.filename = os.path.abspath(self.options.config)
     if not os.path.exists(self.filename):
         raise AssertionError('Config filename %r does not exist.' % self.filename)
     fileConfig(self.filename)
     conf = appconfig('config:' + self.filename)
Example #11
0
 def _app_config(self):
     """
     This is the first part of CkanCommand._load_config()
     """
     from paste.deploy import appconfig
     if not self.options.config:
         msg = 'No config file supplied'
         raise self.BadCommand(msg)
     self.filename = os.path.abspath(self.options.config)
     if not os.path.exists(self.filename):
         raise AssertionError('Config filename %r does not exist.' % self.filename)
     fileConfig(self.filename)
     conf = appconfig('config:' + self.filename)
Example #12
0
File: cli.py Project: arkka/ckan
    def _load_config_into_test_app(self):
        from paste.deploy import loadapp
        import paste.fixture
        if not self.options.config:
            msg = 'No config file supplied'
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        if not os.path.exists(self.filename):
            raise AssertionError('Config filename %r does not exist.' % self.filename)
        fileConfig(self.filename)

        wsgiapp = loadapp('config:' + self.filename)
        self.app = paste.fixture.TestApp(wsgiapp)
Example #13
0
def init_mediadrop(config_filename, here_dir=None, disable_logging=False):
    if not os.path.exists(config_filename):
        raise IOError('Config file %r does not exist.' % config_filename)
    if here_dir is None:
        here_dir = os.getcwd()
    if not disable_logging:
        logging_config.fileConfig(config_filename)

    config_name = 'config:%s' % config_filename
    # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
    # will automatically be initialized and restored via the registry
    # restorer along with the other StackedObjectProxys
    # Load app config into paste.deploy to simulate request config
    # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
    # code
    conf = appconfig(config_name, relative_to=here_dir)
    conf.update(dict(app_conf=conf.local_conf, global_conf=conf.global_conf))
    paste.deploy.config.CONFIG.push_thread_config(conf)

    # Load locals and populate with objects for use in shell
    sys.path.insert(0, here_dir)

    # WebOb 1.2+ does not support unicode_errors/decode_param_names anymore for
    # the Request() class so we need to override Pylons' defaults to prevent
    # DeprecationWarnings (only shown in Python 2.6 by default).
    webob_request_options = {
        'charset': 'utf-8',
        'errors': None,
        'decode_param_names': None,
        'language': 'en-us',
    }
    global_conf = {'pylons.request_options': webob_request_options}
    # Load the wsgi app first so that everything is initialized right
    wsgiapp = loadapp(config_name,
                      relative_to=here_dir,
                      global_conf=global_conf)
    test_app = TestApp(wsgiapp)

    # Query the test app to setup the environment
    tresponse = test_app.get('/_test_vars')
    request_id = int(tresponse.body)

    # Disable restoration during test_app requests
    test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end(
    )
    test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(
        request_id)

    # Restore the state of the Pylons special objects (StackedObjectProxies)
    paste.registry.restorer.restoration_begin(request_id)
Example #14
0
def uwsgi_pypy_paste_loader(config):
    global wsgi_application
    c = ffi.string(config)
    if c.startswith('config:'):
        c = c[7:]
    if c[0] != '/':
        c = os.getcwd() + '/' + c
    try:
        from paste.script.util.logging_config import fileConfig
        fileConfig(c)
    except ImportError:
        print "PyPy WARNING: unable to load paste.script.util.logging_config"
    from paste.deploy import loadapp
    wsgi_application = loadapp('config:%s' % c)
Example #15
0
def uwsgi_pypy_paste_loader(config):
    global wsgi_application
    c = ffi.string(config)
    if c.startswith('config:'):
        c = c[7:]
    if c[0] != '/':
        c = os.getcwd() + '/' + c
    try:
        from paste.script.util.logging_config import fileConfig
        fileConfig(c)
    except ImportError:
        print "PyPy WARNING: unable to load paste.script.util.logging_config"
    from paste.deploy import loadapp
    wsgi_application = loadapp('config:%s' % c)
Example #16
0
File: cli.py Project: okfn/ckan-old
    def _load_config(self):
        from paste.deploy import appconfig
        from ckan.config.environment import load_environment

        if not self.options.config:
            msg = "No config file supplied"
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        try:
            fileConfig(self.filename)
        except Exception:
            pass
        conf = appconfig("config:" + self.filename)
        load_environment(conf.global_conf, conf.local_conf)
Example #17
0
def dbsetup():
    from paste.registry import Registry
    from paste.script.util.logging_config import fileConfig
    from paste.deploy import appconfig
    filename = os.path.abspath("../ckan/development.ini")
    if not os.path.exists(filename):
        raise AssertionError('Config filename %r does not exist.' % filename)
    fileConfig(filename)
    conf = appconfig('config:' + filename)
    assert 'ckan' not in dir() # otherwise loggers would be disabled

    # We have now loaded the config. Now we can import ckan for the
    # first time.
    from ckan.config.environment import load_environment
    load_environment(conf.global_conf, conf.local_conf)
def dbsetup():
    from paste.registry import Registry
    from paste.script.util.logging_config import fileConfig
    from paste.deploy import appconfig
    filename = os.path.abspath("../ckan/development.ini")
    if not os.path.exists(filename):
        raise AssertionError('Config filename %r does not exist.' % filename)
    fileConfig(filename)
    conf = appconfig('config:' + filename)
    assert 'ckan' not in dir()  # otherwise loggers would be disabled

    # We have now loaded the config. Now we can import ckan for the
    # first time.
    from ckan.config.environment import load_environment
    load_environment(conf.global_conf, conf.local_conf)
Example #19
0
def init_mediadrop(config_filename, here_dir=None, disable_logging=False):
    if not os.path.exists(config_filename):
        raise IOError('Config file %r does not exist.' % config_filename)
    if here_dir is None:
        here_dir = os.getcwd()
    if not disable_logging:
        logging_config.fileConfig(config_filename)

    config_name = 'config:%s' % config_filename
    # XXX: Note, initializing CONFIG here is Legacy support. pylons.config
    # will automatically be initialized and restored via the registry
    # restorer along with the other StackedObjectProxys
    # Load app config into paste.deploy to simulate request config
    # Setup the Paste CONFIG object, adding app_conf/global_conf for legacy
    # code
    conf = appconfig(config_name, relative_to=here_dir)
    conf.update(dict(app_conf=conf.local_conf,
                     global_conf=conf.global_conf))
    paste.deploy.config.CONFIG.push_thread_config(conf)

    # Load locals and populate with objects for use in shell
    sys.path.insert(0, here_dir)

    # WebOb 1.2+ does not support unicode_errors/decode_param_names anymore for
    # the Request() class so we need to override Pylons' defaults to prevent
    # DeprecationWarnings (only shown in Python 2.6 by default).
    webob_request_options = {
        'charset': 'utf-8',
        'errors': None,
        'decode_param_names': None,
        'language': 'en-us',
    }
    global_conf = {'pylons.request_options': webob_request_options}
    # Load the wsgi app first so that everything is initialized right
    wsgiapp = loadapp(config_name, relative_to=here_dir, global_conf=global_conf)
    test_app = TestApp(wsgiapp)

    # Query the test app to setup the environment
    tresponse = test_app.get('/_test_vars')
    request_id = int(tresponse.body)

    # Disable restoration during test_app requests
    test_app.pre_request_hook = lambda self: paste.registry.restorer.restoration_end()
    test_app.post_request_hook = lambda self: paste.registry.restorer.restoration_begin(request_id)

    # Restore the state of the Pylons special objects (StackedObjectProxies)
    paste.registry.restorer.restoration_begin(request_id)
Example #20
0
    def _load_config(self):
        from paste.deploy import appconfig
        if not self.options.config:
            msg = 'No config file supplied'
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        if not os.path.exists(self.filename):
            raise AssertionError('Config filename %r does not exist.' % self.filename)
        fileConfig (self.filename)
        conf = appconfig('config:' + self.filename)
        # We have now loaded the config. Now we can import helloworld for the first time.
        from helloworld.config.environment import load_environment
        load_environment (conf.global_conf, conf.local_conf)

        self.registry = Registry()
        self.registry.prepare()
        return
Example #21
0
def uwsgi_pypy_paste_loader(config):
    """
    load a .ini paste app
    """
    global wsgi_application
    c = ffi.string(config).decode()
    lhs, sep, rhs = c.partition('config:')
    if sep and not lhs:
        c = rhs
    c = os.path.abspath(c)
    try:
        from paste.script.util.logging_config import fileConfig
        fileConfig(c)
    except ImportError:
        print("PyPy WARNING: unable to load paste.script.util.logging_config")
    from paste.deploy import loadapp
    wsgi_application = loadapp('config:%s' % c)
Example #22
0
def main():
    parser = OptionParser(
        usage = "%prog [config_file]",
        version = "0.1",
        description = "bots network launcher"
    )
    parser.add_option('-c', '--config',
        dest = 'cfgfile',
        help = 'path to configuration file'
    )
    parser.add_option('-p', '--sqla-prefix',
        dest = 'sqlaprefix',
        default = 'sqlalchemy.',
        help = 'SQLAlchemy config prefix (default: %default)'
    )

    options, args = parser.parse_args()
    if not options.cfgfile and not args:
        parser.error("You need to pass the config file")
    elif not options.cfgfile and args:
        options.cfgfile = args[0]

    cfgfile = os.path.abspath(options.cfgfile)
    loadapp('config:%s' % os.path.abspath(cfgfile))
    config['pylons.g'].sa_engine = engine_from_config(config,
                                                      options.sqlaprefix)

    print 'setting up logging'
    from paste.script.util.logging_config import fileConfig
#    import logging.config
#    logging.config.fileConfig(open(cfgfile, 'r'))
    fileConfig(cfgfile)
    log = logging.getLogger(__name__)
    log.debug('foo......')
    log.error('bar!')

    import network, irclib
    bnw = network.IRCBotsNetwork()
    try:
        bnw.connect_all()
        bnw.process_all()
    except (KeyboardInterrupt, irclib.ServerNotConnectedError):
        bnw.quit()
    finally:
        sys.exit()
Example #23
0
    def _load_config(self):
        from paste.deploy import appconfig
        from ckan.config.environment import load_environment
        if not self.options.config:
            msg = 'No config file supplied'
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        try:
            fileConfig(self.filename)
        except Exception: pass
        conf = appconfig('config:' + self.filename)
        load_environment(conf.global_conf, conf.local_conf)

        self.registry=Registry()
        self.registry.prepare()
        import pylons
        self.translator_obj = MockTranslator()
        self.registry.register(pylons.translator, self.translator_obj)
Example #24
0
    def _load_config(self):
        from paste.deploy import appconfig
        from ckan.config.environment import load_environment
        if not self.options.config:
            msg = 'No config file supplied'
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        if not os.path.exists(self.filename):
            raise AssertionError('Config filename %r does not exist.' % self.filename)
        fileConfig(self.filename)
        conf = appconfig('config:' + self.filename)
        load_environment(conf.global_conf, conf.local_conf)

        self.registry=Registry()
        self.registry.prepare()
        import pylons
        self.translator_obj = MockTranslator()
        self.registry.register(pylons.translator, self.translator_obj)
Example #25
0
def read_config(section, config_file=None):
    config = ConfigParser.ConfigParser()
    if config_file is None:
        logging.warn("No config file specified, using worker.cfg")
        config_file = 'worker.cfg'
    configs = [config_file, os.path.expanduser('~/.ckanworker.cfg')]
    config.read(configs)
    for c in configs: 
        try:
            fileConfig(c)
            break
        except: pass
    data = config.defaults()
    try:
        data.update(dict(config.items(section)))
    except ConfigParser.NoSectionError:
        pass
    return data
Example #26
0
 def __init__(self, app=None, cfgFilePath=None, port=7443, host='0.0.0.0',
              ssl_context=None):
     """Load an application configuration from cfgFilePath ini file and 
     instantiate Paste server object
     """       
     self.__thread = None
     
     if cfgFilePath:
         fileConfig(cfgFilePath, defaults={'here':path.dirname(cfgFilePath)})
         app = loadapp('config:%s' % cfgFilePath)
         
     elif app is None:
         raise KeyError('Either the "cfgFilePath" or "app" keyword must be '
                        'set')
                    
     self.__pasteServer = paste.httpserver.serve(app, host=host, port=port, 
                                                 start_loop=False, 
                                                 ssl_context=ssl_context)
Example #27
0
    def _load_config(self):
        from paste.deploy import appconfig
        from ckan.config.environment import load_environment
        if not self.options.config:
            msg = 'No config file supplied'
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        if not os.path.exists(self.filename):
            raise AssertionError('Config filename %r does not exist.' % self.filename)
        fileConfig(self.filename)
        conf = appconfig('config:' + self.filename)
        load_environment(conf.global_conf, conf.local_conf)

        self.registry=Registry()
        self.registry.prepare()
        import pylons
        self.translator_obj = MockTranslator()
        self.registry.register(pylons.translator, self.translator_obj)
Example #28
0
def uwsgi_pypy_paste_loader(config):
    """
    load a .ini paste app
    """
    global wsgi_application
    c = ffi.string(config)
    if c.startswith("config:"):
        c = c[7:]
    if c[0] != "/":
        c = os.getcwd() + "/" + c
    try:
        from paste.script.util.logging_config import fileConfig

        fileConfig(c)
    except ImportError:
        print("PyPy WARNING: unable to load paste.script.util.logging_config")
    from paste.deploy import loadapp

    wsgi_application = loadapp("config:%s" % c)
Example #29
0
def uwsgi_pypy_paste_loader(config):
    """
    load a .ini paste app
    """
    global wsgi_application
    c = ffi.string(config)
    if c.startswith(b"config:"):
        c = c[7:]
    if c[0] != b"/"[0]:
        c = os.getcwd() + "/" + c.decode()
    try:
        from paste.script.util.logging_config import fileConfig

        fileConfig(c)
    except ImportError:
        print("PyPy WARNING: unable to load paste.script.util.logging_config")
    from paste.deploy import loadapp

    wsgi_application = loadapp("config:%s" % c)
Example #30
0
def init_mediadrop(config_filename, here_dir=None, disable_logging=False):
    if not os.path.exists(config_filename):
        raise IOError('Config file %r does not exist.' % config_filename)
    if here_dir is None:
        here_dir = os.getcwd()
    if not disable_logging:
        logging_config.fileConfig(config_filename)

    conf = appconfig('config:%s' % config_filename, relative_to=here_dir)
    pylons_config = load_environment(conf.global_conf, conf.local_conf)
    paste_registry = Registry()
    paste_registry.prepare()
    pylons_config['paste.registry'] = paste_registry
    
    app_globals = pylons_config['pylons.app_globals']
    register_instance(paste_registry, 'app_globals', app_globals)
    register_instance(paste_registry, 'config', pylons_config)
    fake_request(pylons_config, registry=paste_registry)
    setup_global_translator(registry=paste_registry)
def test4():
    for i in range(5):
        conf = globals()['config%d' % i]
        sys.stdout.write('config%d: ' % i)
        loggerDict = logging.getLogger().manager.loggerDict
        logging._acquireLock()
        try:
            saved_handlers = logging._handlers.copy()
            if hasattr(logging, '_handlerList'):
                saved_handler_list = logging._handlerList[:]
            saved_loggers = loggerDict.copy()
        finally:
            logging._releaseLock()
        try:
            fn = tempfile.mktemp(".ini")
            f = open(fn, "w")
            f.write(conf)
            f.close()
            try:
                logging_config.fileConfig(fn)
                #call again to make sure cleanup is correct
                logging_config.fileConfig(fn)
            except:
                if i not in (2, 3):
                    raise
                t = sys.exc_info()[0]
                message(str(t) + ' (expected)')
            else:
                message('ok.')
            os.remove(fn)
        finally:
            logging._acquireLock()
            try:
                logging._handlers.clear()
                logging._handlers.update(saved_handlers)
                if hasattr(logging, '_handlerList'):
                    logging._handlerList[:] = saved_handler_list
                loggerDict = logging.getLogger().manager.loggerDict
                loggerDict.clear()
                loggerDict.update(saved_loggers)
            finally:
                logging._releaseLock()
def test4():
    for i in range(5):
        conf = globals()['config%d' % i]
        sys.stdout.write('config%d: ' % i)
        loggerDict = logging.getLogger().manager.loggerDict
        logging._acquireLock()
        try:
            saved_handlers = logging._handlers.copy()
            if hasattr(logging, '_handlerList'):
                saved_handler_list = logging._handlerList[:]
            saved_loggers = loggerDict.copy()
        finally:
            logging._releaseLock()
        try:
            fn = tempfile.mktemp(".ini")
            f = open(fn, "w")
            f.write(conf)
            f.close()
            try:
                logging_config.fileConfig(fn)
                #call again to make sure cleanup is correct
                logging_config.fileConfig(fn)
            except:
                if i not in (2, 3):
                    raise
                t = sys.exc_info()[0]
                message(str(t) + ' (expected)')
            else:
                message('ok.')
            os.remove(fn)
        finally:
            logging._acquireLock()
            try:
                logging._handlers.clear()
                logging._handlers.update(saved_handlers)
                if hasattr(logging, '_handlerList'):
                    logging._handlerList[:] = saved_handler_list
                loggerDict = logging.getLogger().manager.loggerDict
                loggerDict.clear()
                loggerDict.update(saved_loggers)
            finally:
                logging._releaseLock()
Example #33
0
File: cli.py Project: arkka/ckan
    def _load_config(self):
        from paste.deploy import appconfig
        if not self.options.config:
            msg = 'No config file supplied'
            raise self.BadCommand(msg)
        self.filename = os.path.abspath(self.options.config)
        if not os.path.exists(self.filename):
            raise AssertionError('Config filename %r does not exist.' % self.filename)
        fileConfig(self.filename)
        conf = appconfig('config:' + self.filename)
        assert 'ckan' not in dir() # otherwise loggers would be disabled
        # We have now loaded the config. Now we can import ckan for the
        # first time.
        from ckan.config.environment import load_environment
        load_environment(conf.global_conf, conf.local_conf)

        self.registry=Registry()
        self.registry.prepare()
        import pylons
        self.translator_obj = MockTranslator()
        self.registry.register(pylons.translator, self.translator_obj)
Example #34
0
  
  Create symlink::
      $ ln -s /usr/lib/pymodules/python2.6/ckan/wsgi.py /etc/ckan/dgu.py

  Apache config line::
      WSGIScriptAlias / /etc/ckan/dgu.py

  dgu.py will load the Pylons config: dgu.ini (looking in the same directory.)
"""

import os
import sys
from apachemiddleware import MaintenanceResponse

symlink_filepath = __file__
if os.path.basename(symlink_filepath) == 'wsgi.py':
    print usage
    sys.exit(1)
config_filepath = symlink_filepath.replace('.py', '.ini')
assert os.path.exists(
    config_filepath), 'Cannot find file %r (from symlink %r)' % (
        config_filepath, __file__)

# enable logging
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)

from paste.deploy import loadapp
application = loadapp('config:%s' % config_filepath)
application = MaintenanceResponse(application)
Example #35
0
def serve_app(config_filepath):     
    defCertFilePath = path.join(PKI_DIR, 'host.pem')
    defPriKeyFilePath = path.join(PKI_DIR, 'host.pem')
        
    parser = optparse.OptionParser()
    parser.add_option("-p",
                      "--port",
                      dest="port",
                      default=5000,
                      type='int',
                      help="port number to run under")

    parser.add_option("-s",
                      "--with-ssl",
                      dest="with_ssl",
                      default='True',
                      help="Run with SSL")

    parser.add_option("-c",
                      "--cert-file",
                      dest='certFilePath',
                      default=defCertFilePath,
                      help="SSL Certificate file")

    parser.add_option("-k",
                      "--private-key-file",
                      default=defPriKeyFilePath,
                      dest='priKeyFilePath',
                      help="SSL private key file")

    parser.add_option("-f",
                      "--conf",
                      dest="configFilePath",
                      default=config_filepath,
                      help="Configuration file path")
    
    parser.add_option("-a",
                      "--with-ssl-client-auth",
                      dest="ssl_client_authn",
                      action='store_true',
                      default=True,
                      help="Set client authentication with SSL (requires -s "
                           "option")
    
    opt = parser.parse_args()[0]
    config_filepath = path.abspath(opt.configFilePath)
    
    if opt.with_ssl.lower() == 'true':
        ssl_context = SSL.Context(SSL.SSLv23_METHOD)
    
        ssl_context.set_session_id('oauthserver')
        ssl_context.use_privatekey_file(opt.priKeyFilePath)
        ssl_context.use_certificate_file(opt.certFilePath)
        
        ssl_context.load_verify_locations(None, CACERT_DIR)
        ssl_context.set_verify_depth(9)
        
        # Load the application from the Paste ini file configuration        
        fileConfig(config_filepath, 
                   defaults={'here': path.dirname(config_filepath)})
        app = loadapp('config:%s' % config_filepath)
        
        if opt.ssl_client_authn:
            # Wrap the application in middleware to set the SSL client certificate 
            # obtained from the SSL handshake in environ                
            app = OpenSSLVerifyCallbackMiddleware(app)
            _callback = app.create_ssl_callback()
            
            # Wrap in middleware to simulate Apache environment
            app = ApacheSSLVariablesMiddleware(app)
        
            ssl_context.set_verify(SSL.VERIFY_PEER, _callback)
            
        server = PasteDeployAppServer(app=app, 
                                      port=opt.port,
                                      ssl_context=ssl_context) 
    else:
        server = PasteDeployAppServer(config_filepath=config_filepath, 
                                      port=opt.port) 
    server.start()
Example #36
0
 opt = parser.parse_args()[0]
 cfgFilePath = path.abspath(opt.configFilePath)
 
 if opt.withSSL.lower() == 'true':
     
     ssl_context = SSL.Context(SSL.SSLv23_METHOD)
     ssl_context.set_options(SSL.OP_NO_SSLv2)
 
     ssl_context.use_privatekey_file(opt.priKeyFilePath)
     ssl_context.use_certificate_file(opt.certFilePath)
     
     ssl_context.load_verify_locations(None, BaseTestCase.CACERT_DIR)
     ssl_context.set_verify_depth(9)
     
     # Load the application from the Paste ini file configuration        
     fileConfig(cfgFilePath, defaults={'here': path.dirname(cfgFilePath)})
     app = loadapp('config:%s' % cfgFilePath)
     
     if opt.ssl_client_authn:
         # Wrap the application in middleware to set the SSL client certificate 
         # obtained from the SSL handshake in environ                
         app = OpenSSLVerifyCallbackMiddleware(app)
         _callback = app.createSSLCallback()
         
         # Wrap in middleware to simulate Apache environment
         app = ApacheSSLVariablesMiddleware(app)
     
         ssl_context.set_verify(SSL.VERIFY_PEER, _callback)
         
     server = PasteDeployAppServer(app=app, 
                                   port=opt.port,
Example #37
0
            response = "Trigger OpenID Relying Party..."
            start_response('401 Unauthorized',
                           [('Content-type', 'text/plain'),
                            ('Content-length', str(len(response)))])
        return [response]


# To start run
# $ paster serve services.ini or run this file as a script
# $ ./securedapp.py [port #]
if __name__ == '__main__':
    import sys
    import os
    from os.path import dirname, abspath
    import logging
    logging.basicConfig(level=logging.DEBUG)

    if len(sys.argv) > 1:
        port = int(sys.argv[1])
    else:
        port = 6080

    cfgFilePath = os.path.join(dirname(abspath(__file__)), 'securedapp.ini')

    from paste.httpserver import serve
    from paste.deploy import loadapp
    from paste.script.util.logging_config import fileConfig

    fileConfig(cfgFilePath)
    app = loadapp('config:%s' % cfgFilePath)
    serve(app, host='0.0.0.0', port=port)
Example #38
0
#http://mydjangoblog.com/2009/03/30/django-mod_python-and-virtualenv/


import os, sys
pcwd = os.path.dirname(__file__)


from paste.script.util.logging_config import fileConfig
fileConfig('%s/deployment.ini' % pcwd)

from paste.deploy import loadapp
application = loadapp('config:%s/deployment.ini' % pcwd) 


from paste.modpython import handler
Example #39
0
from paste.deploy import loadapp

# here = os.path.dirname(os.path.abspath(__file__))
# config_filepath = os.path.join(here, 'production.ini')

if 'CKAN_CONFIG' in os.environ:
    config_filepath = os.path.abspath(os.environ['CKAN_CONFIG'])
else:
    config_filepath = os.path.join(VIRTUAL_ENV, 'src/ckan/development.ini')

print("Configuration file: {}".format(config_filepath))

## Configure logging
from paste.script.util.logging_config import fileConfig
fileConfig(config_filepath)

## Get the application
application = loadapp('config:%s' % config_filepath)

## Load configuration
from pylons import config

## Make sure this is configured properly

## --- NOTE ---
## it looks like full_stack is removed somewhere, so let's
## just hope for the best..

# if config.get('full_stack') != 'false':
#     raise ValueError("You must set full_stack = false in main configuration!")  # noqa
Example #40
0
def serve_app(config_filepath):
    defCertFilePath = path.join(PKI_DIR, 'host.pem')
    defPriKeyFilePath = path.join(PKI_DIR, 'host.pem')

    parser = optparse.OptionParser()
    parser.add_option("-p",
                      "--port",
                      dest="port",
                      default=5000,
                      type='int',
                      help="port number to run under")

    parser.add_option("-s",
                      "--with-ssl",
                      dest="with_ssl",
                      default='True',
                      help="Run with SSL")

    parser.add_option("-c",
                      "--cert-file",
                      dest='certFilePath',
                      default=defCertFilePath,
                      help="SSL Certificate file")

    parser.add_option("-k",
                      "--private-key-file",
                      default=defPriKeyFilePath,
                      dest='priKeyFilePath',
                      help="SSL private key file")

    parser.add_option("-f",
                      "--conf",
                      dest="configFilePath",
                      default=config_filepath,
                      help="Configuration file path")

    parser.add_option("-a",
                      "--with-ssl-client-auth",
                      dest="ssl_client_authn",
                      action='store_true',
                      default=True,
                      help="Set client authentication with SSL (requires -s "
                      "option")

    opt = parser.parse_args()[0]
    config_filepath = path.abspath(opt.configFilePath)

    if opt.with_ssl.lower() == 'true':
        ssl_context = SSL.Context(SSL.SSLv23_METHOD)

        ssl_context.set_session_id('oauthserver')
        ssl_context.use_privatekey_file(opt.priKeyFilePath)
        ssl_context.use_certificate_file(opt.certFilePath)

        ssl_context.load_verify_locations(None, CACERT_DIR)
        ssl_context.set_verify_depth(9)

        # Load the application from the Paste ini file configuration
        fileConfig(config_filepath,
                   defaults={'here': path.dirname(config_filepath)})
        app = loadapp('config:%s' % config_filepath)

        if opt.ssl_client_authn:
            # Wrap the application in middleware to set the SSL client certificate
            # obtained from the SSL handshake in environ
            app = OpenSSLVerifyCallbackMiddleware(app)
            _callback = app.create_ssl_callback()

            # Wrap in middleware to simulate Apache environment
            app = ApacheSSLVariablesMiddleware(app)

            ssl_context.set_verify(SSL.VERIFY_PEER, _callback)

        server = PasteDeployAppServer(app=app,
                                      port=opt.port,
                                      ssl_context=ssl_context)
    else:
        server = PasteDeployAppServer(config_filepath=config_filepath,
                                      port=opt.port)
    server.start()
 opt = parser.parse_args()[0]
 cfgFilePath = path.abspath(opt.configFilePath)
 
 if opt.withSSL.lower() == 'true':
     
     ssl_context = SSL.Context(SSL.SSLv23_METHOD)
     ssl_context.set_options(SSL.OP_NO_SSLv2)
 
     ssl_context.use_privatekey_file(opt.priKeyFilePath)
     ssl_context.use_certificate_file(opt.certFilePath)
     
     ssl_context.load_verify_locations(None, BaseTestCase.CACERT_DIR)
     ssl_context.set_verify_depth(9)
     
     # Load the application from the Paste ini file configuration        
     fileConfig(cfgFilePath, defaults={'here': path.dirname(cfgFilePath)})
     app = loadapp('config:%s' % cfgFilePath)
     
     if opt.ssl_client_authn:
         # Wrap the application in middleware to set the SSL client certificate 
         # obtained from the SSL handshake in environ                
         app = OpenSSLVerifyCallbackMiddleware(app)
         _callback = app.createSSLCallback()
         
         # Wrap in middleware to simulate Apache environment
         app = ApacheSSLVariablesMiddleware(app)
     
         ssl_context.set_verify(SSL.VERIFY_PEER, _callback)
         
     server = PasteDeployAppServer(app=app, 
                                   port=opt.port,
Example #42
0
# wsgi application starter for "course"

# production
course_dir  = '/var/local/course'
course_lib_dir  = '%s/pylib' % course_dir
config_file = '%s/production.ini' % course_dir

import sys
sys.path.insert(0, course_lib_dir)
from paste.script.util.logging_config import fileConfig
from paste.deploy import loadapp

fileConfig(config_file) 
application = loadapp('config:%s' % config_file)
Example #43
0
# -*- coding: utf-8 -*-
import os.path
from pyramid.paster import get_app
from paste.script.util.logging_config import fileConfig

here = os.path.dirname(os.path.abspath(__file__))
conf = os.path.join(here, 'production.ini')
fileConfig(conf)

application = get_app(conf, 'main')
        else:
            response = "Trigger OpenID Relying Party..."
            start_response('401 Unauthorized', 
                           [('Content-type', 'text/plain'),
                            ('Content-length', str(len(response)))])
        return [response]
    
# To start run 
# $ paster serve services.ini or run this file as a script
# $ ./securedapp.py [port #]
if __name__ == '__main__':
    import sys
    import os
    from os.path import dirname, abspath
    import logging
    logging.basicConfig(level=logging.DEBUG)

    if len(sys.argv) > 1:
        port = int(sys.argv[1])
    else:
        port = 5080
        
    cfgFilePath = os.path.join(dirname(abspath(__file__)), 'securedapp.ini')
        
    from paste.httpserver import serve
    from paste.deploy import loadapp
    from paste.script.util.logging_config import fileConfig
    
    fileConfig(cfgFilePath)
    app = loadapp('config:%s' % cfgFilePath)
    serve(app, host='0.0.0.0', port=port)
Example #45
0
#!/usr/bin/env python
# THis is the app to run with uwsgi
import os 
from paste.script.util.logging_config import fileConfig

INIFILE = '/etc/privacyidea/privacyidea.ini'

os.environ['PYTHON_EGG_CACHE'] = '/var/tmp'

fileConfig( INIFILE )
from paste.deploy import loadapp

application = loadapp('config:%s' % INIFILE)