本文整理汇总了Python中raven.contrib.django.raven_compat.models.client.captureException函数的典型用法代码示例。如果您正苦于以下问题:Python captureException函数的具体用法?Python captureException怎么用?Python captureException使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了captureException函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wrapper
def wrapper(event, context):
tracing_id = get_tracing_id(event)
os.environ["TRACING_REQUEST_ID"] = tracing_id
if sentry:
# Provide additional metadata to sentry in case the exception
# gets trapped and reported within the function.
sentry.user_context({
"aws_log_group_name": getattr(context, "log_group_name"),
"aws_log_stream_name": getattr(context, "log_stream_name"),
"aws_function_name": getattr(context, "function_name"),
"tracing_id": tracing_id
})
try:
measurement = "%s_duration_ms" % (func.__name__)
with influx_timer(measurement, timestamp=now()):
return func(event, context)
except Exception as e:
logger.exception("Got an exception: %r", e)
if sentry:
logger.info("Inside sentry capture block.")
sentry.captureException()
else:
logger.info("Sentry is not available.")
raise
finally:
from django.db import connection
connection.close()
示例2: handle_notification
def handle_notification(request):
""" Handle bounced emails via an SNS webhook. """
try:
notification = json.loads(request.body)
except ValueError, e:
client.captureException()
return HttpResponseBadRequest()
示例3: create_tree
def create_tree(self, father, tree):
if isinstance(tree, dict):
for key, value in tree.items():
cat = Category.objects.create(
name=key,
slug="",
parent=father
)
self.create_tree(cat, value)
if isinstance(tree, str):
try:
course = Course.objects.get(slug=tree)
except Course.DoesNotExist:
if self.LOCAL_CACHE:
name = self.LOCAL_CACHE.get(tree, "Unknown course in cache")
else:
try:
ulb_course = ULBCourse.get_from_slug(tree, self.YEAR)
name = ulb_course.name
except Exception:
print("Slug %s failed" % tree)
client.captureException()
name = "Unknown course in cache"
course = Course.objects.create(name=name, slug=tree)
course.categories.add(father)
if isinstance(tree, list):
for subtree in tree:
self.create_tree(father, subtree)
示例4: get_context_data
def get_context_data(self, **kwargs):
ctx = super(BlogPostsMixin, self).get_context_data(**kwargs)
blog = BlogPost.objects.all()
if self.blog_slugs:
if isinstance(self.blog_slugs, basestring):
blog_slugs = [self.blog_slugs]
else:
blog_slugs = self.blog_slugs
blog = blog.filter_by_blogs(*blog_slugs)
ctx['blog_slugs'] = blog_slugs
if self.blog_tags:
blog = blog.filter_by_tags(*self.blog_tags)
ctx['blog_tags'] = self.blog_tags
if self.blog_posts_limit:
blog = blog[:self.blog_posts_limit]
try:
# run the query here so that we can catch exceptions
# and render the page without blog posts
ctx[self.blog_posts_template_variable] = list(blog)
except Exception:
sentry_client.captureException()
ctx[self.blog_posts_template_variable] = []
return ctx
示例5: write
def write(self, proteinbox=None, summary=None):
'''
Writes the wikitext representation of the protein box to MediaWiki.
Returns (result, None) if successful, or (None, Error) if not.
Arguments:
- `proteinbox`: an updated proteinbox to write
'''
page = self.get_page()
if not self.bots_allowed():
logger.warn('Bots Blocked', exc_info=True, extra={'page': page, 'bot': self})
try:
if proteinbox:
result = page.save(str(proteinbox), summary, minor=True)
self.text = page.edit()
else:
result = page.save(self.text, summary, minor=True)
self.force_update = False
self.save()
except MwClientError:
client.captureException()
示例6: fetch_flows
def fetch_flows(org, backend=None):
from ureport.polls.models import CACHE_ORG_FLOWS_KEY, UREPORT_ASYNC_FETCHED_DATA_CACHE_TIME
start = time.time()
logger.info("Fetching flows for %s" % org.name)
if backend:
backends = [backend]
else:
backends = org.backends.filter(is_active=True)
this_time = datetime.now()
org_flows = dict(time=datetime_to_ms(this_time), results=dict())
for backend_obj in backends:
backend = org.get_backend(backend_slug=backend_obj.slug)
try:
all_flows = backend.fetch_flows(org)
org_flows["results"] = all_flows
cache_key = CACHE_ORG_FLOWS_KEY % (org.pk, backend_obj.slug)
cache.set(cache_key, org_flows, UREPORT_ASYNC_FETCHED_DATA_CACHE_TIME)
except Exception:
client.captureException()
import traceback
traceback.print_exc()
logger.info("Fetch %s flows took %ss" % (org.name, time.time() - start))
if len(backends):
return org_flows.get("results", dict())
示例7: retriveVtk
def retriveVtk(request):
if request.user.is_authenticated():
path = request.POST.get('path','')
if not path:
path = '/'
try:
webdav = easywebdav.connect(settings.LOBCDER_HOST, username='user',
password=request.ticket, protocol='https'
)
fileName = path.split('/')[-1]
fileToDownload = os.path.join(settings.LOBCDER_DOWNLOAD_DIR, fileName)
downloadChunks = webdav.downloadChunks(settings.LOBCDER_ROOT + path)
#remove file if exists
if os.path.exists(fileToDownload) and os.stat(fileToDownload)[6] != int(downloadChunks.raw.headers['content-length']):
os.remove(fileToDownload)
if not os.path.exists(fileToDownload):
webdav.download(settings.LOBCDER_ROOT+ path, fileToDownload)
content = json.dumps({'path': fileName}, sort_keys=False)
response = HttpResponse(content=content,
content_type='application/json')
return response
except Exception, e:
client.captureException()
response = HttpResponse(status=500)
response._is_string = True
return response
示例8: _action_loop
def _action_loop(self, model_name, timeout=5):
model_queue = self._model_queues[model_name]
try:
while not self.should_stop:
msgs = []
while len(msgs) < self.chunk_size:
try:
# If we have any messages queued up, push them through ASAP
msgs.append(model_queue.get(timeout=.1 if msgs else timeout))
except queue.Empty:
break
if not msgs:
logger.debug('%r: Recieved no messages to queue up', self)
continue
start = time.time()
logger.debug('%r: Preparing %d %ss to be indexed', self, len(msgs), model_name)
for msg, action in zip(msgs, ElasticsearchActionGenerator([self.index], msgs)):
# Keep blocking on put() until there's space in the queue or it's time to stop
while not self.should_stop:
try:
self._queue.put((msg, action), timeout=timeout)
break
except queue.Full:
continue
logger.info('%r: Prepared %d %ss to be indexed in %.02fs', self, len(msgs), model_name, time.time() - start)
except Exception as e:
client.captureException()
logger.exception('%r: _action_loop(%s) encountered an unexpected error', self, model_name)
self.stop()
示例9: process_response
def process_response(self, request, response):
try:
if isinstance(response,HttpResponsePermanentRedirect):
return response
subdomain = request.META['HTTP_HOST'].split(settings.SESSION_COOKIE_DOMAIN)[0]
if subdomain not in ['portal','devel'] and request.META['HTTP_HOST'] not in settings.BASE_URL: # we are in a institutional portal
institutionportal = InstitutionPortal.objects.get(subdomain=subdomain)
request.session['institutionportal'] = institutionportal
if all(x not in request.path for x in ['login', 'done', 'scs_auth', 'media', 'static', 'api']) and request.user not in institutionportal.institution.user_set.all():
if request.user.is_anonymous() and request.path not in ['/','']:
request.session['errormessage'] = "Please login to access to the requested resource"
if request.path not in ['/','']:
return render_to_response("scs/login.html", {}, RequestContext(request))
else:
if request.path not in ['/','']:
request.session['errormessage'] = "You can't access if you are not memeber of the %s institution group" %institutionportal.institution.name
return render_to_response("scs/403.html", {}, RequestContext(request))
else:
if request.session.get('institutionportal', None):
del(request.session['institutionportal'])
return response
except Exception, e:
print e
print request.META['HTTP_HOST']
from raven.contrib.django.raven_compat.models import client
client.captureException()
if request.session.get('institutionportal', None):
del(request.session['institutionportal'])
return HttpResponsePermanentRedirect(settings.BASE_URL)
示例10: authenticate
def authenticate( self, username = None, password= None, *args, **kwargs):
"""
Biomedtown backend authenticate method.
It delivery Authenticate request to biomedtown mod_auth_tkt service.
Arguments:
username (string) : Username.\n
password (string) : Password.\n
Return:
User (User instance) : Django User instance.\n
tkt64 (string) : return new ticket generation.\n
"""
if username is None or password is None:
return None
try:
service_response = self.service.rpc_login(username, password)
if service_response is not False:
user, tkt64 =self.userTicket(service_response)
if user is None:
return
return user, tkt64
return None
except Exception, e:
from raven.contrib.django.raven_compat.models import client
client.captureException()
return None
示例11: get_image
def get_image(image, size_name=None, template_name="image.html", retina=False, **kwargs):
""" Templatetag to get the HTML for an image from a cropduster image object """
if image:
if CROPDUSTER_CROP_ONLOAD:
# If set, will check for thumbnail existence
# if not there, will create the thumb based on predefiend crop/size settings
thumb_path = image.thumbnail_path(size_name)
if not exists(thumb_path) and exists(image.image.path):
try:
size = image.size_set.size_set.get(slug=size_name)
except Size.DoesNotExist:
return ""
try:
image.create_thumbnail(size, force_crop=True)
except:
raven_client.captureException(exc_info=sys.exc_info())
return ""
if retina:
image_url = image.retina_thumbnail_url(size_name)
else:
image_url = image.thumbnail_url(size_name)
if not image_url:
return ""
try:
image_size = IMAGE_SIZE_MAP[(image.size_set_id, size_name)]
except KeyError:
return ""
# Set all the args that get passed to the template
kwargs["image_url"] = image_url
if hasattr(image_size, "auto_size") and image_size.auto_size != AUTO_SIZE:
kwargs["width"] = image_size.width if hasattr(image_size, "width") else ""
kwargs["height"] = image_size.height if hasattr(image_size, "height") else ""
if CROPDUSTER_PLACEHOLDER_MODE:
kwargs["image_url"] = "http://placehold.it/%sx%s" % (kwargs["width"], kwargs["height"])
kwargs["size_name"] = size_name
kwargs["attribution"] = image.attribution
if hasattr(image, "caption"): kwargs["alt"] = image.caption
if "title" not in kwargs: kwargs["title"] = kwargs["alt"]
tmpl = get_template("templatetags/" + template_name)
context = template.Context(kwargs)
return tmpl.render(context)
else:
return ""
示例12: delete
def delete(self, ticket, *args, **kwargs):
try:
WorkflowManager.deleteExecution(self.id, ticket)
except Exception, e:
from raven.contrib.django.raven_compat.models import client
client.captureException()
pass
示例13: get_instagram_photos
def get_instagram_photos(limit=6):
recent_media = []
cached_data = cache.get("instagram_photos")
if cached_data is not None:
return cached_data
try:
url = (
"https://api.instagram.com/v1/users/self/media/recent/?access_token=%s"
% settings.INSTAGRAM_ACCESS_TOKEN
)
response = requests.get(url)
if response.status_code == 200:
data = json.loads(response.content.decode())
for item in data["data"]:
recent_media.append(
{
"link": item["link"],
"image": item["images"]["thumbnail"]["url"],
"name": item["caption"]["text"].split("\n")[0],
}
)
cache.set("instagram_photos", recent_media[:limit], 60 * 60 * 24)
except Exception as e:
client.captureException()
logger.error(e)
return recent_media[:limit]
示例14: statusMessage
def statusMessage(request):
"""
:type request: django.core.handlers.wsgi.WSGIRequest
:return:
"""
try:
if request.path == u'/done/':
return {}
if request.session.get('statusmessage', False):
message = request.session['statusmessage']
del request.session['statusmessage']
return {
'statusmessage': message,
}
if request.session.get('welcome', False):
message = request.session['welcome']
del request.session['welcome']
return {
'welcome': message,
}
if request.session.get('errormessage', False):
message = request.session['errormessage']
del request.session['errormessage']
return {
'errormessage': message,
}
except Exception, e:
client.captureException()
pass
示例15: _index_loop
def _index_loop(self):
try:
while not self.should_stop:
msgs = []
actions = self._actions(250, msgs)
stream = helpers.streaming_bulk(
self.es_client,
actions,
max_chunk_bytes=self.MAX_CHUNK_BYTES,
raise_on_error=False,
)
start = time.time()
for (ok, resp), msg in zip(stream, msgs):
if not ok and not (resp.get('delete') and resp['delete']['status'] == 404):
raise ValueError(ok, resp, msg)
assert len(resp.values()) == 1
_id = list(resp.values())[0]['_id']
assert msg.payload['ids'] == [util.IDObfuscator.decode_id(_id)], '{} {}'.format(msg.payload, util.IDObfuscator.decode_id(_id))
msg.ack()
if len(msgs):
logger.info('%r: Indexed %d documents in %.02fs', self, len(msgs), time.time() - start)
else:
logger.debug('%r: Recieved no messages for %.02fs', self, time.time() - start)
except Exception as e:
client.captureException()
logger.exception('%r: _index_loop encountered an unexpected error', self)
self.stop()