本文整理汇总了Python中girder.constants.TerminalColor.warning方法的典型用法代码示例。如果您正苦于以下问题:Python TerminalColor.warning方法的具体用法?Python TerminalColor.warning怎么用?Python TerminalColor.warning使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类girder.constants.TerminalColor
的用法示例。
在下文中一共展示了TerminalColor.warning方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: route
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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))
示例2: route
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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))
示例3: getPluginDir
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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
示例4: __init__
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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.'))
示例5: __init__
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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.'))
示例6: loadPlugins
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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
示例7: getDbConnection
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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
示例8: findAllPlugins
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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
示例9: loadPlugins
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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
示例10: route
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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))
示例11: _ensureInit
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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__))
示例12: findAllPlugins
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
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
示例13: addModel
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
def addModel(name, model, resources=None, silent=False):
"""
Add a model to the Swagger documentation.
:param resources: The type(s) of resource(s) to add the model to. New
resource types may be implicitly defined, with the expectation that
routes will be added for them at some point. If no resources are
passed, the model will be exposed for every resource type
:param resources: str or tuple/list[str]
:param name: The name of the model.
:type name: str
:param model: The model to add.
:type model: dict
:param silent: Set this to True to suppress warnings.
:type silent: bool
.. warning:: This is a low-level API which does not validate the format of
``model``. See the `Swagger Model documentation`_ for a complete
specification of the correct format for ``model``.
.. versionchanged:: The syntax and behavior of this function was modified
after v1.3.2. The previous implementation did not include a resources
parameter.
.. _Swagger Model documentation: https://github.com/swagger-api/
swagger-spec/blob/d79c205485d702302003d4de2f2c980d1caf10f9/
versions/1.2.md#527-model-object
"""
if resources:
if isinstance(resources, six.string_types):
resources = (resources,)
for resource in resources:
models[resource][name] = model
else:
if not silent:
print(TerminalColor.warning(
'WARNING: adding swagger models without specifying resources '
'to bind to is discouraged (%s).' % name))
models[None][name] = model
示例14: getPluginDirs
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
def getPluginDirs(curConfig=None):
"""Return an ordered list of directories that plugins can live in."""
failedPluginDirs = set()
if curConfig is None:
curConfig = _config.getConfig()
if 'plugins' in curConfig and 'plugin_directory' in curConfig['plugins']:
pluginDirs = curConfig['plugins']['plugin_directory'].split(':')
else:
pluginDirs = [defaultPluginDir()]
for pluginDir in pluginDirs:
try:
mkdir(pluginDir)
except OSError:
print(TerminalColor.warning(
'Could not create plugin directory %s.' % pluginDir))
failedPluginDirs.add(pluginDir)
return [dir for dir in pluginDirs if dir not in failedPluginDirs]
示例15: reconnect
# 需要导入模块: from girder.constants import TerminalColor [as 别名]
# 或者: from girder.constants.TerminalColor import warning [as 别名]
def reconnect(self):
"""
Reconnect to the database and rebuild indices if necessary. Users should
typically not have to call this method.
"""
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.create_index(index[0], **index[1])
else:
self.collection.create_index(index)
if type(self._textIndex) is dict:
textIdx = [(k, 'text') for k in six.viewkeys(self._textIndex)]
try:
self.collection.create_index(
textIdx, weights=self._textIndex,
default_language=self._textLanguage)
except pymongo.errors.OperationFailure:
print(
TerminalColor.warning('WARNING: Text search not enabled.'))