Esempio n. 1
0
    def obj_update(self, bundle, skip_errors=False, **kwargs):
        """
        Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned
        as acceptable exceptions which get transformed into a CREATE operation.
        We don't want such a behavior. So we catch does exceptions and throw an BadRequest message
        """
        from tastypie.serializers import Serializer

        try:
            serdes = Serializer()
            deserialized = None
            try:
                deserialized = serdes.deserialize(
                    bundle.request.raw_post_data,
                    format=bundle.request.META.get('CONTENT_TYPE',
                                                   'application/json'))
            except Exception:
                deserialized = None
            del serdes

            if deserialized is None:
                return ImmediateHttpResponse(response=http.HttpBadRequest())

            if 'unregister_c2dm' in deserialized and deserialized[
                    'unregister_c2dm'] == True:
                bundle.data['c2dm_id'] = None

            updated_bundle = super(UserResource,
                                   self).obj_update(bundle,
                                                    skip_errors=skip_errors,
                                                    **kwargs)
            return updated_bundle
        except (NotFound, MultipleObjectsReturned):
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
Esempio n. 2
0
    def wrap_view(self, view):
        @csrf_exempt
        def wrapper(request, *args, **kwargs):
            try:
                callback = view
                if isinstance(view, basestring):
                    callback = getattr(self, view)
                response = callback(request, *args, **kwargs)

                if request.is_ajax():
                    # IE excessively caches XMLHttpRequests, so we're disabling
                    # the browser cache here.
                    # See http://www.enhanceie.com/ie/bugs.asp for details.
                    patch_cache_control(response, no_cache=True)

                return response
            except (BadRequest, fields.ApiFieldError), e:
                return http.HttpBadRequest(e.args[0])
            except ValidationError, e:
                if e.messages:
                    dct = dict(errors=e.messages)
                    format = self.determine_format(request)
                    return http.HttpBadRequest(self.serialize(
                        request, dct, format),
                                               mimetype=format)
                return http.HttpBadRequest()
Esempio n. 3
0
    def obj_update(self, bundle, **kwargs):
        draw_id = kwargs['pk']
        try:
            draw = self._client.retrieve_draw(draw_id)
        except mongodb.MongoDriver.NotFoundError:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest("Draw not found"))
        if not draw.check_write_access(bundle.request.user):
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpUnauthorized("Only the owner can update"))

        for name, value in bundle.data.items():
            if not hasattr(draw, name):
                continue
            elif name in self.FROZEN_ATTRIBUTES + self.FORBIDDEN_ATTRIBUTES:
                if getattr(draw, name) != value:
                    raise exceptions.ImmediateHttpResponse(
                        response=http.HttpBadRequest("{0} is forbidden".format(
                            name)))
            else:
                setattr(draw, name, value)

        try:
            draw.validate()
        except bom.InvalidDraw as e:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest(e.serialize()))

        draw.add_audit("DRAW_PARAMETERS")
        self._client.save_draw(draw)
        bundle.obj = draw
        return bundle
Esempio n. 4
0
        def post(self, request, provider=None, params=None, **kwargs):
            from requests import RequestException
            from allauth.socialaccount import providers
            from allauth.socialaccount.helpers import complete_social_login
            from allauth.socialaccount.models import SocialLogin, SocialToken
            from allauth.socialaccount.providers.facebook.provider import FacebookProvider

            if provider == 'facebook':
                try:
                    app = providers.registry.by_id(
                        FacebookProvider.id).get_app(request)
                    token = SocialToken(app=app, token=params.access_token)
                    login = fb_complete_login(request, app, token)
                    login.token = token
                    login.state = SocialLogin.state_from_request(request)
                    ret = complete_social_login(request, login)
                except RequestException:
                    return http.HttpBadRequest(
                        'Error accessing FB user profile')
                else:
                    # If user does not exist
                    if login.account.user.id is None:
                        return http.HttpBadRequest('Not registered')

                    return self._construct_login_response(login.account.user)

            return http.HttpBadRequest('Invalid provider')
Esempio n. 5
0
 def obj_create(self, bundle, **kwargs):
     data = bundle.data
     LOG.info("Creating draw with data: {}".format(data))
     for attr in self.FORBIDDEN_ATTRIBUTES:
         if attr in data:
             raise exceptions.ImmediateHttpResponse(
                 response=http.HttpBadRequest("{0} is forbidden".format(
                     attr)))
     try:
         type_ = data.pop('type')
         draw = draw_factory.create_draw(type_, data)
         draw.validate()
     except KeyError:
         raise exceptions.ImmediateHttpResponse(
             response=http.HttpBadRequest("Missing draw type"))
     except draw_factory.DrawNotRegistered:
         raise exceptions.ImmediateHttpResponse(
             response=http.HttpBadRequest("Invalid draw type"))
     except bom.InvalidDraw as e:
         raise exceptions.ImmediateHttpResponse(
             response=http.HttpBadRequest(e.serialize()))
     draw.owner = bundle.request.user.pk
     if not draw.is_shared:
         draw.toss()
     self._client.save_draw(draw)
     bundle.obj = draw
     return bundle
Esempio n. 6
0
    def try_draw(self, request, **_):
        self.method_check(request, allowed=['post'])
        self.throttle_check(request)
        try:
            data = json.loads(request.body)
        except TypeError:
            data = json.loads(request.body.decode('utf-8'))

        try:
            type_ = data.pop('type')
            draw = draw_factory.create_draw(type_, data)
            draw.validate()
        except KeyError:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest("Missing draw type"))
        except draw_factory.DrawNotRegistered:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest("Invalid draw type"))
        except bom.InvalidDraw as e:
            raise exceptions.ImmediateHttpResponse(
                response=http.HttpBadRequest(e.serialize()))
        self._client.save_draw(draw)
        result = draw.toss()
        self.log_throttled_access(request)
        return self.create_response(request, result)
Esempio n. 7
0
    def obj_create(self, bundle, request=None, **kwargs):
        """Oversee the creation of product and its required productversion.
        Probably not strictly RESTful.
        """

        pv_required_msg = str("The 'productversions' key must exist, " +
                              "must be a list, and the list must contain " +
                              "at least one entry.")
        # pull the productversions off, they don't exist yet
        try:
            productversions = bundle.data.pop('productversions')
            if not isinstance(productversions, list):
                raise ImmediateHttpResponse(
                    response=http.HttpBadRequest(pv_required_msg))
            if not len(productversions):
                raise ImmediateHttpResponse(
                    response=http.HttpBadRequest(pv_required_msg))

            bundle.data["productversions"] = []
        except KeyError:
            raise ImmediateHttpResponse(
                response=http.HttpBadRequest(pv_required_msg))

        # create the product
        updated_bundle = super(ProductResource,
                               self).obj_create(bundle=bundle,
                                                request=request,
                                                **kwargs)

        # create the productversions
        for pv in productversions:
            ProductVersion.objects.get_or_create(product=updated_bundle.obj,
                                                 **pv)

        return updated_bundle
Esempio n. 8
0
def get_virtual_flag_from_url(request):
    """
    import inspect
    
    print 'caller 1:', inspect.stack()[1]
    print 'caller 2:', inspect.stack()[2]
    print 'caller 3:', inspect.stack()[3]
    print 'caller 4:', inspect.stack()[4]
    print 'caller 5:', inspect.stack()[5]
    print 'caller 6:', inspect.stack()[6]
    print 'caller 7:', inspect.stack()[7]
    print 'caller 8:', inspect.stack()[8]
    print 'caller 9:', inspect.stack()[9]
    print 'caller 10:', inspect.stack()[10]
    print 'caller 11:', inspect.stack()[11]
    print 'caller 12:', inspect.stack()[12]
    """
    
    ## retrieve the value of the virtual flag
    virtual = str(request.GET.get('virtual'))    
    if virtual is None:
        raise ImmediateHttpResponse(response = http.HttpBadRequest(content='No "virtual" flag in request url'))
    
    try:
        virtual = str2bool(virtual)
    except ValueError:
        raise ImmediateHttpResponse(response = http.HttpBadRequest(content='"virtual" flag could not be parsed to a boolean'))
    
    return virtual
Esempio n. 9
0
    def get_search(self, request, **kwargs):
        """
        Execute a search query to elasticsearch

        Request parameters are:
        - `q`: string query
        - `types`: set of document types (`contact`, `organization`, `invoice`, ...)

        A minimum of 2 chars are required for the query to be processed (wildcards excluded).
        """
        import re
        import pyes
        from pyes.query import Search, StringQuery

        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        try:
            # Tenant (slug) must be present
            tenant = request.tenant.slug
            # By default, search is made among all types, can be overriden passing a types argument
            doc_types = request.GET.getlist('types')
            # The 'q' parameter represents the query
            query = request.GET.get('q')
            # The query must be a string and composed by at least 2 chars (ES wildcards excluded)
            assert (isinstance(query, basestring)
                    and len(re.sub('[?*]', '', query)) >= 2)
        except:
            return http.HttpBadRequest()

        try:
            conn = pyes.ES(settings.ES_SERVERS, basic_auth=settings.ES_AUTH)
            q = Search(StringQuery(query))
            resultset = conn.search(
                q,
                indices=tenant,
                doc_types=u",".join(doc_types) if doc_types else None)
            searched_items = []
            for res in resultset:
                res.update({
                    'id': res._meta['id'],
                    'resource_type': res._meta['type'],
                    'score': res._meta['score']
                })
                searched_items.append(res)
        except:
            return http.HttpBadRequest()

        self.log_throttled_access(request)

        paginator = self._meta.paginator_class(
            request.GET,
            searched_items,
            resource_uri=self.get_resource_uri(),
            limit=self._meta.limit)
        to_be_serialized = paginator.page()
        return self.create_response(request,
                                    to_be_serialized,
                                    response_class=http.HttpResponse)
Esempio n. 10
0
    def obj_update(self, bundle, request=None, **kwargs):
        """Lots of rules for modifying product for tags."""
        tag = self.get_via_uri(bundle.request.path, request)
        caseversions = tag.caseversions.all()
        err_msg = str(
            "Tag's Product may not be changed unless " +
            "the tag is not in use, the product is being " +
            "set to None, or the product matches the existing cases.")

        # if we're even thinking about changing the product
        if 'product' in bundle.data.keys():
            logger.debug('thinking about product')
            # if tag is in use
            if caseversions:
                logger.debug('tag in use')
                desired_product = bundle.data['product']
                products = set(
                    [cv.productversion.product for cv in caseversions])
                # if it is *changing* the product
                if desired_product != tag.product:
                    logger.debug('changing product')
                    # if changing from global to product-specific
                    if not desired_product == None:
                        logger.debug(
                            'changing from global to product-specific')
                        # if existing caseversions represent more than one
                        # product
                        desired_product_id = self._id_from_uri(desired_product)
                        if len(products) > 1:
                            logger.exception(err_msg)
                            raise ImmediateHttpResponse(
                                response=http.HttpBadRequest(err_msg))
                        # or if cases' product is not requested product
                        elif str(list(products)[0].id) != desired_product_id:
                            logger.exception(err_msg)
                            raise ImmediateHttpResponse(
                                response=http.HttpBadRequest(err_msg))
        # code from here through the last else is optional,
        # but nice if tracking down coverage problems
        # requested product matches the single product used by
        # all of the caseversions
                        else:
                            logger.debug(
                                "product matches caseversions' product")
                    else:  # changing from product-specific to global
                        logger.debug(
                            "changing from product-specific to global")
                else:
                    logger.debug("not changing product")
            else:
                logger.debug("tag not in use")
        else:
            logger.debug("not thinking about product")

        return super(TagResource, self).obj_update(bundle=bundle,
                                                   request=request,
                                                   **kwargs)
Esempio n. 11
0
    def obj_update(self, bundle, skip_errors=False, **kwargs):
        """
        Could be an intentional action that the default obj_update treats DoesNotExist and MultipleObjectReturned
        as acceptable exceptions which get transformed into a CREATE operation.
        We don't want such a behavior. So we catch does exceptions and throw an BadRequest message
        """
        from tastypie.serializers import Serializer
        from models import ConferenceRole

        try:
            serdes = Serializer()
            deserialized = None
            try:
                deserialized = serdes.deserialize(
                    bundle.request.body,
                    format=bundle.request.META.get('CONTENT_TYPE',
                                                   'application/json'))
            except Exception:
                deserialized = None

            if deserialized is None:
                return ImmediateHttpResponse(
                    response=http.HttpBadRequest('Empty update data'))
            ''' Check for the existence of the role parameter in the deserialized data '''
            if not 'role' in deserialized:
                return ImmediateHttpResponse(response=http.HttpBadRequest(
                    'Missing conference role data'))

            if not deserialized['role'] in ConferenceRole.ROLE_TYPES:
                return ImmediateHttpResponse(response=http.HttpBadRequest(
                    'Conference role data not in accepted list'))

            updated_bundle = super(ConferenceRoleResource,
                                   self).obj_update(bundle,
                                                    skip_errors=skip_errors,
                                                    **kwargs)

            # create ConferenceRole entry
            user_profile = bundle.request.user.get_profile()
            role = deserialized['role']

            confrole = ConferenceRole(conference=updated_bundle.obj,
                                      user_profile=user_profile,
                                      role=role)
            confrole.save()

            return updated_bundle

        except (NotFound, MultipleObjectsReturned), ex:
            raise ImmediateHttpResponse(response=http.HttpBadRequest())
Esempio n. 12
0
def get_virtual_flag_from_url(request):

    ## retrieve the value of the virtual flag
    virtual = str(request.GET.get('virtual'))
    if virtual is None:
        raise ImmediateHttpResponse(response=http.HttpBadRequest(
            content='No "virtual" flag in request url'))

    try:
        virtual = str2bool(virtual)
    except ValueError:
        raise ImmediateHttpResponse(response=http.HttpBadRequest(
            content='"virtual" flag could not be parsed to a boolean'))

    return virtual
Esempio n. 13
0
        def wrapper(request, *args, **kwargs):
            try:
                desired_format = self.determine_format(request)
                if method == "POST" or method == "PUT":
                    if not raw:
                        data = self.deserialize(request, request.raw_post_data,
                                                desired_format)
                    else:
                        data = request.raw_post_data
                elif method == "GET":
                    data = request.GET
                response_data = {}
                if hasattr(form_class, "static_get_form_kwargs"):
                    kwargs = form_class.static_get_form_kwargs(
                        request, data, *args, **kwargs)
                    form = form_class(**kwargs)
                else:
                    form = form_class(data=data)

                if not form.is_valid():
                    context = RequestContext(request, {})
                    context['form'] = form
                    errors = dict([(k, form.error_class.as_text(v))
                                   for k, v in form.errors.items()])
                    response_data['errors'] = errors

                    serialized = self.serialize(request, response_data,
                                                desired_format)
                    return http.HttpBadRequest(
                        serialized,
                        content_type=build_content_type(desired_format))

                else:
                    if hasattr(form, "save"):
                        obj = form.save()
                        if obj:
                            if hasattr(form, "bundle_obj"):
                                response_data = form.bundle_obj(obj, request)
                            else:
                                response_data = obj

                return self.create_response(request, response_data)
            except JSONDecodeError, e:
                data = dict(errors=e.message)
                serialized = self.serialize(request, data, desired_format)
                return http.HttpBadRequest(
                    serialized,
                    content_type=build_content_type(desired_format))
    def obj_update(self, bundle, request=None, **kwargs):
        bundle.obj = self.cached_obj_get(
            request=request, **self.remove_api_resource_names(kwargs))

        if 'alias' in bundle.data:
            # FIXME: sanitize input for alias (it gets echoed back as markup)
            alias = bundle.data['alias']
            record = bundle.obj
            if alias == "":
                record.alias = None
            else:
                record.alias = alias
            record.save()

        input_attrs = bundle.data
        attrs = {}
        resource_class = record.resource_class.get_class()
        for name, property in resource_class.get_all_attribute_properties():
            if name in bundle.data:
                attrs[name] = property.encrypt(property.cast(
                    input_attrs[name]))

        if len(attrs):
            # NB this operation is done inside the storage daemon, because it is
            # necessary to tear down any running session (e.g. consider modifying the IP
            # address of a controller)
            ScanDaemonRpcInterface().modify_resource(record.id, attrs)

        # Require that something was set
        if not 'alias' in bundle.data or len(attrs):
            raise ImmediateHttpResponse(http.HttpBadRequest())

        return bundle
Esempio n. 15
0
 def sword_collection(self, request, **kwargs):
     location = get_object_or_None(Location, uuid=kwargs['uuid'])
     if location and (location.purpose != Location.SWORD_DEPOSIT
                      or location.space.access_protocol != Space.FEDORA):
         return http.HttpBadRequest('This is not a SWORD server space.')
     self.log_throttled_access(request)
     return sword_views.collection(request, location or kwargs['uuid'])
Esempio n. 16
0
    def activate(self, request, **kwargs):
        try:
            self.validate_request(request.GET, ['token'])
            token = request.GET.get("token", None)
            # Make sure the key we're trying conforms to the pattern of a
            # SHA1 hash; if it doesn't, no point trying to look it up in
            # the database.
            if SHA1_RE.search(token):
                profile = RegistrationProfile.objects.get(activation_key=token)
                if not profile.activation_key_expired():
                    user = profile.user
                    user.is_active = True
                    user.save()
                    profile.activation_key = RegistrationProfile.ACTIVATED
                    profile.save()
                    return self.create_response(request, {
                            "success": True
                        })
                else:
                    return http.HttpForbidden('Your activation token is no longer active or valid')
            else:
                return http.HttpForbidden('Your activation token  is no longer active or valid')

        except RegistrationProfile.DoesNotExist:
            return http.HttpNotFound('Your activation token is no longer active or valid')

        except MalformedRequestError as e:
            return http.HttpBadRequest("%s as request GET parameters" % e)
Esempio n. 17
0
 def raise_bad_request(self, bundle, errors):
     desired_format = self.determine_format(bundle.request)
     serialized = self.serialize(bundle.request, errors, desired_format)
     response = http.HttpBadRequest(
         content=serialized,
         content_type=build_content_type(desired_format))
     raise ImmediateHttpResponse(response=response)
Esempio n. 18
0
 def obj_update(self, bundle, request=None, **kwargs):
     """
     Could be an intentional feature that the default obj_update treats DoesNotExist and MultipleObjectReturned
     as acceptable exceptions which get transformed into a CREATE operation.
     We don't want such a behavior. So we catch those exceptions and throw a BadRequest message
     """
         
     try:
         updated_bundle = super(AnnotationResource, self).obj_update(bundle, request, **kwargs)
         
         ## make notification for 'order' type annotations
         if updated_bundle.data['category'] == Annotation.ORDER:
             from coresql.models import OrderFeature
             
             owner_profile = None
             if not bundle.obj.environment is None:
                 owner_profile = bundle.obj.environment.owner
                 
             if not bundle.obj.area is None:
                 owner_profile = bundle.obj.area.environment.owner
                 
             registration_id = None
             if owner_profile:
                 registration_id = owner_profile.c2dm_id
             
             collapse_key = "annotation_" + Annotation.ORDER
             
             self._make_c2dm_notification(registration_id, collapse_key, updated_bundle, 
                                          params = {'type' : OrderFeature.NEW_ORDER})
         
         return updated_bundle
     except (NotFound, MultipleObjectsReturned):
         raise ImmediateHttpResponse(response = http.HttpBadRequest())
Esempio n. 19
0
 def get_detail(self, request, **kwargs):
     ## override the list retrieval part to verify additionally that an ``user`` filter exists
     ## otherwise reject the call with a HttpMethodNotAllowed
     if 'request' in request.GET:
         return super(EnvrionmentContextResource, self).get_detail(request, **kwargs)
     else:
         raise ImmediateHttpResponse(response=http.HttpBadRequest())
Esempio n. 20
0
        def inner(self, request, **kwargs):
            """
            Handle ``{method}`` request.

            Implement ``async_{method} to add custom request, returning
            celery.result.AsyncResult. If it returns None, HttpBadRequest
            is returned from this method. If you don't implement the
            custom method, it will return HttpNotImplemented.
            """
            try:
                result = getattr(self, 'async_' + method)(
                    request, **self.remove_api_resource_names(kwargs))
                if result is None:
                    return http.HttpBadRequest()
            except NotImplementedError:
                return http.HttpNotImplemented()

            if isinstance(result, AsyncResult):
                if isinstance(result, EagerResult):
                    EAGER_RESULTS[result.id] = result
                response = http.HttpAccepted()
                response['Location'] = self._build_reverse_url(
                    'api_async_state',
                    kwargs={
                        'api_name': self._meta.api_name,
                        'resource_name': self._meta.resource_name,
                        'task_id': result.id
                    })
                return response
            else:
                return result
Esempio n. 21
0
    def create(self, request=None, **kwargs):
        """POST method of DialCallback API"""
        logger.debug('DialCallback API authentication called!')
        auth_result = self._meta.authentication.is_authenticated(request)
        if not auth_result is True:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        logger.debug('DialCallback API authorization called!')
        auth_result = self._meta.authorization.is_authorized(request, object)

        logger.debug('DialCallback API validation called!')
        errors = self._meta.validation.is_valid(request)

        if not errors:
            logger.debug('DialCallback API get called!')
            opt_aleg_uuid = request.POST.get('DialALegUUID')
            opt_dial_bleg_uuid = request.POST.get('DialBLegUUID')
            opt_dial_bleg_status = request.POST.get('DialBLegStatus')
            #We are just analyzing the hangup
            if opt_dial_bleg_status != 'hangup':
                object_list = [{'result': 'OK - Bleg status is not Hangup'}]
                logger.debug('DialCallback API : Result 200!')
                obj = CustomXmlEmitter()
                return self.create_response(request,
                                            obj.render(request, object_list))
            callrequest = Callrequest.objects.get(aleg_uuid=opt_aleg_uuid)
            data = {}
            for element in CDR_VARIABLES:
                if not request.POST.get('variable_%s' % element):
                    data[element] = None
                else:
                    data[element] = request.POST.get('variable_%s' % element)

            from_plivo = request.POST.get('From')
            to_plivo = request.POST.get('To')

            create_voipcall(obj_callrequest=callrequest,
                            plivo_request_uuid=callrequest.request_uuid,
                            data=data,
                            data_prefix='',
                            leg='b',
                            from_plivo=from_plivo,
                            to_plivo=to_plivo)
            object_list = [{'result': 'OK'}]
            logger.debug('DialCallback API : Result 200!')
            obj = CustomXmlEmitter()

            return self.create_response(request,
                                        obj.render(request, object_list))
        else:
            if len(errors):
                if request:
                    desired_format = self.determine_format(request)
                else:
                    desired_format = self._meta.default_format

                serialized = self.serialize(request, errors, desired_format)
                response = http.HttpBadRequest(content=serialized,
                                               content_type=desired_format)
                raise ImmediateHttpResponse(response=response)
Esempio n. 22
0
    def put_list(self, request, **kwargs):
        """
        based on tastypie/resources.py but modified to do what we actually want!

        Up a collection of resources with another collection.

        Calls ``delete_list`` to clear out the collection then ``obj_create``
        with the provided the data to create the new collection.

        Return ``HttpNoContent`` (204 No Content) if
        ``Meta.always_return_data = False`` (default).

        Return ``HttpAccepted`` (202 Accepted) if
        ``Meta.always_return_data = True``.
        """
        deserialized = self.deserialize(request,
                                        request.raw_post_data,
                                        format=request.META.get(
                                            'CONTENT_TYPE',
                                            'application/json'))
        deserialized = self.alter_deserialized_list_data(request, deserialized)

        if not 'objects' in deserialized:
            raise http.HttpBadRequest("Invalid data sent.")

        bundle = self.build_bundle(data=dict_strip_unicode_keys(deserialized),
                                   request=request)

        self.obj_update(bundle, **kwargs)
Esempio n. 23
0
    def non_form_errors(self, error_list):
        """
        Raises passed field errors as an immediate HttpBadRequest response.
        Similar to Marketplace.form_errors, except that it allows you to raise
        form field errors outside of form validation.

        Accepts a list of two-tuples, consisting of a field name and error
        message.

        Example usage:

        errors = []

        if 'app' in bundle.data:
            errors.append(('app', 'Cannot update the app of a rating.'))

        if 'user' in bundle.data:
            errors.append(('user', 'Cannot update the author of a rating.'))

        if errors:
            raise self.non_form_errors(errors)
        """
        errors = defaultdict(list)
        for e in error_list:
            errors[e[0]].append(e[1])
        response = http.HttpBadRequest(json.dumps({'error_message': errors}),
                                       content_type='application/json')
        return ImmediateHttpResponse(response=response)
Esempio n. 24
0
    def wrap_form(self, form_class, method="POST", raw=False, anon=False):
        """
        Creates a view for a given form class, which calls to is_valid()
        and save() when needed. You can get the form args reimplementing
        static_get_form_kwargs(request, data, *args, **kwargs) in your
        form.
        """
        @csrf_exempt
        def wrapper(request, *args, **kwargs):
            if not anon and not request.user.is_authenticated():
                    self.is_authenticated(request)
            try:
                desired_format = self.determine_format(request)
                if method == "POST" or method== "PUT":
                    if not raw:
                        data = self.deserialize(request, request.raw_post_data,
                            desired_format)
                    else:
                        data = request.raw_post_data
                elif method == "GET":
                    data = request.GET
                response_data = {}
                if hasattr(form_class, "static_get_form_kwargs"):
                    kwargs = form_class.static_get_form_kwargs(request, data, 
                        *args, **kwargs)
                    form = form_class(**kwargs)
                else:
                    form = form_class(data=data)

                if not form.is_valid():
                    context = RequestContext(request, {})
                    context['form'] = form
                    errors = dict([(k, form.error_class.as_text(v)) for k, v in form.errors.items()])
                    response_data['errors'] = errors

                    serialized = self.serialize(request, response_data, desired_format)
                    return http.HttpBadRequest(serialized,
                        content_type=build_content_type(desired_format))

                else:
                    if hasattr(form, "save"):
                        obj = form.save()
                        if obj:
                            if hasattr(form, "bundle_obj"):
                                response_data = form.bundle_obj(obj, request)
                            else:
                                response_data = obj

                return self.create_response(request, response_data)
            except JSONDecodeError, e:
                data = dict(errors=e.message)
                serialized = self.serialize(request, data, desired_format)
                return http.HttpBadRequest(serialized,
                        content_type=build_content_type(desired_format))
            except (BadRequest, fields.ApiFieldError), e:
                data = dict(errors=e.args[0])
                serialized = self.serialize(request, data, desired_format)
                return http.HttpBadRequest(serialized,
                        content_type=build_content_type(desired_format))
Esempio n. 25
0
 def error_response(self, errors, request):
     if request:
         desired_format = self.determine_format(request)
     else:
         desired_format = self._meta.default_format
     serialized = self.serialize(request, errors, desired_format)
     response = http.HttpBadRequest(content=serialized, content_type=build_content_type(desired_format))
     raise ImmediateHttpResponse(response=response)
Esempio n. 26
0
    def get_statistics(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        self.throttle_check(request)

        try:
            body = request.body
            deserialized = self.deserialize(request,
                                            body,
                                            format=request.META.get(
                                                'CONTENT_TYPE',
                                                'application/json'))
            deserialized = self.alter_deserialized_detail_data(
                request, deserialized)
        except ValueError as e:
            # Serialization errors -> relayed to API users
            return self.create_response(request,
                                        e,
                                        response_class=http.HttpBadRequest)
        except:
            # Other errors
            return http.HttpBadRequest()

        try:
            result = Statistics._get_collection().aggregate(
                deserialized.get('pipeline')).get('result')
        except (InvalidOperation, OperationFailure) as e:
            # Aggregation pipeline operation errors -> relayed to API users
            return self.create_response(request,
                                        e,
                                        response_class=http.HttpBadRequest)
        except:
            # Other errors
            return http.HttpBadRequest()

        self.log_throttled_access(request)

        paginator = self._meta.paginator_class(
            request.GET,
            result,
            resource_uri=self.get_resource_uri(),
            limit=self._meta.limit)
        to_be_serialized = paginator.page()
        return self.create_response(request,
                                    to_be_serialized,
                                    response_class=http.HttpAccepted)
Esempio n. 27
0
    def file_data(self, request, **kwargs):
        """
        Returns file metadata as a JSON array of objects.

        This maps properties of the File class to the names of the
        Elasticsearch indices' Transferfile index, allowing this to directly
        substitute for Elasticsearch when looking up metadata on specific files.

        Acceptable parameters are:
            * relative_path (searches the `name` field)
            * fileuuid (searches the `source_id` field)
            * accessionid (searches the `accessionid` field)
            * sipuuid (searches the `source_package` field)

        :returns: an array of one or more objects. See the transferfile
        index for information on the return format.
        If no results are found for the specified query, returns 404.
        If no acceptable query parameters are found, returns 400.
        """
        property_map = {
            "relative_path": "name",
            "fileuuid": "source_id",
            "accessionid": "accessionid",
            "sipuuid": "source_package"
        }
        query = {}
        for source, dest in property_map.iteritems():
            try:
                query[dest] = request.GET[source]
            except KeyError:
                pass

        if not query:
            response = {
                "success": False,
                "error": "No supported query properties found!"
            }
            return http.HttpBadRequest(content=json.dumps(response),
                                       content_type="application/json")

        files = File.objects.filter(**query)
        if not files.exists():
            return http.HttpNotFound()

        response = []
        for f in files:
            response.append({
                "accessionid": f.accessionid,
                "file_extension": os.path.splitext(f.name)[1],
                "filename": os.path.basename(f.name),
                "relative_path": f.name,
                "fileuuid": f.source_id,
                "origin": f.origin,
                "sipuuid": f.source_package
            })

        return http.HttpResponse(content=json.dumps(response),
                                 content_type="application/json")
Esempio n. 28
0
 def obj_create(self, bundle, **kwargs):
     try:
         change = IPAddressChange(**bundle.data)
     except TypeError:
         raise ImmediateHttpResponse(
             response=http.HttpBadRequest(
                 'Unexpected argument. Allowed arguments: '
                 'current_ip_address and new_ip_address'
             )
         )
     try:
         change_ip_address(**bundle.data)
     except ChangeIPAddressError as e:
         raise ImmediateHttpResponse(
             response=http.HttpBadRequest(e.message)
         )
     bundle.obj = change
     return bundle
Esempio n. 29
0
 def logout(self, request, **kwargs):
     '''
     Log out the currently authenticated user
     '''
     try:
         auth_logout(request)
         return self.create_response(request, dict(status="success"))
     except Exception, e:
         raise ImmediateHttpResponse(response=http.HttpBadRequest())
Esempio n. 30
0
def checkTargetMonth(target_month):    
    if target_month is None :
        target_month = now()
    else :    
        try:
            target_month = make_aware(datetime.strptime(target_month, '%Y-%m-%d'), now().tzinfo)
        except Exception as e:
            raise ImmediateHttpResponse(response=http.HttpBadRequest(e.message))       
    return target_month