本文整理汇总了Python中message.Messager.error方法的典型用法代码示例。如果您正苦于以下问题:Python Messager.error方法的具体用法?Python Messager.error怎么用?Python Messager.error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类message.Messager
的用法示例。
在下文中一共展示了Messager.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_match_regex
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def _get_match_regex(text, text_match="word", match_case=False,
whole_string=False):
"""
Helper for the various search_anns_for_ functions.
"""
if match_case:
regex_flags = 0
else:
regex_flags = re.IGNORECASE
if text is None:
text = ''
if text_match == "word":
# full word match: require word boundaries or, optionally,
# whole string boundaries
if whole_string:
return re.compile(r'^'+re.escape(text)+r'$', regex_flags)
else:
return re.compile(r'\b'+re.escape(text)+r'\b', regex_flags)
elif text_match == "substring":
# any substring match, as text (nonoverlapping matches)
return re.compile(re.escape(text), regex_flags)
elif text_match == "regex":
try:
return re.compile(text, regex_flags)
except: # whatever (sre_constants.error, other?)
Messager.warning('Given string "%s" is not a valid regular expression.' % text)
return None
else:
Messager.error('Unrecognized search match specification "%s"' % text_match)
return None
示例2: _server_crash
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def _server_crash(cookie_hdrs, e):
from config import ADMIN_CONTACT_EMAIL, DEBUG
from jsonwrap import dumps
from message import Messager
stack_trace = _get_stack_trace()
if DEBUG:
# Send back the stack-trace as json
error_msg = '\n'.join(('Server Python crash, stack-trace is:\n',
stack_trace))
Messager.error(error_msg, duration=-1)
else:
# Give the user an error message
# Use the current time since epoch as an id for later log look-up
error_msg = ('The server encountered a serious error, '
'please contact the administrators at %s '
'and give the id #%d'
) % (ADMIN_CONTACT_EMAIL, int(time()))
Messager.error(error_msg, duration=-1)
# Print to stderr so that the exception is logged by the webserver
print(stack_trace, file=stderr)
json_dic = {
'exception': 'serverCrash',
}
return (cookie_hdrs, ((JSON_HDR, ), dumps(Messager.output_json(json_dic))))
示例3: _config_check
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def _config_check():
from message import Messager
from sys import path
from copy import deepcopy
from os.path import dirname
# Reset the path to force config.py to be in the root (could be hacked
# using __init__.py, but we can be monkey-patched anyway)
orig_path = deepcopy(path)
# Can't you empty in O(1) instead of O(N)?
while path:
path.pop()
path.append(path_join(abspath(dirname(__file__)), '../..'))
# Check if we have a config, otherwise whine
try:
import config
del config
except ImportError, e:
path.extend(orig_path)
# "Prettiest" way to check specific failure
if e.message == 'No module named config':
Messager.error(_miss_config_msg(), duration=-1)
else:
Messager.error(_get_stack_trace(), duration=-1)
raise ConfigurationError
示例4: retrieve_stored
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def retrieve_stored(document, suffix):
stored_path = _stored_path()+'.'+suffix
if not isfile(stored_path):
# @ninjin: not sure what 'version' was supposed to be returned
# here, but none was defined, so returning that
# raise NoSVGError(version)
raise NoSVGError('None')
filename = document+'.'+suffix
# sorry, quick hack to get the content-type right
# TODO: send this with initial 'stored' response instead of
# guessing on suffix
if suffix == SVG_SUFFIX:
content_type = 'image/svg+xml'
elif suffix == PNG_SUFFIX:
content_type = 'image/png'
elif suffix == PDF_SUFFIX:
content_type = 'application/pdf'
elif suffix == EPS_SUFFIX:
content_type = 'application/postscript'
else:
Messager.error('Unknown suffix "%s"; cannot determine Content-Type' % suffix)
# TODO: reasonable backoff value
content_type = None
# Bail out with a hack since we violated the protocol
hdrs = [('Content-Type', content_type),
('Content-Disposition', 'inline; filename=' + filename)]
with open(stored_path, 'rb') as stored_file:
data = stored_file.read()
raise NoPrintJSONError(hdrs, data)
示例5: _parse_relation_annotation
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def _parse_relation_annotation(self, id, data, data_tail, input_file_path):
try:
type_delim = data.index(' ')
type, type_tail = (data[:type_delim], data[type_delim:])
except ValueError:
# cannot have a relation with just a type (contra event)
raise IdedAnnotationLineSyntaxError(id, self.ann_line, self.ann_line_num+1, input_file_path)
try:
args = [tuple(arg.split(':')) for arg in type_tail.split()]
except ValueError:
raise IdedAnnotationLineSyntaxError(id, self.ann_line, self.ann_line_num+1, input_file_path)
if len(args) != 2:
Messager.error('Error parsing relation: must have exactly two arguments')
raise IdedAnnotationLineSyntaxError(id, self.ann_line, self.ann_line_num+1, input_file_path)
args.sort()
if args[0][0] == args[1][0]:
Messager.error('Error parsing relation: arguments must not be identical')
raise IdedAnnotationLineSyntaxError(id, self.ann_line, self.ann_line_num+1, input_file_path)
return BinaryRelationAnnotation(id, type,
args[0][0], args[0][1],
args[1][0], args[1][1],
data_tail, source_id=input_file_path)
示例6: ann_logger
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def ann_logger():
"""
Lazy initializer for the annotation logger. Returns None if
annotation logging is not configured and a logger otherwise.
"""
if ann_logger.__logger == False:
# not initialized
if ANNOTATION_LOG is None:
# not configured
ann_logger.__logger = None
else:
# initialize
try:
l = logging.getLogger('annotation')
l.setLevel(logging.INFO)
handler = logging.FileHandler(ANNOTATION_LOG)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s\t%(message)s')
handler.setFormatter(formatter)
l.addHandler(handler)
ann_logger.__logger = l
except IOError, e:
Messager.error("""Error: failed to initialize annotation log %s: %s.
Edit action not logged.
Please check ANNOTATION_LOG setting in config.py""" % (ANNOTATION_LOG, e))
logging.error("Failed to initialize annotation log %s: %s" %
(ANNOTATION_LOG, e))
ann_logger.__logger = None
示例7: ssdb_supstring_exists
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def ssdb_supstring_exists(s, dbname, threshold=DEFAULT_THRESHOLD):
"""Given a string s and a DB name, returns whether at least one string in
the associated simstring DB likely contains s as an (approximate)
substring."""
try:
import simstring
except ImportError:
Messager.error(SIMSTRING_MISSING_ERROR, duration=-1)
raise NoSimStringError
if threshold == 1.0:
# optimized (not hugely, though) for this common case
db = ssdb_open(dbname.encode('UTF-8'))
__set_db_measure(db, 'overlap')
db.threshold = threshold
result = db.retrieve(s)
db.close()
# assume simstring DBs always contain UTF-8 - encoded strings
result = [r.decode('UTF-8') for r in result]
for r in result:
if s in r:
return True
return False
else:
# naive implementation for everything else
return len(ssdb_supstring_lookup(s, dbname, threshold)) != 0
示例8: ann_logger
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def ann_logger(directory):
"""
Lazy initializer for the annotation logger. Returns None if
annotation logging is not configured for the given directory and a
logger otherwise.
"""
if ann_logger.__logger == False:
# not initialized
annlogfile = options_get_annlogfile(directory)
if annlogfile == '<NONE>':
# not configured
ann_logger.__logger = None
else:
# initialize
try:
l = logging.getLogger('annotation')
l.setLevel(logging.INFO)
handler = logging.FileHandler(annlogfile)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s\t%(message)s')
handler.setFormatter(formatter)
l.addHandler(handler)
ann_logger.__logger = l
except IOError, e:
Messager.error("""Error: failed to initialize annotation log %s: %s.
Edit action not logged.
Please check the Annotation-log logfile setting in tools.conf""" % (annlogfile, e))
logging.error("Failed to initialize annotation log %s: %s" %
(annlogfile, e))
ann_logger.__logger = None
示例9: reverse_arc
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def reverse_arc(collection, document, origin, target, type, attributes=None):
directory = collection
#undo_resp = {} # TODO
real_dir = real_directory(directory)
#mods = ModificationTracker() # TODO
projectconf = ProjectConfiguration(real_dir)
document = path_join(real_dir, document)
with TextAnnotations(document) as ann_obj:
# bail as quick as possible if read-only
if ann_obj._read_only:
raise AnnotationsIsReadOnlyError(ann_obj.get_document())
if projectconf.is_equiv_type(type):
Messager.warning('Cannot reverse Equiv arc')
elif not projectconf.is_relation_type(type):
Messager.warning('Can only reverse configured binary relations')
else:
# OK to reverse
found = None
# TODO: more sensible lookup
for ann in ann_obj.get_relations():
if (ann.arg1 == origin and ann.arg2 == target and
ann.type == type):
found = ann
break
if found is None:
Messager.error('reverse_arc: failed to identify target relation (from %s to %s, type %s) (deleted?)' % (str(origin), str(target), str(type)))
else:
# found it; just adjust this
found.arg1, found.arg2 = found.arg2, found.arg1
# TODO: modification tracker
json_response = {}
json_response['annotations'] = _json_from_ann(ann_obj)
return json_response
示例10: ssdb_build
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def ssdb_build(strs, dbname, ngram_length=DEFAULT_NGRAM_LENGTH, include_marks=DEFAULT_INCLUDE_MARKS):
"""
Given a list of strings, a DB name, and simstring options, builds
a simstring DB for the strings.
"""
try:
import simstring
except ImportError:
Messager.error(SIMSTRING_MISSING_ERROR, duration=-1)
raise NoSimStringError
dbfn = __ssdb_path(dbname)
try:
# only library defaults (n=3, no marks) supported just now (TODO)
assert ngram_length == 3, "Error: unsupported n-gram length"
assert include_marks == False, "Error: begin/end marks not supported"
db = simstring.writer(dbfn)
for s in strs:
db.insert(s)
db.close()
except:
print >> sys.stderr, "Error building simstring DB"
raise
return dbfn
示例11: possible_arc_types
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def possible_arc_types(collection, origin_type, target_type):
directory = collection
real_dir = real_directory(directory)
projectconf = ProjectConfiguration(real_dir)
response = {}
try:
possible = projectconf.arc_types_from_to(origin_type, target_type)
# TODO: proper error handling
if possible is None:
Messager.error('Error selecting arc types!', -1)
elif possible == []:
# nothing to select
response['html'] = generate_empty_fieldset()
response['keymap'] = {}
response['empty'] = True
else:
# XXX TODO: intentionally breaking this; KB shortcuts
# should no longer be sent here. Remove 'keymap' and
# 'html' args once clientside generation done.
arc_kb_shortcuts = {} #select_keyboard_shortcuts(possible)
response['keymap'] = {}
for k, p in arc_kb_shortcuts.items():
response['keymap'][k] = "arc_"+p
response['html'] = generate_arc_type_html(projectconf, possible, arc_kb_shortcuts)
except:
Messager.error('Error selecting arc types!', -1)
raise
return response
示例12: __read_term_hierarchy
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def __read_term_hierarchy(input):
root_nodes = []
last_node_at_depth = {}
macros = {}
for l in input:
# skip empties and lines starting with '#'
if l.strip() == '' or re.match(r'^\s*#', l):
continue
# interpret lines of only hyphens as separators
# for display
if re.match(r'^\s*-+\s*$', l):
# TODO: proper placeholder and placing
root_nodes.append(SEPARATOR_STR)
continue
# interpret lines of the format <STR1>=STR2 as "macro"
# definitions, defining <STR1> as a placeholder that should be
# replaced with STR2 whevever it occurs.
m = re.match(r'^<([a-zA-Z_-]+)>=\s*(.*?)\s*$', l)
if m:
name, value = m.groups()
if name in reserved_macro_name:
Messager.error("Cannot redefine <%s> in configuration, it is a reserved name." % name)
# TODO: proper exception
assert False
else:
macros["<%s>" % name] = value
continue
# macro expansion
for n in macros:
l = l.replace(n, macros[n])
m = re.match(r'^(\s*)([^\t]+)(?:\t(.*))?$', l)
assert m, "Error parsing line: '%s'" % l
indent, terms, args = m.groups()
terms = [t.strip() for t in terms.split("|") if t.strip() != ""]
if args is None or args.strip() == "":
args = []
else:
args = [a.strip() for a in args.split(",") if a.strip() != ""]
# depth in the ontology corresponds to the number of
# spaces in the initial indent.
depth = len(indent)
n = TypeHierarchyNode(terms, args)
if depth == 0:
# root level, no children assignments
root_nodes.append(n)
else:
# assign as child of last node at the depth of the parent
assert depth-1 in last_node_at_depth, "Error: no parent for '%s'" % l
last_node_at_depth[depth-1].children.append(n)
last_node_at_depth[depth] = n
return root_nodes
示例13: _safe_serve
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def _safe_serve(params, client_ip, client_hostname, cookie_data):
# Note: Only logging imports here
from config import WORK_DIR
from logging import basicConfig as log_basic_config
# Enable logging
try:
from config import LOG_LEVEL
log_level = _convert_log_level(LOG_LEVEL)
except ImportError:
from logging import WARNING as LOG_LEVEL_WARNING
log_level = LOG_LEVEL_WARNING
log_basic_config(filename=path_join(WORK_DIR, "server.log"), level=log_level)
# Do the necessary imports after enabling the logging, order critical
try:
from common import ProtocolError, ProtocolArgumentError, NoPrintJSONError
from dispatch import dispatch
from jsonwrap import dumps
from message import Messager
from session import get_session, init_session, close_session, NoSessionError, SessionStoreError
except ImportError:
# Note: Heisenbug trap for #612, remove after resolved
from logging import critical as log_critical
from sys import path as sys_path
log_critical("Heisenbug trap reports: " + str(sys_path))
raise
init_session(client_ip, cookie_data=cookie_data)
response_is_JSON = True
try:
# Unpack the arguments into something less obscure than the
# Python FieldStorage object (part dictonary, part list, part FUBAR)
http_args = DefaultNoneDict()
for k in params:
# Also take the opportunity to convert Strings into Unicode,
# according to HTTP they should be UTF-8
try:
http_args[k] = unicode(params.getvalue(k), encoding="utf-8")
except TypeError:
Messager.error(
"protocol argument error: expected string argument %s, got %s" % (k, type(params.getvalue(k)))
)
raise ProtocolArgumentError
# Dispatch the request
json_dic = dispatch(http_args, client_ip, client_hostname)
except ProtocolError, e:
# Internal error, only reported to client not to log
json_dic = {}
e.json(json_dic)
# Add a human-readable version of the error
err_str = str(e)
if err_str != "":
Messager.error(err_str, duration=-1)
示例14: _create_relation
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def _create_relation(ann_obj, projectconf, mods, origin, target, type,
attributes, old_type, old_target, undo_resp={}):
attributes = _parse_attributes(attributes)
if old_type is not None or old_target is not None:
assert type in projectconf.get_relation_types(), (
('attempting to convert relation to non-relation "%s" ' % (target.type, )) +
('(legit types: %s)' % (unicode(projectconf.get_relation_types()), )))
sought_target = (old_target
if old_target is not None else target.id)
sought_type = (old_type
if old_type is not None else type)
sought_origin = origin.id
# We are to change the type, target, and/or attributes
found = None
for ann in ann_obj.get_relations():
if (ann.arg1 == sought_origin and ann.arg2 == sought_target and
ann.type == sought_type):
found = ann
break
if found is None:
# TODO: better response
Messager.error('_create_relation: failed to identify target relation (type %s, target %s) (deleted?)' % (str(old_type), str(old_target)))
elif found.arg2 == target.id and found.type == type:
# no changes to type or target
pass
else:
# type and/or target changed, mark.
before = unicode(found)
found.arg2 = target.id
found.type = type
mods.change(before, found)
target_ann = found
else:
# Create a new annotation
new_id = ann_obj.get_new_id('R')
# TODO: do we need to support different relation arg labels
# depending on participant types? This doesn't.
rels = projectconf.get_relations_by_type(type)
rel = rels[0] if rels else None
assert rel is not None and len(rel.arg_list) == 2
a1l, a2l = rel.arg_list
ann = BinaryRelationAnnotation(new_id, type, a1l, origin.id, a2l, target.id, '\t')
mods.addition(ann)
ann_obj.add_annotation(ann)
target_ann = ann
# process attributes
if target_ann is not None:
_set_attributes(ann_obj, ann, attributes, mods, undo_resp)
elif attributes != None:
Messager.error('_create_relation: cannot set arguments: failed to identify target relation (type %s, target %s) (deleted?)' % (str(old_type), str(old_target)))
return target_ann
示例15: filter_folia
# 需要导入模块: from message import Messager [as 别名]
# 或者: from message.Messager import error [as 别名]
def filter_folia(ann_obj):
forbidden_ann=[]
response = {"entities":[],"comments":[],"relations":[],"attributes":[],"tokens":{}}
try:
import simplejson as json
import session
string = session.load_conf()["config"]
val = json.loads(string)["foliaLayers"]
except session.NoSessionError:
val = []
except KeyError:
val = []
pass
except Exception as e:
val = []
Messager.error("Error while enabling/disabling folia layers: "+str(e))
pass
try:
response["tokens"]=ann_obj.folia["tokens"]
except KeyError as e:
pass
if val:
removed = set()
forbidden = set(i for i in val)
result = []
alternatives = "alter" in val
try:
if 'all' in val:
response["tokens"]={}
return response
else:
for i in ann_obj.folia["entities"]:
if not i[3] in forbidden and not ( i[4] and alternatives ):
result.append(i)
else:
removed.add(i[0])
response["entities"] = result
result = []
for i in ann_obj.folia["relations"]:
if not i[3] in forbidden and not i[2][0][1] in removed and not i[2][1][1] in removed and not ( i[4] and alternatives ):
result.append(i)
else:
removed.add(i[0])
response["relations"] = result
result = []
for i in ann_obj.folia["attributes"]:
if not i[2] in removed:
result.append(i)
response["attributes"] = result
result = []
for i in ann_obj.folia["comments"]:
if not i[0] in removed:
result.append(i)
response["comments"] = result
except KeyError:
pass
else:
response = ann_obj.folia
return response