Пример #1
0
    def obj_create(self, bundle, request=None, **kwargs):
        """Custom create method to override the default post"""

        try:
            params = bundle.data
            # sanity check on the input parameters
            if 'encrypted_string' in params:
                del params['encrypted_string']
            if 'unencrypted' not in params:
                return HttpApplicationError(
                    "API creation of SecureString requires \'unencrypted\' parameter"
                )
            if 'name' not in params:
                return HttpApplicationError(
                    "API creation of SecureString requires \'name\' parameter")

            # create and save the new object
            try:
                secured = SecureString.objects.get(name=params['name'])
                secured.encrypt(params['unencrypted'])
                secured.save()
            except SecureString.DoesNotExist:
                secured = SecureString.create(params['unencrypted'],
                                              params['name'])
                secured.save()

            return bundle
        except Exception as exc:
            logger.debug(str(exc))
            return HttpApplicationError("Error creating secure string: " +
                                        str(exc))
Пример #2
0
    def process_response(self, request, response):
        # clusters - a list with varnish clusters to refresh
        clusters = VclRefreshState.get_refresh(request.id)
        if 'error_message' in request.session:
            del request.session['error_message']

        if len(clusters) > 0:
            start = time.time()
            try:
                result = load_vcl_task.delay(
                    timezone.now(), [cluster.id for cluster in clusters])

                if 'tastypie' in str(type(response)):
                    if 'respond-async' in request.META.get('HTTP_PREFER', ''):
                        response.status_code = 202
                else:
                    result.get()

                    if isinstance(result.result, Exception):
                        raise result.result
            except Exception as e:
                logging.info("Error while reloading cluster: %s (%s)" %
                             (e, type(response)))
                if 'tastypie' in str(type(response)):
                    return HttpApplicationError(
                        "%s: %s" % (e.__class__.__name__, str(e)[:400]))
                request.session['error_message'] = "%s: %s" % (
                    e.__class__.__name__, str(e))

            logging.info("cluster reload time: %f" % (time.time() - start))
        return response
Пример #3
0
 def __init__(self, response=None, *args, **kwargs):
     # If there is not response, we assume is a 500 error
     if not response:
         self.response = HttpApplicationError()
     if not isinstance(response, HttpResponse):
         raise ValueError(
             "{0} is not a valid HttpResponse".format(response))
     self.response = response
Пример #4
0
def raise_app_error(message):
    """
    Raises Http500 error with message.

    :param message: Error message
    :return: None
    """
    raise ImmediateHttpResponse(HttpApplicationError(message))
Пример #5
0
    def get_detail(self, request, **kwargs):
        """
            Called by the request dispatcher in case somebody tries to GET a job resource.
            For the frontend, deliver the current job status if pending, or the result.
        """
        basic_bundle = self.build_bundle(request=request)
        try:
            job = self.cached_obj_get(
                bundle=basic_bundle,
                **self.remove_api_resource_names(kwargs))
        except ObjectDoesNotExist:
            return HttpNotFound()
        except MultipleObjectsReturned:
            return HttpMultipleChoices(
                "More than one resource is found at this URI.")

        if job.done():
            if job.exit_code == 0:
                response = {}
                # We deliver the columns layout for the result tables + all
                # global issues
                relative_url = reverse(
                    'results',
                    kwargs={
                        'api_name': 'front',
                        'pk': job.graph.pk,
                        'secret': job.secret})
                # This is a quick fix for dealing with reverse() begind an SSL proxy
                # Normally, Django should consider the X-FORWARDED header inside the reverse()
                # implementation and figure out by itself what the correct base is
                results_url = settings.SERVER + relative_url
                if not job.requires_download:
                    response['columns'] = [
                        {'mData': key, 'sTitle': title} for key, title in job.result_titles]
                    response['axis_titles'] = job.axis_titles()
                    response['static_info'] = job.static_info()
                try:
                    response['issues'] = Result.objects.get(
                        job=job,
                        kind=Result.GRAPH_ISSUES).issues
                except Exception:
                    # no global issues recorded, that's fine
                    pass
                response = HttpResponse(json.dumps(response))
                response["Location"] = results_url
                return response
            else:
                logger.debug("Job is done, but with non-zero exit code.")
                mail_managers(
                    'Job %s for graph %u ended with non-zero exit code %u.' % (
                        job.pk,
                        job.graph.pk,
                        job.exit_code),
                    job.graph.to_xml())
                return HttpApplicationError()
        else:
            # Job is pending, tell this by HTTP return code
            return HttpAccepted()
Пример #6
0
 def obj_get_list(self, **kwargs):
     try:
         return super(RawModelResource, self).obj_get_list(**kwargs)
     except (NotFound, ObjectDoesNotExist):
         raise ImmediateHttpResponse(HttpNotFound(settings.HTTP_NOT_FOUND))
     except ImmediateHttpResponse:
         raise
     except Exception:
         raise ImmediateHttpResponse(
             HttpApplicationError(settings.HTTP_APPLICATION_ERROR))
Пример #7
0
 def serialize(self, bundle, format='application/json', options={}):
     try:
         return super(MySerializer, self).serialize(bundle, format, options)
     except (ImproperlyConfigured, UnsupportedFormat):
         raise ImmediateHttpResponse(
             HttpNotImplemented(settings.HTTP_NOT_IMPLEMENTED_ERROR))
     except ImmediateHttpResponse:
         raise
     except Exception:
         raise ImmediateHttpResponse(
             HttpApplicationError(settings.HTTP_APPLICATION_ERROR))
Пример #8
0
    def process_response(self, request, response):
        # clusters - a list with varnish clusters to refresh
        clusters = VclRefreshState.get_refresh(request.id)
        if 'error_message' in request.session:
            del request.session['error_message']

        if len(clusters) > 0:
            start = time.perf_counter()
            try:
                result = load_vcl_task.delay(
                    timezone.now(), [cluster.id for cluster in clusters])

                if 'tastypie' in str(type(
                        response)) and 'respond-async' in request.META.get(
                            'HTTP_PREFER', ''):
                    response.status_code = 202
                    response['Location'] = '/api/v0.1/task/{}/'.format(
                        result.id)
                else:
                    if settings.ENABLE_UWSGI_SWITCH_CONTEXT:
                        try:
                            import uwsgi
                            while not result.ready():
                                uwsgi.async_sleep(1)
                                uwsgi.suspend()
                        except:
                            pass

                    result.get()

                    if isinstance(result.result, Exception):
                        raise result.result
            except SoftTimeLimitExceeded:
                logging.error(
                    "Time for finish the task has been reached: The task with id {} will be killed."
                    .format(result.id))
            except Exception as e:
                logging.info("Error while reloading cluster: %s (%s)" %
                             (e, type(response)))
                if 'tastypie' in str(type(response)):
                    return HttpApplicationError(
                        "%s: %s" % (e.__class__.__name__, str(e)[:400]))
                request.session['error_message'] = "%s: %s" % (
                    e.__class__.__name__, unescape_exception(e))

            logging.info("cluster reload time: %f" %
                         (time.perf_counter() - start))
        return response
Пример #9
0
    def process_response(self, request, response):
        # clusters - a list with varnish clusters to refresh
        clusters = VclRefreshState.get_refresh(request.id)
        if 'error_message' in request.session:
            del request.session['error_message']

        if len(clusters) > 0:
            start = time.time()
            try:
                VarnishCluster().load_vcl(datetime.datetime.now().isoformat(), clusters)
            except Exception as e:
                logging.info("Error while reloading cluster: %s (%s)" % (e, type(response)))
                if 'tastypie' in str(type(response)):
                    return HttpApplicationError("%s: %s" % (e.__class__.__name__, str(e)[:400]))
                request.session['error_message'] = "%s: %s" % (e.__class__.__name__, str(e)[:400])

            logging.info("cluster reload time: %f" % (time.time() - start))
        return response
Пример #10
0
 def server_error(cls, msg):
     msg_json = '{"status": "error", "message": "%s" }' % msg
     return HttpApplicationError(msg_json, content_type='application/json')
Пример #11
0
 def response(self):
     return HttpApplicationError(
         json.dumps(self._response),
         content_type='application/json')