本文整理汇总了Python中girder.constants.TerminalColor类的典型用法代码示例。如果您正苦于以下问题:Python TerminalColor类的具体用法?Python TerminalColor怎么用?Python TerminalColor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TerminalColor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process_annotations
def process_annotations(event):
"""Add annotations to an image on a ``data.process`` event"""
info = event.info
if 'anot' in info.get('file', {}).get('exts', []):
reference = info.get('reference', None)
try:
reference = json.loads(reference)
except (ValueError, TypeError):
print(TerminalColor.error(
'Warning: Could not get reference from the annotation param. '
'Make sure you have at ctk-cli>=1.3.1 installed.'
))
return
if 'userId' not in reference or 'itemId' not in reference:
print(TerminalColor.error(
'Annotation reference does not contain required information.'
))
return
userId = reference['userId']
imageId = reference['itemId']
# load model classes
Item = ModelImporter.model('item')
File = ModelImporter.model('file')
User = ModelImporter.model('user')
Annotation = ModelImporter.model('annotation', plugin='large_image')
# load models from the database
user = User.load(userId, force=True)
image = File.load(imageId, level=AccessType.READ, user=user)
item = Item.load(image['itemId'], level=AccessType.WRITE, user=user)
file = File.load(
info.get('file', {}).get('_id'),
level=AccessType.READ, user=user
)
if not (item and user and file):
print(TerminalColor.error(
'Could not load models from the database'
))
return
try:
data = json.loads(
''.join(File.download(file)())
)
except Exception:
print(TerminalColor.error(
'Could not parse annotation file'
))
return
Annotation.createAnnotation(
item,
user,
data
)
示例2: route
def route(self, method, route, handler, nodoc=False, resource=None):
"""
Define a route for your REST resource.
:param method: The HTTP method, e.g. 'GET', 'POST', 'PUT'
:type method: str
:param route: The route, as a list of path params relative to the
resource root. Elements of this list starting with ':' are assumed to
be wildcards.
:type route: list
:param handler: The method to be called if the route and method are
matched by a request. Wildcards in the route will be expanded and
passed as kwargs with the same name as the wildcard identifier.
:type handler: function
:param nodoc: If your route intentionally provides no documentation,
set this to True to disable the warning on startup.
:type nodoc: bool
"""
if not hasattr(self, '_routes'):
self._routes = collections.defaultdict(
lambda: collections.defaultdict(list))
# Insertion sort to maintain routes in required order.
def shouldInsert(a, b):
"""
Return bool representing whether route a should go before b. Checks
by comparing each token in order and making sure routes with
literals in forward positions come before routes with wildcards
in those positions.
"""
for i in xrange(0, len(a)):
if a[i][0] != ':' and b[i][0] == ':':
return True
return False
nLengthRoutes = self._routes[method.lower()][len(route)]
for i in xrange(0, len(nLengthRoutes)):
if shouldInsert(route, nLengthRoutes[i][0]):
nLengthRoutes.insert(i, (route, handler))
break
else:
nLengthRoutes.append((route, handler))
# Now handle the api doc if the handler has any attached
if resource is None and hasattr(self, 'resourceName'):
resource = self.resourceName
elif resource is None:
resource = handler.__module__.rsplit('.', 1)[-1]
if hasattr(handler, 'description'):
if handler.description is not None:
docs.addRouteDocs(
resource=resource, route=route, method=method,
info=handler.description.asDict(), handler=handler)
elif not nodoc:
routePath = '/'.join([resource] + list(route))
print TerminalColor.warning(
'WARNING: No description docs present for route {} {}'
.format(method, routePath))
示例3: loadPlugins
def loadPlugins(plugins, root, appconf, apiRoot=None, curConfig=None,
buildDag=True):
"""
Loads a set of plugins into the application.
:param plugins: The set of plugins to load, by directory name.
:type plugins: list
:param root: The root node of the server tree.
:type root: object
:param appconf: The server's cherrypy configuration object.
:type appconf: dict
:param apiRoot: The cherrypy api root object.
:type apiRoot: object or None
:param curConfig: A girder config object to use.
:type curConfig: dict or None
:param buildDag: If the ``plugins`` parameter is already a topo-sorted list
with all dependencies resolved, set this to False and it will skip
rebuilding the DAG. Otherwise the dependency resolution and sorting
will occur within this method.
:type buildDag: bool
:returns: A 3-tuple containing the modified root, config, and apiRoot
objects.
:rtype tuple:
"""
# Register a pseudo-package for the root of all plugins. This must be
# present in the system module list in order to avoid import warnings.
if curConfig is None:
curConfig = _config.getConfig()
if 'plugins' in curConfig and 'plugin_directory' in curConfig['plugins']:
print(TerminalColor.warning(
'Warning: the plugin_directory setting is deprecated. Please use '
'the `girder-install plugin` command and remove this setting from '
'your config file.'))
if ROOT_PLUGINS_PACKAGE not in sys.modules:
module = imp.new_module(ROOT_PLUGINS_PACKAGE)
girder.plugins = module
sys.modules[ROOT_PLUGINS_PACKAGE] = module
print(TerminalColor.info('Resolving plugin dependencies...'))
if buildDag:
plugins = getToposortedPlugins(plugins, curConfig, ignoreMissing=True)
for plugin in plugins:
try:
root, appconf, apiRoot = loadPlugin(
plugin, root, appconf, apiRoot, curConfig=curConfig)
print(TerminalColor.success('Loaded plugin "%s"' % plugin))
except Exception:
print(TerminalColor.error(
'ERROR: Failed to load plugin "%s":' % plugin))
girder.logger.exception('Plugin load failure: %s' % plugin)
traceback.print_exc()
return root, appconf, apiRoot
示例4: getDbConnection
def getDbConnection(uri=None, replicaSet=None):
"""
Get a MongoClient object that is connected to the configured database.
We lazy-instantiate a module-level singleton, the MongoClient objects
manage their own connection pools internally.
:param uri: if specified, connect to this mongo db rather than the one in
the config.
:param replicaSet: if uri is specified, use this replica set.
"""
global _dbClients
origKey = (uri, replicaSet)
if origKey in _dbClients:
return _dbClients[origKey]
if uri is None or uri == '':
dbConf = getDbConfig()
uri = dbConf.get('uri')
replicaSet = dbConf.get('replica_set')
clientOptions = {
'connectTimeoutMS': 15000,
# This is the maximum time between when we fetch data from a cursor.
# If it times out, the cursor is lost and we can't reconnect. If it
# isn't set, we have issues with replica sets when the primary goes
# down. This value can be overridden in the mongodb uri connection
# string with the socketTimeoutMS.
'socketTimeoutMS': 60000,
}
if uri is None:
dbUriRedacted = 'mongodb://localhost:27017/girder'
print(TerminalColor.warning('WARNING: No MongoDB URI specified, using '
'the default value'))
client = pymongo.MongoClient(dbUriRedacted, **clientOptions)
else:
parts = uri.split('@')
if len(parts) == 2:
dbUriRedacted = 'mongodb://' + parts[1]
else:
dbUriRedacted = uri
if replicaSet:
client = pymongo.MongoReplicaSetClient(
uri, replicaSet=replicaSet,
read_preference=ReadPreference.SECONDARY_PREFERRED,
**clientOptions)
else:
client = pymongo.MongoClient(uri, **clientOptions)
client = MongoProxy(client, logger=logger)
_dbClients[origKey] = _dbClients[(uri, replicaSet)] = client
desc = ''
if replicaSet:
desc += ', replica set: %s' % replicaSet
print(TerminalColor.info('Connected to MongoDB: %s%s' % (dbUriRedacted,
desc)))
return client
示例5: route
def route(self, method, route, handler, nodoc=False, resource=None):
"""
Define a route for your REST resource.
:param method: The HTTP method, e.g. 'GET', 'POST', 'PUT', 'PATCH'
:type method: str
:param route: The route, as a list of path params relative to the
resource root. Elements of this list starting with ':' are assumed
to be wildcards.
:type route: tuple
:param handler: The method to be called if the route and method are
matched by a request. Wildcards in the route will be expanded and
passed as kwargs with the same name as the wildcard identifier.
:type handler: function
:param nodoc: If your route intentionally provides no documentation,
set this to True to disable the warning on startup.
:type nodoc: bool
:param resource: The name of the resource at the root of this route.
"""
if not hasattr(self, '_routes'):
self._routes = collections.defaultdict(
lambda: collections.defaultdict(list))
# Insertion sort to maintain routes in required order.
nLengthRoutes = self._routes[method.lower()][len(route)]
for i in xrange(0, len(nLengthRoutes)):
if self._shouldInsertRoute(route, nLengthRoutes[i][0]):
nLengthRoutes.insert(i, (route, handler))
break
else:
nLengthRoutes.append((route, handler))
# Now handle the api doc if the handler has any attached
if resource is None and hasattr(self, 'resourceName'):
resource = self.resourceName
elif resource is None:
resource = handler.__module__.rsplit('.', 1)[-1]
if hasattr(handler, 'description'):
if handler.description is not None:
docs.addRouteDocs(
resource=resource, route=route, method=method,
info=handler.description.asDict(), handler=handler)
elif not nodoc:
routePath = '/'.join([resource] + list(route))
print TerminalColor.warning(
'WARNING: No description docs present for route {} {}'
.format(method, routePath))
# Warn if there is no access decorator on the handler function
if not hasattr(handler, 'accessLevel'):
routePath = '/'.join([resource] + list(route))
print TerminalColor.warning(
'WARNING: No access level specified for route {} {}'
.format(method, routePath))
示例6: loadPlugins
def loadPlugins(plugins, root, appconf, apiRoot=None, curConfig=None):
"""
Loads a set of plugins into the application. The list passed in should not
already contain dependency information; dependent plugins will be loaded
automatically.
:param plugins: The set of plugins to load, by directory name.
:type plugins: list
:param root: The root node of the server tree.
:param appconf: The server's cherrypy configuration object.
:type appconf: dict
:returns: A list of plugins that were actually loaded, once dependencies
were resolved and topological sort was performed.
"""
# Register a pseudo-package for the root of all plugins. This must be
# present in the system module list in order to avoid import warnings.
if curConfig is None:
curConfig = config.getConfig()
if 'plugins' in curConfig and 'plugin_directory' in curConfig['plugins']:
print(TerminalColor.warning(
'Warning: the plugin_directory setting is deprecated. Please use '
'the `girder-install plugin` command and remove this setting from '
'your config file.'))
if ROOT_PLUGINS_PACKAGE not in sys.modules:
module = imp.new_module(ROOT_PLUGINS_PACKAGE)
girder.plugins = module
sys.modules[ROOT_PLUGINS_PACKAGE] = module
print(TerminalColor.info('Resolving plugin dependencies...'))
filteredDepGraph = {
pluginName: info['dependencies']
for pluginName, info in six.viewitems(findAllPlugins(curConfig))
if pluginName in plugins
}
for pset in toposort(filteredDepGraph):
for plugin in pset:
try:
root, appconf, apiRoot = loadPlugin(
plugin, root, appconf, apiRoot, curConfig=curConfig)
print(TerminalColor.success('Loaded plugin "{}"'
.format(plugin)))
except Exception:
print(TerminalColor.error(
'ERROR: Failed to load plugin "{}":'.format(plugin)))
traceback.print_exc()
return root, appconf, apiRoot
示例7: findAllPlugins
def findAllPlugins(curConfig=None):
"""
Walks the plugins directories to find all of the plugins. If the plugin has
a plugin.json file, this reads that file to determine dependencies.
"""
allPlugins = {}
pluginDirs = getPluginDirs(curConfig)
if not pluginDirs:
print(TerminalColor.warning('Plugin directory not found. No plugins '
'loaded.'))
return allPlugins
for pluginDir in pluginDirs:
dirs = [dir for dir in os.listdir(pluginDir) if os.path.isdir(
os.path.join(pluginDir, dir))]
for plugin in dirs:
data = {}
configJson = os.path.join(pluginDir, plugin, 'plugin.json')
configYml = os.path.join(pluginDir, plugin, 'plugin.yml')
if os.path.isfile(configJson):
with open(configJson) as conf:
try:
data = json.load(conf)
except ValueError as e:
print(
TerminalColor.error(
('ERROR: Plugin "%s": '
'plugin.json is not valid JSON.') % plugin))
print(e)
continue
elif os.path.isfile(configYml):
with open(configYml) as conf:
try:
data = yaml.safe_load(conf)
except yaml.YAMLError as e:
print(
TerminalColor.error(
('ERROR: Plugin "%s": '
'plugin.yml is not valid YAML.') % plugin))
print(e)
continue
allPlugins[plugin] = {
'name': data.get('name', plugin),
'description': data.get('description', ''),
'version': data.get('version', ''),
'dependencies': set(data.get('dependencies', []))
}
return allPlugins
示例8: loadPlugins
def loadPlugins(plugins, root, appconf, apiRoot=None, curConfig=None):
"""
Loads a set of plugins into the application. The list passed in should not
already contain dependency information; dependent plugins will be loaded
automatically.
:param plugins: The set of plugins to load, by directory name.
:type plugins: list
:param root: The root node of the server tree.
:param appconf: The server's cherrypy configuration object.
:type appconf: dict
:returns: A list of plugins that were actually loaded, once dependencies
were resolved and topological sort was performed.
"""
# Register a pseudo-package for the root of all plugins. This must be
# present in the system module list in order to avoid import warnings.
if curConfig is None:
curConfig = config.getConfig()
if "plugins" in curConfig and "plugin_directory" in curConfig["plugins"]:
pluginDir = curConfig["plugins"]["plugin_directory"]
elif os.path.exists(os.path.join(PACKAGE_DIR, "plugins")):
pluginDir = os.path.join(PACKAGE_DIR, "plugins")
else:
pluginDir = os.path.join(ROOT_DIR, "plugins")
if ROOT_PLUGINS_PACKAGE not in sys.modules:
sys.modules[ROOT_PLUGINS_PACKAGE] = type(
"", (), {"__path__": pluginDir, "__package__": ROOT_PLUGINS_PACKAGE, "__name__": ROOT_PLUGINS_PACKAGE}
)()
print(TerminalColor.info("Resolving plugin dependencies..."))
filteredDepGraph = {
pluginName: info["dependencies"]
for pluginName, info in six.iteritems(findAllPlugins(curConfig))
if pluginName in plugins
}
for pset in toposort(filteredDepGraph):
for plugin in pset:
try:
root, appconf, apiRoot = loadPlugin(plugin, root, appconf, apiRoot, curConfig=curConfig)
print(TerminalColor.success('Loaded plugin "{}"'.format(plugin)))
except Exception:
print(TerminalColor.error('ERROR: Failed to load plugin "{}":'.format(plugin)))
traceback.print_exc()
return root, appconf, apiRoot
示例9: __init__
def __init__(self):
self.name = None
self._indices = []
self._textIndex = None
self._textLanguage = None
self._filterKeys = {
AccessType.READ: set(),
AccessType.WRITE: set(),
AccessType.ADMIN: set(),
AccessType.SITE_ADMIN: set()
}
self.initialize()
db_connection = getDbConnection()
self.database = db_connection.get_default_database()
self.collection = MongoProxy(self.database[self.name])
for index in self._indices:
if isinstance(index, (list, tuple)):
self.collection.ensure_index(index[0], **index[1])
else:
self.collection.ensure_index(index)
if type(self._textIndex) is dict:
textIdx = [(k, 'text') for k in self._textIndex.keys()]
try:
self.collection.ensure_index(
textIdx, weights=self._textIndex,
default_language=self._textLanguage)
except pymongo.errors.OperationFailure:
print(
TerminalColor.warning('WARNING: Text search not enabled.'))
示例10: __init__
def __init__(self):
self.name = None
self._indices = []
self._textIndex = None
self._textLanguage = None
self.initialize()
db_cfg = getDbConfig()
db_connection = getDbConnection()
dbName = db_cfg['database']
self.database = db_connection[dbName]
self.collection = self.database[self.name]
for index in self._indices:
if isinstance(index, (list, tuple)):
self.collection.ensure_index(index[0], **index[1])
else:
self.collection.ensure_index(index)
if type(self._textIndex) is dict:
textIdx = [(k, 'text') for k in self._textIndex.keys()]
try:
self.collection.ensure_index(
textIdx, weights=self._textIndex,
default_language=self._textLanguage)
except pymongo.errors.OperationFailure:
print(
TerminalColor.warning('WARNING: Text search not enabled.'))
示例11: getPluginDir
def getPluginDir(curConfig=None):
"""
Returns the /path/to the currently configured plugin directory.
"""
if curConfig is None:
curConfig = config.getConfig()
# This uses the plugin directory specified in the config first.
if "plugins" in curConfig and "plugin_directory" in curConfig["plugins"]:
pluginsDir = curConfig["plugins"]["plugin_directory"]
# If none is specified, it looks if there is a plugin directory next
# to the girder python package. This is the case when running from the
# git repository.
elif os.path.isdir(os.path.join(ROOT_DIR, "plugins")):
pluginsDir = os.path.join(ROOT_DIR, "plugins")
# As a last resort, use plugins inside the girder python package.
# This is intended to occur when girder is pip installed.
else:
pluginsDir = os.path.join(PACKAGE_DIR, "plugins")
if not os.path.exists(pluginsDir):
try:
os.makedirs(pluginsDir)
except OSError:
if not os.path.exists(pluginsDir):
print(TerminalColor.warning("Could not create plugin directory."))
pluginsDir = None
return pluginsDir
示例12: findEntryPointPlugins
def findEntryPointPlugins(allPlugins):
# look for plugins enabled via setuptools `entry_points`
for entry_point in iter_entry_points(group='girder.plugin'):
# set defaults
allPlugins[entry_point.name] = {
'name': entry_point.name,
'description': '',
'version': '',
'dependencies': set()
}
configJson = os.path.join('girder', 'plugin.json')
configYml = os.path.join('girder', 'plugin.yml')
data = {}
try:
if pkg_resources.resource_exists(entry_point.name, configJson):
with pkg_resources.resource_stream(
entry_point.name, configJson) as conf:
try:
data = json.load(codecs.getreader('utf8')(conf))
except ValueError as e:
print(
TerminalColor.error(
'ERROR: Plugin "%s": plugin.json is not valid '
'JSON.' % entry_point.name))
print(e)
elif pkg_resources.resource_exists(entry_point.name, configYml):
with pkg_resources.resource_stream(
entry_point.name, configYml) as conf:
try:
data = yaml.safe_load(conf)
except yaml.YAMLError as e:
print(
TerminalColor.error(
'ERROR: Plugin "%s": plugin.yml is not valid '
'YAML.' % entry_point.name))
print(e)
except ImportError:
pass
if data == {}:
data = getattr(entry_point.load(), 'config', {})
allPlugins[entry_point.name].update(data)
allPlugins[entry_point.name]['dependencies'] = set(
allPlugins[entry_point.name]['dependencies'])
示例13: findAllPlugins
def findAllPlugins(curConfig=None):
"""
Walks the plugins directory to find all of the plugins. If the plugin has
a plugin.json file, this reads that file to determine dependencies.
"""
allPlugins = {}
pluginsDir = getPluginDir(curConfig)
if not pluginsDir:
print(TerminalColor.warning("Plugin directory not found. No plugins " "loaded."))
return allPlugins
dirs = [dir for dir in os.listdir(pluginsDir) if os.path.isdir(os.path.join(pluginsDir, dir))]
for plugin in dirs:
data = {}
configJson = os.path.join(pluginsDir, plugin, "plugin.json")
configYml = os.path.join(pluginsDir, plugin, "plugin.yml")
if os.path.isfile(configJson):
with open(configJson) as conf:
try:
data = json.load(conf)
except ValueError as e:
print(TerminalColor.error('ERROR: Plugin "%s": plugin.json is not valid JSON.' % plugin))
print(e)
continue
elif os.path.isfile(configYml):
with open(configYml) as conf:
try:
data = yaml.safe_load(conf)
except yaml.YAMLError as e:
print(TerminalColor.error('ERROR: Plugin "%s": plugin.yml is not valid YAML.' % plugin))
print(e)
continue
allPlugins[plugin] = {
"name": data.get("name", plugin),
"description": data.get("description", ""),
"version": data.get("version", ""),
"dependencies": set(data.get("dependencies", [])),
}
return allPlugins
示例14: route
def route(self, method, route, handler, nodoc=False):
"""
Define a route for your REST resource.
:param method: The HTTP method, e.g. 'GET', 'POST', 'PUT'
:type method: str
:param route: The route, as a list of path params relative to the
resource root. Elements of this list starting with ':' are assumed to
be wildcards.
:type route: list
:param handler: The method to be called if the route and method are
matched by a request. Wildcards in the route will be expanded and
passed as kwargs with the same name as the wildcard identifier.
:type handler: function
:param nodoc: If your route intentionally provides no documentation,
set this to True to disable the warning on startup.
:type nodoc: bool
"""
if not hasattr(self, '_routes'):
self._routes = {
'get': [],
'post': [],
'put': [],
'delete': []
}
self._routes[method.lower()].append((route, handler))
# Now handle the api doc if the handler has any attached
resourceName = handler.im_class.__module__.rsplit('.', 1)[-1]
if hasattr(handler, 'description'):
docs.addRouteDocs(
resource=resourceName, route=route, method=method,
info=handler.description.asDict(), handler=handler)
elif not nodoc:
routePath = '/'.join([resourceName] + list(route))
print TerminalColor.warning(
'WARNING: No description docs present for route {} {}'
.format(method, routePath))
示例15: _ensureInit
def _ensureInit(self):
"""
Calls ``Resource.__init__`` if the subclass constructor did not already
do so.
In the past, Resource subclasses were not expected to call their
superclass constructor.
"""
if not hasattr(self, '_routes'):
Resource.__init__(self)
print(TerminalColor.warning(
'WARNING: Resource subclass "%s" did not call '
'"Resource__init__()" from its constructor.' %
self.__class__.__name__))