Esempio n. 1
0
 def validate(i):
     i = int(i)
     if min_length and i < min_length:
         raise CustomException(detail='Min is {}'.format(min_length))
     if max_length and i > max_length:
         raise CustomException(detail='Max is {}'.format(max_length))
     return i
Esempio n. 2
0
    def post(self):
        """
        Login user

            username  min 5, max 50

            password  min 5, max 50


        :return:
        """
        try:
            data = LoginRegisterParser.parse_args()
            user = User.query.get(username=data['username'])
            if user is None:
                raise CustomException(detail='User does not exist.')
            else:
                if user.check_password(data['password']):
                    data = {'token': user.encode_auth_token()}
                    return responses.SuccessResponse(data).send()
                else:
                    raise CustomException(
                        detail='username or password is incorrect.')
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 3
0
 def validate(d):
     if type(d) is not dict:
         raise CustomException(detail='Must be Dictionary.')
     if keys:
         for key in keys:
             if key not in d.keys():
                 raise CustomException(detail='{} is required'.format(key))
     return d
Esempio n. 4
0
def check_perm_owner_update(request, instance):
    if hasattr(instance, 'user') and instance.user == request.user:
        return True
    elif hasattr(instance, 'user'):
        raise CustomException(detail=ugettext('No Permission to update'), code=403)
    elif request.user.is_superuser:
        return True
    else:
        raise CustomException(detail=ugettext('No Permission to update'), code=403)
Esempio n. 5
0
 def validate(s):
     if type(s) is not str:
         raise CustomException(detail='Must be string.')
     if min_length and len(s) < min_length:
         raise CustomException(detail='Min length is {}'.format(min_length))
     if max_length and len(s) > max_length:
         raise CustomException(detail='Max length is {}'.format(max_length))
     if choices:
         for item in choices:
             if s == item[0]:
                 break
         else:
             raise CustomException(detail='Choices are {}'.format(choices))
     return s
Esempio n. 6
0
    def post(self):
        """
        Register user

            username  min 5, max 50

            password  min 5, max 50


        :return:
        """
        try:
            data = LoginRegisterParser.parse_args()
            user = User.query.get(username=data['username'])
            if user is None:
                user = User(username=data['username'])
                user.set_password(data['password'])
                user.create()
                data = {'token': user.encode_auth_token()}
                return responses.SuccessResponse(data, status=201).send()
            else:
                raise CustomException(detail='A user with this data exist.')
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 7
0
    def post(self):
        """
        Create Ad

            title  min 3, max 100

            body  min 3, max 100

            category  {'id': id of category}

            media  [{'path': 'path of media'}] max 5

        :return:
        """
        try:
            data = AdParser.parse_args()
            data['category'] = Category.query.get(data['category']['id'])
            if not data['category']:
                raise CustomException(detail='Category does not exist.')
            media = data.pop('media')
            data['user'] = g.user
            ad_item = Ad(**data).create()
            if media:
                for item in media:
                    ad_item.media_set.append(Media(path=item['path']))
            ad_item.save()
            return responses.SuccessResponse(marshal(ad_item, AdSchema),
                                             status=201).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 8
0
    def put(self, id):
        """
        Update ad details by id

            title  min 3, max 100

            body  min 3, max 100

            category  {'id': id of category}

            media  [{'path': 'path of media', 'id': 'id of gallery'}] max 5  id is optional for checking previous created

        :param id:
        :return:
        """
        try:
            data = AdParser.parse_args()
            ad_item = Ad.query.get(id)
            if ad_item is None or ad_item.is_deleted:
                raise CustomException(detail='Ad does not exist.')

            ad_item.has_permission()
            ad_item.update(data)
            return responses.SuccessResponse(marshal(ad_item, AdSchema)).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 9
0
 def create(self, validated_data):
     try:
         car = CarStock.objects.select_for_update().filter(
             car__name__iexact=validated_data['name'],
             total__gt=F('total_sold')).order_by('date').first()
     except CarStock.DoesNotExist as e:
         raise CustomException(detail='There is no {} for sale.'.format(
             validated_data['name']))
     if car.total - car.total_sold < validated_data['count']:
         raise CustomException(
             detail='There is not enough car left for sale.')
     car.total_sold += validated_data['count']
     car.save()
     sale = CarSold(car_stock=car,
                    user=self.context['request'].user,
                    count=validated_data['count'])
     sale.save()
     return sale
Esempio n. 10
0
def pagination_util(request):
    arguments = parser.parse(request.GET.urlencode())
    try:
        size = int(arguments.pop('size', 20))
        index = int(arguments.pop('index', 0))
    except ValueError:
        raise CustomException(detail=ugettext(
            'Size and index query param for pagination must be integer.'),
                              code=400)
    size = index + size
    return index, size
Esempio n. 11
0
 def validate(l):
     if type(l) is not list:
         raise CustomException(detail='Must be list.')
     if max_length and len(l) > max_length:
         raise CustomException(
             detail='Max length is {} and yours is {}'.format(
                 max_length, len(l)))
     if min_length and len(l) < min_length:
         raise CustomException(
             detail='Min length is {} and yours is {}'.format(
                 min_length, len(l)))
     if keys:
         for key in keys:
             for dic in l:
                 if key not in dic.keys():
                     raise CustomException(
                         detail='{} is required'.format(key))
                 if child_max:
                     if len(dic[key]) > child_max:
                         raise CustomException(detail='{} max is {}'.format(
                             key.title(), child_max))
     return l
Esempio n. 12
0
    def get(self, id):
        """
        Get ad details by id

        :param id:
        :return:
        """
        try:
            ad_item = Ad.query.get(id)
            if ad_item is None or ad_item.is_deleted:
                raise CustomException(detail='Ad does not exist.')
            return responses.SuccessResponse(marshal(ad_item, AdSchema)).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 13
0
    def delete(self, id):
        """
        Delete ad

            Soft delete

        :param id:
        :return:
        """
        try:
            ad_item = Ad.query.get(id)
            if ad_item is None or ad_item.is_deleted:
                raise CustomException(detail='Ad does not exist.')
            ad_item.has_permission()
            ad_item.delete()
            return responses.SuccessResponse(status=204).send()
        except CustomException as e:
            return responses.ErrorResponse(message=e.detail,
                                           status=e.status_code).send()
Esempio n. 14
0
    def update(self, data):
        if data.get('category',
                    None) and self.category.id != data['category']['id']:
            category = Category.query.get(data['category']['id'])
            if category:
                self.category = category
            else:
                raise CustomException(detail='Category does not exist.')

        if data.get('title', None) and self.title != data['title']:
            self.title = data['title']

        if data.get('body', None) and self.body != data['body']:
            self.body = data['body']

        if data.get('media'):
            for media_data in data['media']:
                if media_data.get('id', None) is None:
                    self.media_set.append(Media(path=media_data['path']))
        self.save()
Esempio n. 15
0
 def has_permission(self):
     if self.user != g.user:
         raise CustomException(detail='No permission.', code=403)
Esempio n. 16
0
def check_send_email_permission(email):
    email_count = cache.get('{}_{}'.format(settings.EMAIL_SEND_COUNT, email), 0)
    if email_count >= settings.MAX_EMAIL_SEND_COUNT:
        raise CustomException(detail=ugettext('Max email send reached, try later.'), code=403)