def start(): '''Start the CherryPy application server.''' turbogears.startup.call_on_startup.append(fedora.tg.tg1utils.enable_csrf) setupdir = os.path.dirname(os.path.dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ and os.path.exists(os.path.join(setupdir, 'dev.cfg')): configfile = os.path.join(setupdir, 'dev.cfg') elif os.path.exists(os.path.join(curdir, 'fas.cfg')): configfile = os.path.join(curdir, 'fas.cfg') elif os.path.exists(os.path.join('/etc/fas.cfg')): configfile = os.path.join('/etc/fas.cfg') else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("fas"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="fas.config") from fas.controllers import Root turbogears.start_server(Root())
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("gordonweb"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="gordonweb.config") from gordonweb.controllers import Root turbogears.start_server(Root())
def test_windows_filenames(): pkg_resources.resource_filename = windows_filename turbogears.update_config(configfile = testfile, modulename="turbogears.tests.config") testdir = turbogears.config.get("test.dir") print testdir assert testdir == "c:/foo/bar"
def start(): '''Start the CherryPy application server.''' turbogears.startup.call_on_startup.append(fedora.tg.utils.enable_csrf) setupdir = os.path.dirname(os.path.dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ and os.path.exists(os.path.join(setupdir, 'dev.cfg')): configfile = os.path.join(setupdir, 'dev.cfg') elif os.path.exists(os.path.join(curdir, 'fas.cfg')): configfile = os.path.join(curdir, 'fas.cfg') elif os.path.exists(os.path.join('/etc/fas.cfg')): configfile = os.path.join('/etc/fas.cfg') else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("fas"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="fas.config") from fas.controllers import Root turbogears.start_server(Root())
def _read_config(args): """Read deployment configuration file. First looks on the command line for a desired config file, if it's not on the command line, then looks for 'setup.py' in the parent of the directory where this module is located. If 'setup.py' is there, assumes that the application is started from the project directory and should run in development mode and so loads the configuration from a file called 'dev.cfg' in the current directory. If 'setup.py' is not there, the project is probably installed and the code looks first for a file called 'prod.cfg' in the current directory and, if this isn't found either, for a default config file called 'default.cfg' packaged in the egg. """ setupdir = dirname(dirname(__file__)) curdir = getcwd() if args: configfile = args[0] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("music"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="music.config")
def test_update_from_package(): turbogears.update_config(modulename="turbogears.tests.config") assert turbogears.config.get("foo.bar") == "BAZ!" print turbogears.config.get("my.static") assert turbogears.config.get("my.static").endswith( "turbogears/tests/static") assert turbogears.config.get("static_filter.on", path="/static") == True
def _read_config(args): """Read deployment configuration file. First looks on the command line for a desired config file, if it's not on the command line, then looks for 'setup.py' in the parent of the directory where this module is located. If 'setup.py' is there, assumes that the application is started from the project directory and should run in development mode and so loads the configuration from a file called 'dev.cfg' in the current directory. If 'setup.py' is not there, the project is probably installed and the code looks first for a file called 'prod.cfg' in the current directory and, if this isn't found either, for a default config file called 'default.cfg' packaged in the egg. """ setupdir = dirname(dirname(__file__)) curdir = getcwd() if args: configfile = args[0] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("turboaffiliate"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="turboaffiliate.config")
def boot(configfile=None, use_argv=False): """Boot the environment containing the classes and configurations.""" setupdir = dirname(dirname(__file__)) curdir = getcwd() if configfile: pass # Already a string elif use_argv and len(sys.argv) > 1: configfile = sys.argv[1] else: alternatives = [ join(setupdir, "local.cfg"), join(setupdir, "dev.cfg"), join(setupdir, "prod.cfg") ] for alternative in alternatives: if exists(alternative): configfile = alternative break if not configfile: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("buzzbot"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") global configuration configuration = configfile print "** Booting configuration: %s" % configfile turbogears.update_config(configfile=configfile, modulename="buzzbot.config")
def load_config(configfile=None): """ Loads Beaker's configuration and configures logging. """ setupdir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) curdir = os.getcwd() if configfile and os.path.exists(configfile): pass elif 'BEAKER_CONFIG_FILE' in os.environ: configfile = os.environ['BEAKER_CONFIG_FILE'] elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ and os.path.exists(os.path.join(setupdir, 'dev.cfg')): configfile = os.path.join(setupdir, 'dev.cfg') elif os.path.exists(os.path.join(curdir, 'beaker.cfg')): configfile = os.path.join(curdir, 'beaker.cfg') elif os.path.exists('/etc/beaker.cfg'): configfile = '/etc/beaker.cfg' elif os.path.exists('/etc/beaker/server.cfg'): configfile = '/etc/beaker/server.cfg' else: raise RuntimeError("Unable to find configuration to load!") # We only allow the config to be loaded once, update_config() # doesn't seem to update the config when called more than once # anyway configfile = os.path.realpath(configfile) global _config_loaded if _config_loaded is not None and configfile == _config_loaded: return elif _config_loaded is not None and configfile != _config_loaded: raise RuntimeError('Config has already been loaded from %s' % \ _config_loaded) # In general, we want all messages from application code. logging.getLogger().setLevel(logging.DEBUG) # Well-behaved libraries will set their own log levels to something # suitable (sqlalchemy sets it to WARNING, for example) but a number of # libraries leave their level unset. logging.getLogger('passlib').setLevel(logging.INFO) logging.getLogger('turbomail').setLevel(logging.INFO) logging.getLogger('turbogears').setLevel(logging.INFO) logging.getLogger('turbokid').setLevel(logging.INFO) logging.getLogger('turbogears.access').setLevel(logging.WARN) # Note that the actual level of log output is controlled by the handlers, # not the loggers (for example command line tools will typically log to # stderr at WARNING level). The main entry point for the program should # call bkr.log.log_to_{syslog,stream} to set up a handler. # We do not want TurboGears to touch the logging config, so let's # double-check the user hasn't left an old [logging] section in their # config file. from configobj import ConfigObj configdata = ConfigObj(configfile, unrepr=True) if configdata.has_key('logging'): raise RuntimeError( 'TurboGears logging configuration is not supported, ' 'remove [logging] section from config file %s' % configfile) turbogears.update_config(configfile=configfile, modulename="bkr.server.config") _config_loaded = configfile
def main(): import sys import pkg_resources pkg_resources.require("TurboGears") # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(dirname(__file__), "setup.py")): configfile = "dev.cfg" else: configfile = "prod.cfg" lucene_lock = 'index/en/write.lock' if exists(lucene_lock): os.unlink(lucene_lock) # Patch before you start importing etc. import patches import patches.utils patches.utils.configfile = configfile updater = patches.Updater() updater.update() del updater del patches getoutput('./bin/kidc hubspace/templates') import monkeypatch import turbogears import cherrypy cherrypy.lowercase_api = True turbogears.update_config(configfile, modulename="hubspace.config") staic_target = turbogears.config.config.configs['global']['static_target_dir'] static_link = turbogears.config.config.configs['/static']['static_filter.dir'] if os.path.islink(static_link): os.remove(static_link) os.symlink(staic_target, static_link) print "Static link: %s -> %s" % (static_link, staic_target) def add_sync_filters(): import hubspace.sync.core cherrypy.root._cp_filters.extend(hubspace.sync.core._cp_filters) import hubspace.search turbogears.startup.call_on_startup.append(add_sync_filters) turbogears.startup.call_on_shutdown.append(hubspace.search.stop) from hubspace.controllers import Root turbogears.start_server(Root())
def test_update_from_both(): turbogears.update_config(configfile = testfile, modulename="turbogears.tests.config") print turbogears.config.get("foo.bar") assert turbogears.config.get("foo.bar") == "blurb" assert turbogears.config.get("tg.something") == 10 print turbogears.config.get("test.dir") assert turbogears.config.get("test.dir").endswith("turbogears/tests")
def load_config(configfile=None): """ Loads Beaker's configuration and configures logging. """ setupdir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) curdir = os.getcwd() if configfile and os.path.exists(configfile): pass elif 'BEAKER_CONFIG_FILE' in os.environ: configfile = os.environ['BEAKER_CONFIG_FILE'] elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ and os.path.exists(os.path.join(setupdir, 'dev.cfg')): configfile = os.path.join(setupdir, 'dev.cfg') elif os.path.exists(os.path.join(curdir, 'beaker.cfg')): configfile = os.path.join(curdir, 'beaker.cfg') elif os.path.exists('/etc/beaker.cfg'): configfile = '/etc/beaker.cfg' elif os.path.exists('/etc/beaker/server.cfg'): configfile = '/etc/beaker/server.cfg' else: raise RuntimeError("Unable to find configuration to load!") # We only allow the config to be loaded once, update_config() # doesn't seem to update the config when called more than once # anyway configfile = os.path.realpath(configfile) global _config_loaded if _config_loaded is not None and configfile == _config_loaded: return elif _config_loaded is not None and configfile != _config_loaded: raise RuntimeError('Config has already been loaded from %s' % \ _config_loaded) # In general, we want all messages from application code. logging.getLogger().setLevel(logging.DEBUG) # Well-behaved libraries will set their own log levels to something # suitable (sqlalchemy sets it to WARNING, for example) but a number of # libraries leave their level unset. logging.getLogger('passlib').setLevel(logging.INFO) logging.getLogger('turbomail').setLevel(logging.INFO) logging.getLogger('turbogears').setLevel(logging.INFO) logging.getLogger('turbokid').setLevel(logging.INFO) logging.getLogger('turbogears.access').setLevel(logging.WARN) # Note that the actual level of log output is controlled by the handlers, # not the loggers (for example command line tools will typically log to # stderr at WARNING level). The main entry point for the program should # call bkr.log.log_to_{syslog,stream} to set up a handler. # We do not want TurboGears to touch the logging config, so let's # double-check the user hasn't left an old [logging] section in their # config file. from configobj import ConfigObj configdata = ConfigObj(configfile, unrepr=True) if configdata.has_key('logging'): raise RuntimeError('TurboGears logging configuration is not supported, ' 'remove [logging] section from config file %s' % configfile) turbogears.update_config(configfile=configfile, modulename="bkr.server.config") _config_loaded = configfile
def init(daemon_config): turbogears.update_config(configfile="dev.cfg", modulename="vmcweb.config") turbogears.config.update({'global': {'server.environment': 'production'}}) turbogears.config.update({'global': {'autoreload.on': False}}) turbogears.config.update({'global': {'server.log_to_screen': False}}) turbogears.config.update({'global': {'server.webpath': '/vmcweb'}}) cherrypy.root = vmcweb.controllers.Root() if cherrypy.server.state == 0: cherrypy.server.start(init_only=True, server_class=None) atexit.register(cherrypy.server.stop)
def tg_init(self): """ Checks for the required data and initializes the application. """ if TGWindowsService.code_dir: os.chdir(TGWindowsService.code_dir) sys.path.append(TGWindowsService.code_dir) # Redirect stdout and stderr to avoid buffer crashes. sys.stdout = open(join(TGWindowsService.log_dir, 'stdout.log'), 'a') sys.stderr = open(join(TGWindowsService.log_dir, 'stderr.log'), 'a') else: raise ValueError("""The code directory setting is missing. The Windows Service will not run without this setting.""") if not TGWindowsService.root_class: raise ValueError("""The fully qualified root class name must be provided.""") if not TGWindowsService.log_dir: TGWindowsService.log_dir = '.' if exists(join(dirname(__file__), "setup.py")): turbogears.update_config(configfile="dev.cfg", modulename=TGWindowsService.config_module) else: turbogears.update_config(configfile="prod.cfg", modulename=TGWindowsService.config_module) # Set environment to production to disable auto-reload. cherrypy.config.update({ 'global': { 'server.environment': 'production' }, }) # Parse out the root class information and set it to self.root full_class_name = TGWindowsService.root_class last_mark = full_class_name.rfind('.') if (last_mark < 1) or (last_mark + 1) == len(full_class_name): raise ValueError("""The user-defined class name is invalid. Please make sure to include a fully qualified class name for the root_class value (e.g. wiki20.controllers.Root).""") package_name = full_class_name[:last_mark] class_name = full_class_name[last_mark + 1:] exec('from %s import %s as Root' % (package_name, class_name)) self.root = Root
def setup_package(): log.info('Loading test configuration from %s', CONFIG_FILE) assert os.path.exists(CONFIG_FILE), 'Config file %s must exist' % CONFIG_FILE update_config(configfile=CONFIG_FILE, modulename='bkr.server.config') # Override loaded logging config, in case we are using the server's config file # (we really always want our tests' logs to go to stdout, not /var/log/beaker/) log_to_stream(sys.stdout, level=logging.NOTSET) from bkr.inttest import data_setup if not 'BEAKER_SKIP_INIT_DB' in os.environ: data_setup.setup_model() with session.begin(): data_setup.create_labcontroller() #always need a labcontroller data_setup.create_task(name=u'/distribution/install', requires= u'make gcc nfs-utils wget procmail redhat-lsb ntp ' u'@development-tools @development-libs @development ' u'@desktop-platform-devel @server-platform-devel ' u'libxml2-python expect pyOpenSSL'.split()) data_setup.create_task(name=u'/distribution/reservesys', requires=u'emacs vim-enhanced unifdef sendmail'.split()) data_setup.create_distro() if not os.path.exists(turbogears.config.get('basepath.rpms')): os.mkdir(turbogears.config.get('basepath.rpms')) setup_slapd() turbogears.testutil.make_app(Root) turbogears.testutil.start_server() if 'BEAKER_SERVER_BASE_URL' not in os.environ: # need to start the server ourselves # (this only works from the IntegrationTests dir of a Beaker checkout) processes.extend([ Process('beaker', args=['../Server/start-server.py', CONFIG_FILE], listen_port=turbogears.config.get('server.socket_port'), stop_signal=signal.SIGINT) ]) processes.extend([ Process('slapd', args=['slapd', '-d0', '-F/tmp/beaker-tests-slapd-config', '-hldap://127.0.0.1:3899/'], listen_port=3899, stop_signal=signal.SIGINT), ]) try: for process in processes: process.start() except: for process in processes: process.stop() raise
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if exists("/etc/funcweb/prod.cfg"): print "I use the production ito the etc !" configfile = "/etc/funcweb/prod.cfg" elif len(sys.argv) > 1: print "We got something from the sys" configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): print "I use the dev one into the dev dir" configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): print "I use the prod one into the cur dir" configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("funcweb"), "config/default.cfg") print "That is another default conf" except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="funcweb.config") from funcweb.controllers import Root if exists("/etc/funcweb/prod.cfg"): futils.daemonize("/var/run/funcwebd.pid") #then start the server try: turbogears.start_server(Root()) except Exception, e: print "Exception occured :", e sys.exit(1)
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("eCRM"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile = configfile, modulename = "ecrm.config") #update the all vendor report #from ecrm import scheduler #remvoe the function by cl on 2010-09-30 # turbogears.startup.call_on_startup.append(scheduler.schedule) #gen the woven label report #from ecrm import autoOrder #turbogears.startup.call_on_startup.append(autoOrder.scheduleAM) #turbogears.startup.call_on_startup.append(autoOrder.schedulePM) from ecrm.controllers import Root turbogears.start_server(Root())
def tg_init(self): """ Checks for the required data and initializes the application. """ if TGWindowsService.code_dir: os.chdir(TGWindowsService.code_dir) sys.path.append(TGWindowsService.code_dir) # Redirect stdout and stderr to avoid buffer crashes. sys.stdout = open(join(TGWindowsService.log_dir, 'stdout.log'),'a') sys.stderr = open(join(TGWindowsService.log_dir, 'stderr.log'),'a') else: raise ValueError("""The code directory setting is missing. The Windows Service will not run without this setting.""") if not TGWindowsService.root_class: raise ValueError("""The fully qualified root class name must be provided.""") if not TGWindowsService.log_dir: TGWindowsService.log_dir = '.' if exists(join(dirname(__file__), "setup.py")): turbogears.update_config(configfile="dev.cfg", modulename=TGWindowsService.config_module) else: turbogears.update_config(configfile="prod.cfg", modulename=TGWindowsService.config_module) # Set environment to production to disable auto-reload. cherrypy.config.update({'global': {'server.environment': 'production'},}) # Parse out the root class information and set it to self.root full_class_name = TGWindowsService.root_class last_mark = full_class_name.rfind('.') if (last_mark < 1) or (last_mark + 1) == len(full_class_name): raise ValueError("""The user-defined class name is invalid. Please make sure to include a fully qualified class name for the root_class value (e.g. wiki20.controllers.Root).""") package_name = full_class_name[:last_mark] class_name = full_class_name[last_mark+1:] exec('from %s import %s as Root' % (package_name, class_name)) self.root = Root
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = getcwd() # First look on the command line for a desired config file, # if it's not on the command line then load pkgdb.cfg from the sysconfdir if len(sys.argv) > 1: configfile = sys.argv[1] else: configfile = pkgdata.get_filename('pkgdb.cfg', 'config') turbogears.update_config(configfile=configfile, modulename="pkgdb.config") from pkgdb.controllers import Root turbogears.start_server(Root())
def test_update_on_windows(): """turbogears.update_config works as we intend on Windows. """ # save the original function orig_resource_fn = pkg_resources.resource_filename # monkey patch pkg resources to emulate windows pkg_resources.resource_filename = windows_filename update_config(configfile=testfile, modulename="turbogears.tests.config") testdir = cget("test.dir") # update_config calls os.normpath on package_dir, but this will have no # effect on non-windows systems, so we call ntpath.normpath on those here if not sys.platform.startswith("win"): testdir = ntpath.normpath(testdir) # restore original function pkg_resources.resource_filename = orig_resource_fn assert testdir == "c:\\foo\\bar"
def start(): """Start the CherryPy application server.""" global PRODUCTION_ENV setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if exists("/etc/funcweb/prod.cfg"): #we work with production settings now ! PRODUCTION_ENV = True configfile = "/etc/funcweb/prod.cfg" elif len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("funcweb"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="funcweb.config") from funcweb.controllers import Root if PRODUCTION_ENV: utils.daemonize("/var/run/funcwebd.pid") #then start the server try: turbogears.start_server(Root()) except Exception,e: print "Debug information from cherrypy server ...: ",e
def load_config(configfile=None): """ Load bodhi's configuration """ setupdir = os.path.dirname(os.path.dirname(__file__)) curdir = os.getcwd() if configfile and os.path.exists(configfile): pass elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ and os.path.exists(os.path.join(setupdir, 'dev.cfg')): configfile = os.path.join(setupdir, 'dev.cfg') elif os.path.exists(os.path.join(curdir, 'bodhi.cfg')): configfile = os.path.join(curdir, 'bodhi.cfg') elif os.path.exists('/etc/bodhi.cfg'): configfile = '/etc/bodhi.cfg' elif os.path.exists('/etc/bodhi/bodhi.cfg'): configfile = '/etc/bodhi/bodhi.cfg' else: log.error("Unable to find configuration to load!") return log.debug("Loading configuration: %s" % configfile) turbogears.update_config(configfile=configfile, modulename="bodhi.config")
def start(): cherrypy.lowercase_api = True # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: turbogears.update_config(configfile=sys.argv[1], modulename="mirrormanager.config") elif exists(join(os.getcwd(), "setup.py")): turbogears.update_config(configfile="dev.cfg", modulename="mirrormanager.config") else: turbogears.update_config(configfile="/etc/mirrormanager/prod.cfg", modulename="mirrormanager.config") from mirrormanager.controllers import Root turbogears.start_server(Root())
os.remove(os.path.join((LOCAL_DIR), sfile)) for fname in os.listdir(LOCAL_DIR): if (not fname.startswith(SESSION_PREFIX) and not fname.endswith(LOCK)): for sname in sessionfiles: if not fname.endswith(sname.split('-')[1]): for aname in os.listdir(LOCAL_DIR+'/'+fname): os.remove(os.path.join((LOCAL_DIR+'/'+fname), aname)) os.rmdir(os.path.join(LOCAL_DIR, fname)) # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="validator.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg",modulename="validator.config") else: update_config(configfile="prod.cfg",modulename="validator.config") if not os.path.isdir(LOCAL_DIR): try: os.mkdir(LOCAL_DIR) except IOError: print "IOError: %s could not be created" % LOCAL_DIR from validator.controllers import Root from cherrypy.filters import sessionfilter cherrypy.root = Root()
import pkg_resources pkg_resources.require("TurboGears") import turbogears import cherrypy cherrypy.lowercase_api = True from os.path import * import sys # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: turbogears.update_config(configfile=sys.argv[1], modulename="scoop.config") elif exists(join(dirname(__file__), "setup.py")): turbogears.update_config(configfile="dev.cfg", modulename="scoop.config") else: turbogears.update_config(configfile="prod.cfg", modulename="scoop.config") from scoop.controllers import * if True: turbogears.start_server(Root()) else: import thread th = thread.start_new_thread( turbogears.start_server,
if type(nullOrStr) == float : return unicode(int(nullOrStr)) return unicode(nullOrStr).strip() def formatLC(nullOrStr): if not nullOrStr or type(nullOrStr) not in [str,unicode] : return "" return "".join([c for c in nullOrStr if c.isdigit()]) if __name__ == "__main__": import turbogears,os,re import win32com.client from sqlobject import * from ecrm.util.common import * from sqlobject.sqlbuilder import * LIKE.op = "ILIKE" turbogears.update_config(configfile="dev.cfg",modulename="ecrm.config") from ecrm import model from ecrm.model import * print "=======================start to read the ecxel=============================" pythoncom.CoInitialize() xls = win32com.client.Dispatch("Excel.Application") xls.Visible = 0 wb = xls.Workbooks.open(xlsPath) sheet = wb.Sheets[0] beginRow = 2 endRow =80 data = [] for row in range(beginRow,endRow+1): data.append( {
# Look for a 'config' package for dirpath, dirs, dummy2 in os.walk('.'): basename = os.path.basename(dirpath) dirname = os.path.basename(os.path.dirname(dirpath)) init_py = os.path.join(dirpath, '__init__.py') if basename == 'config' and dirname[0] in string.ascii_letters + '_' \ and os.path.exists(init_py): modulename = "%s.app" % dirpath[2:].replace(os.sep, ".") break else: modulename = None # XXX This is a temporary workaround, the code above to find the config # package should really be improved and moved elsewhere. # See http://trac.turbogears.org/ticket/2043 try: update_config(configfile="test.cfg", modulename=modulename) except ImportError, exc: import warnings warnings.warn("Could not import configuration from module: %s" % exc, RuntimeWarning) update_config(configfile="test.cfg", modulename=None) else: database.set_db_uri("sqlite:///:memory:") config.update( {'global': { 'autoreload.on': False, 'tg.new_style_logging': True }})
# If your project uses a database, you can set up database tests # similar to what you see below. Be sure to set the db_uri to # an appropriate uri for your testing database. sqlite is a good # choice for testing, because you can use an in-memory database # which is very fast. import turbogears from turbogears import testutil, database from hardware.model import * from hardware import model turbogears.update_config(configfile='../test.cfg', modulename='hardware.config') #def test_add(): # # host = Host.query().selectone_by(uuid="fish") # print host.uuid # # assert host.uuid != 'fish' # host.delete() # host.flush()
import new_object_state import project_exists_state import dontcare_state import file_exists_state suite = unittest.TestSuite() suite.addTests(unittest.TestLoader().loadTestsFromModule(empty_state)) suite.addTests(unittest.TestLoader().loadTestsFromModule(new_object_state)) suite.addTests(unittest.TestLoader().loadTestsFromModule(project_exists_state)) suite.addTests(unittest.TestLoader().loadTestsFromModule(dontcare_state)) suite.addTests(unittest.TestLoader().loadTestsFromModule(file_exists_state)) if __name__ == "__main__": #grab the config file if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="roboide.config") else: sys.exit('No config file specified') ide_run_cmd = './start-roboide.py' run_proc = subprocess.Popen([ide_run_cmd, sys.argv[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE) #check that the IDE is running port = config.get('server.socket_port') host = config.get('server.socket_host') conn = httplib.HTTPConnection(host, port) done = False while not done: try:
#!/Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python import pkg_resources pkg_resources.require("TurboGears") from turbogears import update_config, start_server import cherrypy cherrypy.lowercase_api = True from os.path import * import sys # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="videostore.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg",modulename="videostore.config") else: update_config(configfile="prod.cfg",modulename="videostore.config") from videostore.controllers import Root start_server(Root())
#!/usr/local/bin/python2.4 import pkg_resources pkg_resources.require("TurboGears") from turbogears import update_config, start_server import cherrypy cherrypy.lowercase_api = True from os.path import * import sys # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="shutterbug.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg",modulename="shutterbug.config") else: update_config(configfile="prod.cfg",modulename="shutterbug.config") from shutterbug.controllers import Root start_server(Root())
#!/usr/bin/python __requires__ = 'TurboGears' import pkg_resources pkg_resources.require('CherryPy >= 2.0, < 3.0alpha') import pytz from datetime import timedelta import turbogears from turbogears import config turbogears.update_config(configfile="/etc/account-expiry.cfg") import turbomail from turbogears.database import session from fas.model import * from email.Message import Message import smtplib # TODO: GPG sign these emails. # Maybe we can do it one-time and just include the signature in the message. WARN_AGE = timedelta(config.get('warn_age')) MAX_AGE = timedelta(config.get('max_age')) EXPIRY_TIME = config.get('max_age') - config.get('warn_age') SMTP_SERVER = config.get('smtp_server') # Taken (and slightly modified) from Toshio's pkgdb-sync-bugzilla.in in pkgdb def send_email(fromAddress, toAddress, subject, message, smtp_server=SMTP_SERVER): '''Send an email if there's an error. This will be replaced by sending messages to a log later. '''
import xmlrpclib import smtplib from email.Message import Message import warnings # Ignore DeprecationWarnings. This allows us to stop getting email # from the cron job. We'll see the same warnings from the server starting up warnings.simplefilter('ignore', DeprecationWarning) import turbogears import bugzilla from turbogears import config cfgfile = '/etc/export-bugzilla.cfg' if os.access('./export-bugzilla.cfg', os.R_OK): cfgfile = './export-bugzilla.cfg' turbogears.update_config(configfile=cfgfile) from turbogears.database import session from fas.model import BugzillaQueue BZSERVER = config.get('bugzilla.url', 'https://bugdev.devel.redhat.com/bugzilla-cvs/xmlrpc.cgi') BZUSER = config.get('bugzilla.username') BZPASS = config.get('bugzilla.password') MAILSERVER = config.get('mail.server', 'localhost') ADMINEMAIL = config.get('mail.admin_email', '*****@*****.**') NOTIFYEMAIL = config.get('mail.notify_email', ['*****@*****.**']) if __name__ == '__main__': opts, args = getopt.getopt(sys.argv[1:], '', ('usage', 'help')) if len(args) != 2 or ('--usage','') in opts or ('--help','') in opts: print """ Usage: export-bugzilla.py GROUP BUGZILLA_GROUP
import os import yum import tempfile from os.path import exists, join from turbogears import config, update_config, database from bodhi.util import Singleton, sanity_check_repodata, mkmetadatadir import logging log = logging.getLogger(__name__) update_config(configfile='bodhi.cfg', modulename='bodhi.config') database.set_db_uri("sqlite:///:memory:") class TestUtil(object): def test_singleton(self): """ Make sure our Singleton class actually works """ class A(Singleton): pass a = A() assert a b = A() assert b is a def test_acls(self): acl = config.get('acl_system') assert acl in ('dummy', 'pkgdb'), "Unknown acl system: %s" % acl
import sys sys.path.append('/Users/weyertdeboer/Development/Sites/Wiki-20') sys.stdout = sys.stderr import os os.environ['PYTHON_EGG_CACHE'] = '/Library/Python/2.5/site-packages' import atexit import cherrypy import cherrypy._cpwsgi import turbogears turbogears.update_config(configfile="dev.cfg", modulename="wiki20.config") turbogears.config.update({'global': {'server.environment': 'production'}}) turbogears.config.update({'global': {'autoreload.on': False}}) turbogears.config.update({'global': {'server.log_to_screen': False}}) import wiki20.controllers cherrypy.root = wiki20.controllers.Root() if cherrypy.server.state == 0: atexit.register(cherrypy.server.stop) cherrypy.server.start(init_only=True, server_class=None) application = cherrypy._cpwsgi.wsgiApp
import win32api import win32process import cherrypy import os import turbogears cherrypy.lowercase_api = True from os.path import * import sys import StringIO import cgitb import traceback os.environ['WEB_PROCESS'] = '1' cherrypy.config.update( os.path.join(os.getenv("RAD_INSTALL_DIR"), "conf", "MS_prod.cfg")) update_config(configfile="MS_prod.cfg", modulename="radspeed.config") from radspeed.core.logconf import * logconf("InstaMSWordReporting.log") class MSWordProcess(): def __init__(self, port): self.port = port self.tg_init() def tg_init(self): try: from radspeed.MSWordReportController import MSWordReportController, Root Root.MSWORD = MSWordReportController()
pkg_resources.require("TurboGears") from turbogears import config, update_config, start_server import cherrypy cherrypy.lowercase_api = True from os.path import * import os, sys import thread # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="reports.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg",modulename="reports.config") else: update_config(configfile="prod.cfg",modulename="reports.config") config.update(dict(package="reports")) from reports.web import Root if __name__ != "__main__": gitPid = True gitPid = os.fork() if not gitPid: exit = os.system('git add .') if exit: sys.exit(1) exit = os.system('git commit -a -m "$(date)"')
# Look for a 'config' package for dirpath, dirs, dummy2 in os.walk('.'): basename = os.path.basename(dirpath) dirname = os.path.basename(os.path.dirname(dirpath)) init_py = os.path.join(dirpath, '__init__.py') if basename == 'config' and dirname[0] in string.ascii_letters + '_' \ and os.path.exists(init_py): modulename = "%s.app" % dirpath[2:].replace(os.sep, ".") break else: modulename = None # XXX This is a temporary workaround, the code above to find the config # package should really be improved and moved elsewhere. # See http://trac.turbogears.org/ticket/2043 try: update_config(configfile="test.cfg", modulename=modulename) except ImportError, exc: import warnings warnings.warn("Could not import configuration from module: %s" % exc, RuntimeWarning) update_config(configfile="test.cfg", modulename=None) else: database.set_db_uri("sqlite:///:memory:") config.update({'global': {'autoreload.on': False, 'tg.new_style_logging': True}}) def start_cp(): if not config.get("cherrypy_started", False): cherrypy.server.start(serverClass=None, initOnly=True)
pkg_resources.require("TurboGears") from turbogears import update_config, start_server, config import cherrypy cherrypy.lowercase_api = True from os.path import * import os, sys, logging # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="roboide.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg", modulename="roboide.config") else: update_config(configfile="prod.cfg", modulename="roboide.config") from roboide.controllers import Root #Determine if we have ll_core try: pkg_resources.require("ll_core") if config.get("server.daemon", False): from ll import daemon me = daemon.Daemon(stdout=config.get("server.logfile", "/dev/null"), stderr=config.get("server.logfile", "/dev/null"),
from turbogears import update_config, start_server, config warnings.resetwarnings() import cherrypy cherrypy.lowercase_api = True from os.path import * import sys from hardware.featureset import init, config_filename _cfg_filename = None if len(sys.argv) > 1: _cfg_filename = sys.argv[1] init(_cfg_filename) update_config(configfile=config_filename(),modulename="hardware.config") warnings.filterwarnings("ignore") from hardware.controllers import Root warnings.resetwarnings() if config.get('server.environment') == 'production': pidfile='/var/run/smolt/smolt.pid' else: pidfile='smolt.pid' #--------------- write out the pid file ----------- import os #pid = file('hardware.pid', 'w') pid = file(pidfile, 'w')
# $Id: test_metadata.py,v 1.1 2006/12/31 09:10:25 lmacken Exp $ import turbogears from turbogears import testutil, database, config turbogears.update_config(configfile='bodhi.cfg', modulename='bodhi.config') database.set_db_uri("sqlite:///:memory:") import glob import shutil import tempfile from datetime import datetime from hashlib import sha256 from os.path import join, exists, basename from datetime import datetime from bodhi.util import mkmetadatadir, get_nvr from bodhi.model import (Release, Package, PackageUpdate, Bugzilla, CVE, PackageBuild) from bodhi.buildsys import get_session from bodhi.metadata import ExtendedMetadata from yum.update_md import UpdateMetadata class TestExtendedMetadata(testutil.DBTest): def __verify_updateinfo(self, repodata): """Verify the updateinfo file This is not a test, just a helper function. """ updateinfos = glob.glob(join(repodata, "*-updateinfo.xml.gz")) assert len(updateinfos) == 1, "We generated %d updateinfo metadata" % len(updateinfos)
#print "sys.prefix: ", sys.prefix #print "cpfile: ", cpfile #print "path insert: ", cpfile[0] sys.path.insert(1, cpfile[0]) #print '\n'.join(sys.path) # Now can import TurboGears, etc. import pkg_resources pkg_resources.require("TurboGears") from turbogears import config, update_config, start_server import cherrypy cherrypy.lowercase_api = True # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="jsproxy.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg", modulename="jsproxy.config") else: update_config(configfile="prod.cfg", modulename="jsproxy.config") config.update(dict(package="jsproxy")) from jsproxy.controllers import Root start_server(Root())
#!/usr/bin/python __requires__ = "TurboGears" import pkg_resources pkg_resources.require("CherryPy >= 2.0, < 3.0alpha") import pytz from datetime import timedelta import turbogears from turbogears import config turbogears.update_config(configfile="/etc/account-expiry.cfg") import turbomail from turbogears.database import session from fas.model import * from email.Message import Message import smtplib # TODO: GPG sign these emails. # Maybe we can do it one-time and just include the signature in the message. WARN_AGE = timedelta(config.get("warn_age")) MAX_AGE = timedelta(config.get("max_age")) EXPIRY_TIME = config.get("max_age") - config.get("warn_age") SMTP_SERVER = config.get("smtp_server") # Taken (and slightly modified) from Toshio's pkgdb-sync-bugzilla.in in pkgdb def send_email(fromAddress, toAddress, subject, message, smtp_server=SMTP_SERVER): """Send an email if there's an error.
import pkg_resources pkg_resources.require("TurboGears") from turbogears import update_config, start_server, config import cherrypy cherrypy.lowercase_api = True from os.path import * import sys sys.path.append('../') from components import db # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="infoshopkeeperonline.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg", modulename="infoshopkeeperonline.config") else: update_config(configfile="prod.cfg", modulename="infoshopkeeperonline.config") config.update({'sqlobject.dburi': db.conn()}) from infoshopkeeperonline.controllers import Root start_server(Root())
''' Copyright (c)2008-2009 Serendio Software Private Limited All Rights Reserved This software is confidential and proprietary information of Serendio Software. It is disclosed pursuant to a non-disclosure agreement between the recipient and Serendio. This source code is provided for informational purposes only, and Serendio makes no warranties, either express or implied, in this. Information in this program, including URL and other Internet website references, is subject to change without notice. The entire risk of the use or the results of the use of this program remains with the user. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this program may be reproduced, stored in, or introduced into a retrieval system, or distributed or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, on a website, or otherwise) or for any purpose, without the express written permission of Serendio Software. Serendio may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this program. Except as expressly provided in any written license agreement from Serendio, the furnishing of this program does not give you any license to these patents, trademarks, copyrights, or other intellectual property. ''' import simplejson import turbogears import sys import os sys.path.append('.') turbogears.update_config(configfile='dev.cfg', modulename='knowledgemate.config') from turbogears.database import session from knowledgemate import model session.begin() try: conn1=model.Connector(name=u'CircuitcityConnector', protocol=u'http', url_segment=u'circuitcity.com', connector_data=unicode(simplejson.dumps({})) ) session.flush() session.commit() print "Connector registration Successfull!" except:
import sys import codecs import re try: from sanum import model except: root_dir = os.path.abspath(os.getcwd() + '/../../') os.chdir(root_dir) sys.path.append(root_dir) from sanum import model import sanum import turbogears turbogears.update_config(configfile="dev.cfg", modulename="sanum.config") from mk_scipy_paper import tex2pdf, current_dir , copy_files, preamble, \ render_abstract, addfile, sourcedir, outdir, outfilename def hack_include_graphics(latex_text, attach_dir): """ Replaces all the \includegraphics call with call that impose the width to be 0.9\linewidth. """ latex_text = re.sub(r'\\includegraphics(\[.*\])?\{', r'\includegraphics\1{' + attach_dir, latex_text) return latex_text
from turbogears import config, update_config, start_server import cherrypy cherrypy.lowercase_api = True # Add WidgetLibs directory to the python path: sys.path.append("../..") # Add Trunk to the python path: sys.path.append("../../..") # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="testserver.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg", modulename="testserver.config") else: update_config(configfile="prod.cfg", modulename="testserver.config") config.update(dict(package="testserver")) from testserver.controllers import Root print "WebBrick panel widgets test server" print "" print "*** NOTE ***" print "File WebBrickGateway/panels/tests/TestServer/testserver/config/app.cfg must" print "be edited so that definition 'webbrickRootDirectory' reflects the location" print "of files to be served on this system" print ""
#!/usr/bin/python import pkg_resources pkg_resources.require("TurboGears") from turbogears import config, update_config, start_server, startup import cherrypy cherrypy.lowercase_api = True from os.path import * import sys # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: update_config(configfile=sys.argv[1], modulename="archives.config") elif exists(join(dirname(__file__), "setup.py")): update_config(configfile="dev.cfg",modulename="archives.config") else: update_config(configfile="prod.cfg",modulename="archives.config") config.update(dict(package="archives")) from archives.controllers import Root from archives import jobs startup.call_on_startup.append(jobs.schedule) start_server(Root())
#!/usr/bin/python import sys import time sys.path.append("/usr/lib/controlpanel") from models.masterdb import * from models.identitydb import * from datetime import datetime, date, timedelta import traceback, urlparse, urllib2 import commands , pickle import turbogears turbogears.update_config(configfile="/root/sanity.cfg") from sqlobject import IN, AND, OR customer = Customer.get(46443) customer = Customer.get(28971) num_servers = 0 num_mps = 0 server_labels = {} lines = open(sys.argv[1]).readlines() # IMPORTED UP TO 80 start = 0 end = start+500 print "Importing %s - %s\n\n" % (start,end) for line in lines[start:end]: line = line.strip() fields = line.split('|')
def load_config(configfile=None): """ Loads Beaker's configuration and configures logging. """ setupdir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) curdir = os.getcwd() if configfile and os.path.exists(configfile): pass elif 'BEAKER_CONFIG_FILE' in os.environ: configfile = os.environ['BEAKER_CONFIG_FILE'] elif os.path.exists(os.path.join(setupdir, 'setup.py')) \ and os.path.exists(os.path.join(setupdir, 'dev.cfg')): configfile = os.path.join(setupdir, 'dev.cfg') elif os.path.exists(os.path.join(curdir, 'beaker.cfg')): configfile = os.path.join(curdir, 'beaker.cfg') elif os.path.exists('/etc/beaker.cfg'): configfile = '/etc/beaker.cfg' elif os.path.exists('/etc/beaker/server.cfg'): configfile = '/etc/beaker/server.cfg' else: raise RuntimeError("Unable to find configuration to load!") # We only allow the config to be loaded once, update_config() # doesn't seem to update the config when called more than once # anyway configfile = os.path.realpath(configfile) global _config_loaded if _config_loaded is not None and configfile == _config_loaded: return elif _config_loaded is not None and configfile != _config_loaded: raise RuntimeError('Config has already been loaded from %s' % \ _config_loaded) # In general, we want all messages from application code, but no debugging # messages from the libraries we are using. logging.getLogger().setLevel(logging.INFO) logging.getLogger('bkr').setLevel(logging.DEBUG) # We don't need access logs from TurboGears, we have the Apache logs. logging.getLogger('turbogears.access').setLevel(logging.WARN) # Note that the actual level of log output is controlled by the handlers, # not the loggers (for example command line tools will typically log to # stderr at WARNING level). The main entry point for the program should # call bkr.log.log_to_{syslog,stream} to set up a handler. # We do not want TurboGears to touch the logging config, so let's # double-check the user hasn't left an old [logging] section in their # config file. from configobj import ConfigObj configdata = ConfigObj(configfile, unrepr=True) if 'logging' in configdata: raise RuntimeError( 'TurboGears logging configuration is not supported, ' 'remove [logging] section from config file %s' % configfile) if not 'global' in configdata: raise RuntimeError('Config file is missing section [global]') # Read our beaker config and store it to Flask config app.config.update(configdata['global']) # Keep this until we completely remove TurboGears turbogears.update_config(configfile=configfile, modulename="bkr.server.config") _config_loaded = configfile
if __name__ == "__main__": parser = optparse.OptionParser() parser.add_option("-c", "--config", action="store", dest="config") parser.add_option("-g", "--server-group-id", action="store", dest="server_group_id") parser.add_option("-o", "--output-path", action="store", dest="output_path") options, args = parser.parse_args() # Validation if not options.config: print "You should provide the path to config file" sys.exit(0) turbogears.update_config(configfile=options.config) try: server_group = ServerGroup.get(int(options.server_group_id)) except: print "The provided server group does not exist." sys.exit(0) if options.output_path: output_path = options.output_path dir = dirname(abspath(output_path)) if not exists(dir): os.makedirs(dir) else: output_path = "Stats.csv"
import turbogears from nose import with_setup from turbogears import testutil, identity, visit from sercom.model import * from sercom.controllers import Root import datetime import cherrypy from turbogears import identity, visit from sercom.model import Visita turbogears.update_config(configfile='test.cfg', modulename='sercom.config') cherrypy.root = Root() class BaseTestController(testutil.DBTest): def create_current_user(self): return Alumno(padron='12345', nombre = "nombre", password = "******") def setUp(self): testutil.DBTest.setUp(self) turbogears.startup.startTurboGears() self.test_user = self.create_current_user() testutil.set_identity_user(self.test_user) self.session = testutil.BrowsingSession() self.session.goto('/login?login_user=12345&login_password=password&login_submit=Login&forward_url=/') def tearDown(self): turbogears.startup.stopTurboGears() testutil.DBTest.tearDown(self)
# $Id: test_metadata.py,v 1.1 2006/12/31 09:10:25 lmacken Exp $ import turbogears from turbogears import testutil, database, config turbogears.update_config(configfile='bodhi.cfg', modulename='bodhi.config') database.set_db_uri("sqlite:///:memory:") import shutil import tempfile from os.path import join, exists from bodhi.util import mkmetadatadir, get_nvr from bodhi.model import (Release, Package, PackageUpdate, Bugzilla, CVE, PackageBuild) from bodhi.buildsys import get_session from bodhi.metadata import ExtendedMetadata from yum.update_md import UpdateMetadata class TestExtendedMetadata(testutil.DBTest): def test_extended_metadata(self): # grab the name of a build in updates-testing, and create it in our db koji = get_session() builds = koji.listTagged('dist-f13-updates-testing', latest=True) # Create all of the necessary database entries release = Release(name='F13', long_name='Fedora 13', id_prefix='FEDORA', dist_tag='dist-f13') package = Package(name=builds[0]['package_name'])
#!C:\Python24\python.exe import pkg_resources pkg_resources.require("TurboGears") import turbogears import cherrypy cherrypy.lowercase_api = True from os.path import * import sys # first look on the command line for a desired config file, # if it's not on the command line, then # look for setup.py in this directory. If it's not there, this script is # probably installed if len(sys.argv) > 1: turbogears.update_config(configfile=sys.argv[1], modulename="mesa.config") elif exists(join(dirname(__file__), "setup.py")): turbogears.update_config(configfile="dev.cfg", modulename="mesa.config") else: turbogears.update_config(configfile="prod.cfg", modulename="mesa.config") from mesa.controllers import Root turbogears.start_server(Root())