本文整理汇总了Python中transifex.txcommon.log.logger.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create
def create(self):
"""
Create a new translation supplied as a string.
Returns:
A dict with information for the request.
Raises:
BadRequestError: There was a problem with the request.
NoContentError: There was no content string in the request.
"""
if 'content' not in self.data:
raise NoContentError("No content found.")
parser = parser_for(
mimetype=get_mimetype_from_method(self.resource.i18n_type)
)
if parser is None:
raise BadRequestError("Mimetype not supported")
file_ = tempfile.NamedTemporaryFile(
mode='wb',
suffix=get_file_extension_for_method(self.resource.i18n_type),
delete=False,
)
try:
file_.write(self.data['content'].encode('UTF-8'))
file_.close()
try:
parser.contents_check(file_.name)
except (FileCheckError, ParseError), e:
raise BadRequestError(e.message)
except Exception, e:
logger.error(e.message, exc_info=True)
raise BadRequestError("A strange error has happened.")
示例2: team_join_withdraw
def team_join_withdraw(request, project_slug, language_code):
team = get_object_or_404(Team, project__slug=project_slug,
language__code=language_code)
project = team.project
access_request = get_object_or_404(TeamAccessRequest, team__pk=team.pk,
user__pk=request.user.pk)
if request.POST:
try:
access_request.delete()
messages.success(request,_(
"You withdrew your request to join the '%s' team."
) % team.language.name)
# ActionLog & Notification
# TODO: Use signals
nt = 'project_team_join_withdrawn'
context = {'access_request': access_request,
'performer': request.user,}
# Logging action
action_logging(request.user, [project, team], nt, context=context)
if settings.ENABLE_NOTICES:
# Send notification for those that are observing this project
txnotification.send_observation_notices_for(project,
signal=nt, extra_context=context)
# Send notification for maintainers, coordinators
notification.send(set(itertools.chain(project.maintainers.all(),
team.coordinators.all())), nt, context)
except IntegrityError, e:
transaction.rollback()
logger.error("Something weird happened: %s" % str(e))
示例3: team_request_deny
def team_request_deny(request, project_slug, language_code):
team_request = get_object_or_404(TeamRequest, project__slug=project_slug,
language__code=language_code)
project = team_request.project
if request.POST:
try:
team_request.delete()
messages.success(request, _(
"You rejected the request by '%(user)s' for a '%(team)s' team."
) % {'team':team_request.language.name,
'user':team_request.user})
# ActionLog & Notification
# TODO: Use signals
nt = 'project_team_request_denied'
context = {'team_request': team_request,
'performer': request.user}
# Logging action
action_logging(request.user, [project], nt, context=context)
if settings.ENABLE_NOTICES:
# Send notification for those that are observing this project
txnotification.send_observation_notices_for(project,
signal=nt, extra_context=context)
# Send notification for maintainers and the user
notification.send(set(itertools.chain(project.maintainers.all(),
[team_request.user])), nt, context)
except IntegrityError, e:
transaction.rollback()
logger.error("Something weird happened: %s" % str(e))
示例4: error_contacting_app
def error_contacting_app(request, url, app, exception):
"""Handle the case, where an app did not respond.
This view is called, if there was a HTTP error, when contacting the remote
tx app.
"""
if all([exception.status_code, exception.content]):
log_msg = (
"Error visiting URL %s for app %s: status code "
"was %s and error_message %s" % (
url, app.name, exception.status_code, exception.content
)
)
view_msg = _("TxApp responded with an error: %s" % exception.content)
else:
log_msg = "Error contacting remote server: url is %s" % url
view_msg = _("Error contacting app.")
logger.error(log_msg)
return render_to_response(
'txapp_error.html',
{
'app_name': app.name,
'error_message': view_msg
},
context_instance=RequestContext(request)
)
示例5: _update
def _update(self, request, project_slug, resource_slug, lang_code=None):
# Permissions handling
try:
resource = Resource.objects.get(
slug=resource_slug, project__slug=project_slug
)
except Resource.DoesNotExist:
return rc.NOT_FOUND
if lang_code == "source":
language = resource.source_language
else:
try:
language = Language.objects.by_code_or_alias(lang_code)
except Language.DoesNotExist:
logger.error("Weird! Selected language code (%s) does "
"not match with any language in the database."
% lang_code)
return BAD_REQUEST(
"Selected language code (%s) does not match with any"
"language in the database." % lang_code
)
team = Team.objects.get_or_none(resource.project, lang_code)
check = ProjectPermission(request.user)
if (not check.submit_translations(team or resource.project) or\
not resource.accept_translations) and not\
check.maintain(resource.project):
return rc.FORBIDDEN
try:
t = Translation.get_object("create", request, resource, language)
res = t.create()
except BadRequestError, e:
return BAD_REQUEST(unicode(e))
示例6: create
def create(self):
"""
Create a new translation supplied as a string.
Returns:
A dict with information for the request.
Raises:
BadRequestError: There was a problem with the request.
NoContentError: There was no content string in the request.
"""
if 'content' not in self.data:
raise NoContentError("No content found.")
parser = registry.appropriate_handler(
self.resource, language=self.language
)
if parser is None:
raise BadRequestError("I18n type is not supported: %s" % i18n_type)
file_ = tempfile.NamedTemporaryFile(
mode='wb',
suffix=registry.extensions_for(self.resource.i18n_method)[0],
delete=False,
)
try:
file_.write(self.data['content'].encode('UTF-8'))
file_.close()
try:
parser.bind_file(file_.name)
parser.is_content_valid()
except (FileCheckError, ParseError), e:
raise BadRequestError(unicode(e))
except Exception, e:
logger.error(unicode(e), exc_info=True)
raise BadRequestError("A strange error has happened.")
示例7: get
def get(self, start=None, end=None, pseudo_type=None):
"""
Return the requested translation in a json string.
If self.language is None, return all translations.
Args:
start: Start for pagination.
end: End for pagination.
Returns:
A dict with the translation(s).
Raises:
BadRequestError: There was a problem with the request.
"""
try:
template = _compile_translation_template(
self.resource, self.language, pseudo_type
)
except Exception, e:
logger.error(e.message, exc_info=True)
raise BadRequestError(
"Error compiling the translation file: %s" % e
)
示例8: project_hub_join_withdraw
def project_hub_join_withdraw(request, project_slug):
# project_slug here refers to outsourced_project_slug. It was kept like
# it to keep consistency across url regexes.
hub_request = get_object_or_404(HubRequest, project__slug=project_slug)
if request.POST:
try:
_hub_request = copy.copy(hub_request)
hub_request.delete()
messages.success(request, _("Request to join '%s' project hub "
"was withdrawn") % _hub_request.project_hub)
# ActionLog & Notification
# TODO: Use signals
nt = 'project_hub_join_withdrawn'
context = {'hub_request': _hub_request,
'performer': request.user,
'sender': request.user}
# Logging action
action_logging(request.user, [_hub_request.project,
hub_request.project_hub], nt, context=context)
if settings.ENABLE_NOTICES:
# Send notification for maintainers, coordinators and the user
notification.send(_hub_request.project_hub.maintainers.all(),
nt, context)
except IntegrityError, e:
transaction.rollback()
logger.error("Something weird happened: %s" % e.message)
示例9: redis_exception_handler
def redis_exception_handler(func):
"""Decorator to handle redis backend exceptions."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except ConnectionError, e:
logger.critical("Cannot connect to redis: %s" % e, exc_info=True)
except Exception, e:
logger.error("Error from redis: %s" % e, exc_info=True)
示例10: wrapper
def wrapper(*args, **kwargs):
if settings.HAYSTACK_SEARCH_ENGINE == 'solr':
try:
soldadmin = SolrCoreAdmin(SearchQuerySet().query.backend.conn.url)
soldadmin.status()
func(*args, **kwargs)
except Exception, e:
logger.error('Error contacting SOLR backend: %s' %
getattr(e, 'reason', str(e)))
raise HaystackError('Error contacting SOLR backend.')
示例11: parse_file
def parse_file(self, is_source=False, lang_rules=None):
"""
Parse an INI file and create a stringset with all entries in the file.
"""
stringset = StringSet()
suggestions = StringSet()
fh = codecs.open(self.filename, "r", "utf-8")
try:
buf = fh.read()
finally:
fh.close()
for line in buf.split('\n'):
# Skip empty lines and comments
if not line or line.startswith(self.comment_chars):
continue
try:
source, trans = line.split('=', 1)
except ValueError:
# Maybe abort instead of skipping?
logger.error('Could not parse line "%s". Skipping...' % line)
continue
# In versions >=1.6 translations are surrounded by double quotes. So remove them
# Normally, if the translation starts with '"', it is a 1.6-file and must
# end with '"', since translations starting with '"' are not allowed in 1.5.
# But, let's check both the first and last character of the translation to be safe.
if trans.startswith('"') and trans.endswith('"'):
trans = trans[1:-1]
# We use empty context
context = ""
if is_source:
source_len = len(source)
new_line = line[:source_len] + re.sub(
re.escape(trans),
"%(hash)s_tr" % {'hash': hash_tag(source, context)},
line[source_len:]
)
# this looks fishy
buf = re.sub(re.escape(line), new_line, buf)
stringset.strings.append(GenericTranslation(source,
trans, rule=5, context=context,
pluralized=False, fuzzy=False,
obsolete=False))
self.stringset=stringset
self.suggestions=suggestions
if is_source:
self.template = str(buf.encode('utf-8'))
示例12: save_web_hook
def save_web_hook(sender, **kwargs):
"""Save a web hook, after saving a project (if defined)."""
project = kwargs["instance"]
form = kwargs["form"]
url = form.cleaned_data["webhook"]
if url:
try:
hook, created = WebHook.objects.get_or_create(project=project, kind="p", defaults={"url": url})
if not created:
hook.url = url
hook.save()
except Exception, e:
logger.error("Error saving hook for project %s: %s" % (project, e))
示例13: visit_url
def visit_url(sender, **kwargs):
"""Visit the URL for the project.
Send the slug of the project, the slug of the resource and the language
of the translation as identifiers. Send the translation percentage
as information.
Args:
sender: The rlstats object itself.
Returns:
True of False for success (or not).
"""
# TODO make it a celery task
# TODO increase the timeout in celery
stats = sender
resource = stats.resource
project = resource.project
language = stats.language
if 'post_function' in kwargs:
post_function = kwargs['post_function']
else:
post_function = requests.post
hooks = WebHook.objects.filter(project=project)
if not hooks:
logger.debug("Project %s has no web hooks" % project.slug)
return
event_info = {
'project': project.slug,
'resource': resource.slug,
'language': language.code,
'percent': stats.translated_perc,
}
logger.debug(
"POST data for %s: %s" % (stats.resource.project.slug, event_info)
)
for hook in hooks:
res = post_function(hook.url,
data=event_info, allow_redirects=False, timeout=2.0)
if res.ok:
logger.debug("POST for project %s successful." % project)
else:
msg = "Error visiting webhook %s: HTTP code is %s" % (
hook, res.status_code)
logger.error(msg)
示例14: import_translation
def import_translation(self, content):
"""Parse a translation file for a resource.
Args:
content: The content to parse.
Returns:
A two element tuple(pair). The first element is the number of
strings added and the second one is the number of those upadted.
"""
handler = self._get_handler(self.resource, self.language)
if handler is None:
msg = _("Invalid i18n method used: %s")
logger.error(msg % self.resource.i18n_method)
raise FormatsBackendError(msg)
return self._import_content(handler, content, False)
示例15: file_extension_for
def file_extension_for(self, resource, language):
"""Return the filename extension that should be used
for the specific resource-language pair.
"""
resource_method = resource.i18n_method
try:
if resource_method != 'PO':
return self.extensions_for(resource_method)[0]
if language is None:
return self.extensions_for('POT')[0]
return self.extensions_for(resource_method)[0]
except IndexError, e:
msg = "No extensions for resource %s: %s"
logger.error(msg % (resource, e), exc_info=True)
raise