Exemplo n.º 1
0
 def test_handle_exception(self):
     exc = APIException('There was a problem!')
     exc.status_code = 400  # set the status code to 400 not possible to set in init
     exc.code = 400  # rest framework APIError is not compatible with integration APIError exception type
     resp = self.endpoint.handle_exception(HttpRequest(), exc)
     assert resp.status_code == 400
     assert resp.exception is True
Exemplo n.º 2
0
def check(res):
    if res['errors']:
        print 'errors:', res
        e = APIException()
        e.status_code = 500
        e.detail = "Internal Error"
        raise e
    return res
Exemplo n.º 3
0
 def __init__(self, why="you must be authenticated to use this api", fields={}):
     raw_detail = {
         "error": "XOSNotAuthenticated",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 4
0
 def __init__(self, why="validation error", fields={}):
     raw_detail = {
         "error": "XOSValidationError",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 5
0
 def __init__(self, why="duplicate key", fields={}):
     raw_detail = {
         "error": "XOSDuplicateKey",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 6
0
 def __init__(self, why="programming error", fields={}):
     raw_detail = {
         "error": "XOSProgrammingError",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 7
0
 def __init__(self, why="permission error", fields={}):
     raw_detail = {
         "error": "XOSPermissionDenied",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 8
0
 def __init__(self, why="conflicting field", fields={}):
     raw_detail = {
         "error": "XOSMissingField",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 9
0
 def __init__(self, why="object not found", fields={}):
     raw_detail = {
         "error": "XOSNotFound",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 10
0
 def __init__(self, why="Service temporarily unavailable, try again later", fields={}):
     raw_detail = {
         "error": "XOSServiceUnavailable",
         "specific_error": why,
         "fields": fields
     }
     APIException.__init__(self, raw_detail)
     self.raw_detail = raw_detail
     self.json_detail = _get_json_error_details(raw_detail)
Exemplo n.º 11
0
    def create(self, request, pk):
        qs = self.get_object()
        if qs.openid != request.auth.openid:
            raise APIException(
                {"detail": "Cannot update data which not yours"})
        else:
            data = request.data
            if 'bin_name' not in data and 'move_to_bin' not in data:
                raise APIException({"detail": "Please Enter the Bin Name"})
            else:
                current_bin_detail = binset.objects.filter(
                    openid=self.request.auth.openid,
                    bin_name=str(data['bin_name'])).first()
                move_to_bin_detail = binset.objects.filter(
                    openid=self.request.auth.openid,
                    bin_name=str(data['move_to_bin'])).first()
                goods_qty_change = stocklist.objects.filter(
                    openid=self.request.auth.openid,
                    goods_code=str(data['goods_code'])).first()
                bin_move_qty_res = qs.goods_qty - int(data['move_qty'])
                if bin_move_qty_res > 0:
                    qs.goods_qty = bin_move_qty_res
                    if current_bin_detail.bin_property == 'Damage':
                        if move_to_bin_detail.bin_property == 'Damage':
                            pass
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    elif current_bin_detail.bin_property == 'Inspection':
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            pass
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    elif current_bin_detail.bin_property == 'Cross_Docking':
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            pass
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    elif current_bin_detail.bin_property == 'Holding':
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            pass
                        else:
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    else:
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            pass
                    StockBinModel.objects.create(
                        openid=self.request.auth.openid,
                        bin_name=str(data['move_to_bin']),
                        goods_code=str(data['goods_code']),
                        goods_desc=goods_qty_change.goods_desc,
                        goods_qty=int(data['move_qty']),
                        bin_size=move_to_bin_detail.bin_size,
                        bin_property=move_to_bin_detail.bin_property)
                    if move_to_bin_detail.empty_label == True:
                        move_to_bin_detail.empty_label = False
                        move_to_bin_detail.save()
                    goods_qty_change.save()
                    qs.save()
                elif bin_move_qty_res == 0:
                    if current_bin_detail.bin_property == 'Damage':
                        if move_to_bin_detail.bin_property == 'Damage':
                            pass
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    elif current_bin_detail.bin_property == 'Inspection':
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            pass
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    elif current_bin_detail.bin_property == 'Cross_Docking':
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            pass
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    elif current_bin_detail.bin_property == 'Holding':
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            pass
                        else:
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock - int(
                                data['move_qty'])
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock + int(
                                data['move_qty'])
                    else:
                        if move_to_bin_detail.bin_property == 'Damage':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.damage_stock = goods_qty_change.damage_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Inspection':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.inspect_stock = goods_qty_change.inspect_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Cross_Docking':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.cross_dock_stock = goods_qty_change.cross_dock_stock + int(
                                data['move_qty'])
                        elif move_to_bin_detail.bin_property == 'Holding':
                            goods_qty_change.can_order_stock = goods_qty_change.can_order_stock - int(
                                data['move_qty'])
                            goods_qty_change.hold_stock = goods_qty_change.hold_stock + int(
                                data['move_qty'])
                        else:
                            pass
                    StockBinModel.objects.create(
                        openid=self.request.auth.openid,
                        bin_name=str(data['move_to_bin']),
                        goods_code=str(data['goods_code']),
                        goods_desc=goods_qty_change.goods_desc,
                        goods_qty=int(data['move_qty']),
                        bin_size=move_to_bin_detail.bin_size,
                        bin_property=move_to_bin_detail.bin_property)
                    if move_to_bin_detail.empty_label == True:
                        move_to_bin_detail.empty_label = False
                        move_to_bin_detail.save()

                    goods_qty_change.save()
                    qs.delete()
                    if StockBinModel.objects.filter(
                            openid=self.request.auth.openid,
                            bin_name=str(data['bin_name'])).exists():
                        pass
                    else:
                        current_bin_detail.empty_label = True
                    current_bin_detail.save()
                elif bin_move_qty_res < 0:
                    raise APIException(
                        {"detail": "Move Qty must < Bin Goods Qty"})
                else:
                    pass
            headers = self.get_success_headers(data)
            return Response(data, status=200, headers=headers)
Exemplo n.º 12
0
    def get(self, request, ffid=None, sfid=None, header=None, method=None):
        if not ffid:
            raise APIException("First file_id not provided")

        if not sfid:
            raise APIException("Second file_id not provided")

        if not header:
            raise APIException("Header not provided")

        if not method:
            raise APIException("Method not provided")

        ffid = int(ffid)
        sfid = int(sfid)

        first_data_raw = CsvFileData.objects.filter(parent_file_id=ffid,
                                                    column_header=header) \
            .order_by('row_num')

        second_data_raw = CsvFileData.objects.filter(parent_file_id=sfid,
                                                     column_header=header) \
            .order_by('row_num')

        itos_map1 = get_itos_map(ffid)
        itos_map2 = get_itos_map(sfid)

        first_data = []
        for dpoint in first_data_raw:
            if dpoint.column_header in itos_map1:
                first_data.append(itos_map1[dpoint.column_header][dpoint.data])
            else:
                first_data.append(dpoint.data)

        second_data = []
        for dpoint in second_data_raw:
            if dpoint.column_header in itos_map2:
                second_data.append(
                    itos_map2[dpoint.column_header][dpoint.data])
            else:
                second_data.append(dpoint.data)

        if len(first_data) != len(second_data):
            messages = []
            if len(second_data) == 0:
                fname = CsvFile.objects.get(id=sfid).display_name
                messages.append(
                    'Header "{}" does not exist in file "{}"'.format(
                        header, fname))

            messages.append(
                'Length of the two files is not identical. {} vs {} rows.'.
                format(len(first_data), len(second_data)))

            return JsonResponse({'status_code': 500, 'messages': messages})

        if 'accuracy' in method.lower():
            acc = str(get_match_acc(first_data, second_data)) + "%"
            accuracy_type = 'Accuracy'
            method_sm = 'Accuracy'
        else:
            acc = get_r2(first_data, second_data)
            accuracy_type = 'R^2'
            method_sm = 'Correlation'

        context = {
            'status_code': 200,
            'accuracy': acc,
            'accuracy_type': accuracy_type,
            'method_sm': method_sm,
            'num_rows': len(first_data),
        }

        return JsonResponse(context)
Exemplo n.º 13
0
 def get(self, request):
     raise APIException('with logging')
Exemplo n.º 14
0
 def authenticate(self, request):
     token = request.query_params.get('token')
     user = models.Userinfo.objects.filter(token=token).first()
     if user:
         return (user.name, 'aaaaaa')
     raise APIException('认证失败')
Exemplo n.º 15
0
def save_facebook_token(request):
    """Save facebook token"""
    logger.debug("Facebook callback just landed")
    print(request.GET)
    error = request.query_params.get('error_code', False)
    error_description = request.query_params.get('error_message', '')
    if error:
        raise APIException("Facebook: " + error_description)

    original_payload = request.query_params.get('state', None)
    payload = request.query_params.get('state', None)
    if payload is None:
        raise ValidationError("No payload specified")
    else:
        try:
            payload = base64.b64decode(payload).decode("utf-8")
            payload = parse_qs(payload)
        except:
            raise ValidationError("Cannot decode payload in base64")

    if "url" not in payload:
        logger.exception(payload)
        raise ValidationError("No url specified from the slack payload")

    if "user" not in payload:
        logger.exception(payload)
        raise ValidationError("No user id specified from the slack payload")

    if "a" not in payload:
        logger.exception(payload)
        raise ValidationError("No academy id specified from the slack payload")

    try:
        academy = Academy.objects.get(id=payload["a"][0])
    except Exception as e:
        raise ValidationError("Not exist academy with that id") from e

    try:
        user = User.objects.get(id=payload["user"][0])
    except Exception as e:
        raise ValidationError("Not exist user with that id") from e

    # token = request.query_params.get('token', None)
    # if token == None:
    #     raise ValidationError("No facebook token specified")

    code = request.query_params.get('code', None)
    if code is None:
        raise ValidationError("No slack code specified")

    params = {
        'client_id': os.getenv('FACEBOOK_CLIENT_ID', ""),
        'client_secret': os.getenv('FACEBOOK_SECRET', ""),
        'redirect_uri': os.getenv('FACEBOOK_REDIRECT_URL', ""),
        'code': code,
    }
    resp = requests.post('https://graph.facebook.com/v8.0/oauth/access_token',
                         data=params)
    if resp.status_code == 200:

        logger.debug("Facebook responded with 200")

        facebook_data = resp.json()
        if 'access_token' not in facebook_data:
            logger.debug("Facebook response body")
            logger.debug(facebook_data)
            raise APIException("Facebook error status: " +
                               facebook_data['error_message'])

        # delete all previous credentials for the same team
        CredentialsFacebook.objects.filter(user_id=user.id).delete()

        utc_now = timezone.now()
        expires_at = utc_now + \
            timezone.timedelta(milliseconds=facebook_data['expires_in'])

        credentials = CredentialsFacebook(
            user=user,
            academy=academy,
            expires_at=expires_at,
            token=facebook_data['access_token'],
        )
        credentials.save()

        params = {
            'access_token': facebook_data['access_token'],
            'fields': 'id,email',
        }
        resp = requests.post('https://graph.facebook.com/me', data=params)
        if resp.status_code == 200:
            logger.debug("Facebook responded with 200")
            facebook_data = resp.json()
            if "email" in facebook_data:
                credentials.email = facebook_data['email']
            if "id" in facebook_data:
                credentials.facebook_id = facebook_data['id']
            credentials.save()

        return HttpResponseRedirect(redirect_to=payload["url"][0])
Exemplo n.º 16
0
def raise_api_exception(code, msg):
    e = APIException()
    e.status_code = code
    e.detail = msg
    raise e
Exemplo n.º 17
0
    def post(self, request, *args, **kwargs):
        from rest_framework.response import Response
        from rest_framework import status

        from rest_framework.exceptions import APIException

        from .utils import validate_otp, generate_otp, send_otp
        from .utils import login_user
        from .models import User
        from .variables import EMAIL, MOBILE

        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)

        verify_otp = serializer.validated_data.get('verify_otp', None)
        name = serializer.validated_data.get('name')
        mobile = serializer.validated_data.get('mobile')
        email = serializer.validated_data.get('email')
        user = serializer.validated_data.get('user', None)

        message = {}

        if verify_otp:
            if validate_otp(email, verify_otp):
                if not user:
                    user = User.objects.create_user(
                        name=name, mobile=mobile, email=email, username=mobile,
                        password=User.objects.make_random_password()
                    )
                    user.is_active = True
                    user.save()
                return Response(login_user(user, self.request),
                                status=status.HTTP_202_ACCEPTED)
            return Response(data={'OTP': [_('OTP Validated successfully!'), ]},
                            status=status.HTTP_202_ACCEPTED)

        else:
            otp_obj_email = generate_otp(EMAIL, email)
            otp_obj_mobile = generate_otp(MOBILE, mobile)

            # Set same OTP for both Email & Mobile
            otp_obj_mobile.otp = otp_obj_email.otp
            otp_obj_mobile.save()

            # Send OTP to Email & Mobile
            sentotp_email = send_otp(email, otp_obj_email, email)
            sentotp_mobile = send_otp(mobile, otp_obj_mobile, email)

            if sentotp_email['success']:
                otp_obj_email.send_counter += 1
                otp_obj_email.save()
                message['email'] = {
                    'otp': _("OTP has been sent successfully.")
                }
            else:
                message['email'] = {
                    'otp': _("OTP sending failed {}".format(
                        sentotp_email['message']))
                }

            if sentotp_mobile['success']:
                otp_obj_mobile.send_counter += 1
                otp_obj_mobile.save()
                message['mobile'] = {
                    'otp': _("OTP has been sent successfully.")
                }
            else:
                message['mobile'] = {
                    'otp': _("OTP sending failed {}".format(
                        sentotp_mobile['message']))
                }

            if sentotp_email['success'] or sentotp_mobile['success']:
                curr_status = status.HTTP_201_CREATED
            else:
                raise APIException(
                    detail=_(
                        'A Server Error occurred: ' + sentotp_mobile['message']
                    ))

            return Response(data=message, status=curr_status)
Exemplo n.º 18
0
def save_github_token(request):

    logger.debug("Github callback just landed")
    logger.debug(request.query_params)

    error = request.query_params.get('error', False)
    error_description = request.query_params.get('error_description', '')
    if error:
        raise APIException("Github: " + error_description)

    url = request.query_params.get('url', None)
    if url == None:
        raise ValidationError("No callback URL specified")
    code = request.query_params.get('code', None)
    if code == None:
        raise ValidationError("No github code specified")

    payload = {
        'client_id': os.getenv('GITHUB_CLIENT_ID', ""),
        'client_secret': os.getenv('GITHUB_SECRET', ""),
        'redirect_uri': os.getenv('GITHUB_REDIRECT_URL', ""),
        'code': code,
    }
    headers = {'Accept': 'application/json'}
    resp = requests.post('https://github.com/login/oauth/access_token',
                         data=payload,
                         headers=headers)
    if resp.status_code == 200:

        logger.debug("Github responded with 200")

        body = resp.json()
        if 'access_token' not in body:
            raise APIException(body['error_description'])

        github_token = body['access_token']
        resp = requests.get('https://api.github.com/user',
                            headers={'Authorization': 'token ' + github_token})
        if resp.status_code == 200:
            github_user = resp.json()
            logger.debug(github_user)
            if github_user['email'] is None:
                resp = requests.get(
                    'https://api.github.com/user/emails',
                    headers={'Authorization': 'token ' + github_token})
                if resp.status_code == 200:
                    emails = resp.json()
                    primary_emails = [
                        x for x in emails if x["primary"] == True
                    ]
                    if len(primary_emails) > 0:
                        github_user['email'] = primary_emails[0]["email"]
                    elif len(emails) > 0:
                        github_user['email'] = emails[0]["email"]

            if github_user['email'] is None:
                raise ValidationError("Imposible to retrieve user email")

            # TODO: if user_id: User.objects.filter(id=user_id).first()

            user = User.objects.filter(
                Q(credentialsgithub__github_id=github_user['id'])
                | Q(email__iexact=github_user['email'])).first()
            if user is None:
                user = User(username=github_user['email'],
                            email=github_user['email'])
                user.save()

            CredentialsGithub.objects.filter(
                github_id=github_user['id']).delete()
            github_credentials = CredentialsGithub(
                github_id=github_user['id'],
                user=user,
                token=github_token,
                username=github_user['login'],
                email=github_user['email'],
                avatar_url=github_user['avatar_url'],
                name=github_user['name'],
                blog=github_user['blog'],
                bio=github_user['bio'],
                company=github_user['company'],
                twitter_username=github_user['twitter_username'])
            github_credentials.save()

            profile = Profile.objects.filter(user=user).first()
            if profile is None:
                profile = Profile(
                    user=user,
                    avatar_url=github_user['avatar_url'],
                    blog=github_user['blog'],
                    bio=github_user['bio'],
                    twitter_username=github_user['twitter_username'])
                profile.save()

            student_role = Role.objects.get(slug="student")
            cus = CohortUser.objects.filter(user=user, role="STUDENT")
            for cu in cus:
                profile_academy = ProfileAcademy.objects.filter(
                    user=cu.user, academy=cu.cohort.academy).first()
                if profile_academy is None:
                    profile_academy = ProfileAcademy(
                        user=cu.user,
                        academy=cu.cohort.academy,
                        role=student_role,
                        email=cu.user.email,
                        first_name=cu.user.first_name,
                        last_name=cu.user.last_name,
                        status='ACTIVE')
                    profile_academy.save()

            token, created = Token.objects.get_or_create(user=user,
                                                         token_type='login')

            return HttpResponseRedirect(redirect_to=url + '?token=' +
                                        token.key)
        else:
            # print("Github error: ", resp.status_code)
            # print("Error: ", resp.json())
            raise APIException("Error from github")
Exemplo n.º 19
0
def appid_validate(data):
    if Users.objects.filter(appid=data).exists():
        return data
    else:
        raise APIException({'detail': 'User Does Not Exists'})
Exemplo n.º 20
0
def handle_response(res):
    if 200 <= res.status_code < 300:
        return res
    exc = APIException(detail=res.reason)
    exc.status_code = res.status_code
    raise exc
Exemplo n.º 21
0
def add_objects(request):
    r = request.data

    if not all(key in ['agent', 'objects', 'root'] for key in request.data):
        raise APIException(detail="Missing parameters", code=400)

    agent = get_object_or_404(Agent, name=r['agent'])
    if request.user not in agent.users.all():
        raise APIException(
            detail="You don't have permission to work on this agent", code=403)

    snapshots = BackupSnapshot.objects.filter(root__path=request.data['root'])

    snapshotids = {}

    for snap in snapshots:
        snapshotids[snap.seqno] = snap
    '''
    class Object(models.Model):
    id = models.CharField(max_length=64, primary_key=True)
    objhash = models.CharField(max_length=64)
    name = models.CharField(max_length=255)
    path = models.CharField(max_length=4096)
    type = models.CharField(max_length=4)
    stat = models.CharField(max_length=255)
    prime = models.ForeignKey(DbFile, on_delete=models.CASCADE, null=True, blank=True)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name="children")
    snapshot = models.ForeignKey(BackupSnapshot, related_name="backup_objects", on_delete=models.CASCADE, null=True)
    '''

    idmap = {}

    for o in request.data['objects']:
        print(o)

        snapshots = []
        for s in o['snapshots'][0]:
            snapshots.append(snapshotids.get(s))

        print(o['type'])

        if o['type'] == 'file':
            prime = DbFile.objects.get(id=o['prime'])
        else:
            prime = None

        if 'parent' in o:
            parent = Object.objects.get(id=o['parent'])
        else:
            parent = None

        dobj = Object.objects.create(id=o['id'],
                                     objhash=o['hash'],
                                     name=o['name'],
                                     path=o['path'],
                                     type=o['type'],
                                     stat=o['stat'],
                                     parent=parent,
                                     prime=prime)

        dobj.snapshots.set([snapshotids[x] for x in o['snapshots'][0]])

    return Response("DONE")
Exemplo n.º 22
0
    def create(self, request):
        # request_validator = RequestValidator()
        # request_validator.authenticate_client(request)
        # auth_response = OAuth2Validator().authenticate_client(request)
        # if not auth_response:
        #     return Response({"error": "invalid_client"}, status=status.HTTP_200_OK)
        client = request.data or {}
        tenant_name = client.get("tenant")
        super_user_username = client.get("username")
        super_user_password = client.get("password")
        super_user_first_name = client.get("firstName")
        super_user_last_name = client.get("lastName")
        super_user_email = client.get("email")
        super_user_mobile = client.get("mobile")
        if tenant_name is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_TENANT_NAME_EMPTY.get("message"))
        if super_user_username is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_USERNAME_EMPTY.get("message"))
        if super_user_password is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_PASSWORD_EMPTY.get("message"))
        if super_user_first_name is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_FIRST_NAME_EMPTY.get("message"))
        if super_user_last_name is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_LAST_NAME_EMPTY.get("message"))
        if super_user_email is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_EMAIL_EMPTY.get("message"))
        if super_user_mobile is None:
            raise APIException(
                TenantAPIErrors.API_ERROR_MOBILE_EMPTY.get("message"))

        try:
            tenant_to_check = Tenant.objects.get(tenant_name=tenant_name)
        except ObjectDoesNotExist as ex:
            tenant_to_check = None

        if tenant_to_check is not None:
            raise APIException("Tenant already exists")

        latest_tenant = None
        schema_name = TenantConstants.TENANT_SCHEMA_NAME_PREFIX + TenantConstants.DEFAULT_TENANT_ID
        try:
            latest_tenant = Tenant.objects\
                .filter(schema_name__contains=TenantConstants.TENANT_SCHEMA_NAME_PREFIX).latest("schema_name")
        except Exception as ex:
            default_tenant = DBUtils.get_or_none(self,
                                                 Tenant,
                                                 schema_name=schema_name)
            if default_tenant is not None:
                raise APIException("Please Try Again")

        if latest_tenant is not None:
            latest_schema_name = latest_tenant.schema_name
            if TenantConstants.TENANT_SCHEMA_NAME_PREFIX in latest_schema_name:
                latest_schema_id = NumberUtils.int_or_0(
                    latest_schema_name.replace(
                        TenantConstants.TENANT_SCHEMA_NAME_PREFIX, ""))
                if latest_schema_id == 0:
                    raise APIException("Please Try Again")
                schema_name = TenantConstants.TENANT_SCHEMA_NAME_PREFIX + str(
                    latest_schema_id + 1)
            else:
                raise APIException("Please Try Again")

        tenant_data = {}
        tenant_data["tenant_name"] = tenant_name
        tenant_data["schema_name"] = schema_name

        try:
            tenant = Tenant.objects.create(**tenant_data)
            tenant.save()
        except Exception as ex:
            raise APIException("Couldn't create tenant")

        TenantUtils.set_current_tenant(tenant, request)

        try:
            # tenant_level_tenant = Tenant.objects.create(**tenant_data)
            # tenant_level_tenant.save()
            user = User.objects.create_user(super_user_username,
                                            email=super_user_email,
                                            password=super_user_password,
                                            first_name=super_user_first_name,
                                            last_name=super_user_last_name,
                                            is_staff=False,
                                            is_superuser=True)
        except Exception as ex:
            raise APIException("Couldn't create user")

        serializer = self.serializer_class(tenant, many=False)
        return Response(serializer.data, status=status.HTTP_200_OK)
Exemplo n.º 23
0
    def create(self, request, *args, **kwargs):
        today = datetime.date.today()

        serializer = CreateCollectionLetterDocumentSerializer(
            data=request.data)
        serializer.is_valid(raise_exception=True)

        invoices = serializer.validated_data["invoices"]
        debt = Decimal(0)
        debt_strings = []
        interest_strings = []
        interest_total = Decimal(0)
        interest_rates = set()
        billing_addresses = []

        for tenant in serializer.validated_data["tenants"]:
            billing_tenantcontact = tenant.get_billing_tenantcontacts(
                today, today).first()

            if not billing_tenantcontact or not billing_tenantcontact.contact:
                raise APIException(
                    _("No billing info or billing info does not have a contact address"
                      ))

            billing_addresses.append("<w:br/>".join([
                str(billing_tenantcontact.contact),
                billing_tenantcontact.contact.address
                if billing_tenantcontact.contact.address else "",
                "{} {}".format(
                    billing_tenantcontact.contact.postal_code
                    if billing_tenantcontact.contact.postal_code else "",
                    billing_tenantcontact.contact.city
                    if billing_tenantcontact.contact.city else "",
                ),
            ]))

        collection_charge_total = Decimal(0)

        for invoice_datum in invoices:
            invoice = invoice_datum["invoice"]
            penalty_interest_data = invoice.calculate_penalty_interest()

            if penalty_interest_data["total_interest_amount"]:
                interest_strings.append(
                    _("Penalty interest for the invoice with the due date of {due_date} is {interest_amount} euroa"
                      ).format(
                          due_date=invoice.due_date.strftime("%d.%m.%Y"),
                          interest_amount=penalty_interest_data[
                              "total_interest_amount"],
                      ))
                interest_total += penalty_interest_data[
                    "total_interest_amount"]

            invoice_debt_amount = invoice.outstanding_amount
            debt += invoice_debt_amount

            debt_strings.append(
                _("{due_date}, {debt_amount} euro (between {start_date} and {end_date})"
                  ).format(
                      due_date=invoice.due_date.strftime("%d.%m.%Y"),
                      debt_amount=invoice_debt_amount,
                      start_date=invoice.billing_period_start_date.strftime(
                          "%d.%m.%Y"),
                      end_date=invoice.billing_period_end_date.strftime(
                          "%d.%m.%Y"),
                  ))

            for interest_period in penalty_interest_data["interest_periods"]:
                interest_rate_tuple = (
                    interest_period["start_date"],
                    interest_period["end_date"],
                    interest_period["penalty_rate"],
                )

                interest_rates.add(interest_rate_tuple)

            collection_charge_total += Decimal(
                invoice_datum["collection_charge"])

        grand_total = debt + interest_total + collection_charge_total

        lease = serializer.validated_data["lease"]

        template_data = {
            "lease_details":
            "<w:br/>".join(
                lease.get_lease_info_text(
                    tenants=serializer.validated_data["tenants"])),
            "billing_address":
            "<w:br/><w:br/>".join(billing_addresses),
            "lease_identifier":
            str(lease.identifier),
            "current_date":
            today.strftime("%d.%m.%Y"),
            "debts":
            "<w:br/>".join(debt_strings),
            "total_debt":
            debt,
            "interest_rates":
            "<w:br/>".join(interest_rates_to_strings(interest_rates)),
            "interests":
            "<w:br/>".join(interest_strings),
            "interest_total":
            interest_total,
            "grand_total":
            grand_total,
            "collection_charge_total":
            collection_charge_total,
            "invoice_count":
            len(invoices),
        }

        doc = serializer.validated_data["template"].render_document(
            template_data)

        if not doc:
            raise ValidationError(
                _("Error creating the document from the template"))

        response = HttpResponse(
            doc,
            content_type=
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        )

        response["Content-Disposition"] = "attachment; filename={}_{}".format(
            str(lease.identifier),
            os.path.basename(
                serializer.validated_data["template"].file.name.replace(
                    "_template", "")),
        )

        return response
Exemplo n.º 24
0
 def __init__(self, why="validation error", fields={}):
     APIException.__init__(self, {"error": "XOSValidationError",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 25
0
    def post(self, request):
        # request.data에
        # access_token과 user_id가 들어온다
        # debug 결과의 NamedTuple
        class DebugTokenInfo(NamedTuple):
            app_id: str
            type: str
            application: str
            expires_at: int
            is_valid: bool
            issued_at: int
            scopes: list
            user_id: str

        # user info의 NamedTuple
        class UserInfo(NamedTuple):
            id: str
            name: str
            email: str

        # token(access_token)을 받아 해당 토큰을 debug
        def get_debug_token_info(token):
            app_id = settings.FACEBOOK_APP_ID
            secret_code = settings.FACEBOOK_APP_SECRET_CODE
            app_access_token = f'{app_id}|{secret_code}'
            # 액세스 토큰 검사
            url_debug_token = 'https://graph.facebook.com/debug_token'
            params_debug_token = {
                'input_token': token,
                'access_token': app_access_token,
            }
            # 이제 유저 정보가 들어온다
            response = requests.get(url_debug_token, params=params_debug_token)
            return DebugTokenInfo(**response.json()['data'])

        # 유저 정보를 받아온다
        def get_user_info(token):
            # 유저 정보를 받아온다
            user_info_fields = [
                'id',
                'name',
                'email',
            ]
            url_graph_user_info = 'https://graph.facebook.com/me'
            params = {
                'fields': ','.join(user_info_fields),
                'access_token': token
            }
            response = requests.get(url_graph_user_info, params=params)
            return UserInfo(**response.json())

        # request.data로 전달된 access_token값으로 debug 요청 결과를 받아옴
        debug_token_info = get_debug_token_info(request.data['access_token'])
        # access_token 값으로 user_info 결과를 받아옴
        user_info = get_user_info(request.data['access_token'])
        # device_token
        device_token = request.data.get('device_token', '')

        # 페이스북이 전달한 user_id와 프론트에서 전달받은 user_id가 일치하지 않으면 오류 발생
        if debug_token_info.user_id != request.data['facebook_user_id']:
            raise APIException('페이스북 사용자와 전달받은 id값이 일치하지 않음')

        # 디버그 토큰값이 비정상이라면 오류 발생
        if not debug_token_info.is_valid:
            raise APIException('페이스북 토큰이 유효하지 않음')

        # 유저에 대한 인증 과정을 거친다
        user = authenticate(facebook_user_id=request.data['facebook_user_id'])
        # 만일 유저가 있다면 serializer data를 리턴한다
        if not user:
            # 유저가 없다면 유저 생성
            user = User.objects.create_user(
                email=user_info.email,
                nickname=user_info.name,
                user_type=User.USER_TYPE_FACEBOOK,
                social_id=user_info.id,
            )
            # 유저 강제 활성화
            user.is_active = True
            user.save()

        # 디바이스 토큰이 들어온다면 디바이스 토큰 값을 넣어준다
        if not device_token == '':
            user.device_token = device_token
            user.save()

        # 유저가 있다면 serialize 데이터 전달
        data = {
            'token': user.token,
            'user': UserSerializer(user).data,
        }

        return Response(data, status=status.HTTP_200_OK)
Exemplo n.º 26
0
    def put(self, request, pk, file_id):
        """
        Update a resource file's metadata

        Accepts application/json encoding.

        ## Parameters
        * `id` - alphanumeric uuid of the resource, i.e. cde01b3898c94cdab78a2318330cf795
        * `file_id` - integer id of the resource file. You can use the `/hsapi/resource/{id}/files`
        to get these
        * `data` - see the "returns" section for formatting

        ## Returns
        ```
        {
            "keywords": [
                "keyword1",
                "keyword2"
            ],
            "spatial_coverage": {
                "units": "Decimal degrees",
                "east": -84.0465,
                "north": 49.6791,
                "name": "12232",
                "projection": "WGS 84 EPSG:4326"
            },
            "extra_metadata": {
                "extended1": "one"
            },
            "temporal_coverage": {
                "start": "2018-02-22",
                "end": "2018-02-24"
            },
            "title": "File Metadata Title"
        }
        ```
        """

        file_serializer = FileMetaDataSerializer(request.data)

        try:
            title = file_serializer.data.pop("title", "")
            resource_file = ResourceFile.objects.get(id=file_id)
            resource_file.metadata.logical_file.dataset_name = title
            resource_file.metadata.logical_file.save()

            spatial_coverage = file_serializer.data.pop("spatial_coverage", None)
            if spatial_coverage is not None:
                if resource_file.metadata.spatial_coverage is not None:
                    cov_id = resource_file.metadata.spatial_coverage.id
                    resource_file.metadata.update_element('coverage',
                                                          cov_id,
                                                          type='point',
                                                          value=spatial_coverage)
                elif resource_file.metadata.spatial_coverage is None:
                    resource_file.metadata.create_element('coverage', type="point",
                                                          value=spatial_coverage)

            temporal_coverage = file_serializer.data.pop("temporal_coverage", None)
            if temporal_coverage is not None:
                if resource_file.metadata.temporal_coverage is not None:
                    cov_id = resource_file.metadata.temporal_coverage.id
                    resource_file.metadata.update_element('coverage',
                                                          cov_id,
                                                          type='period',
                                                          value=temporal_coverage)
                elif resource_file.metadata.temporal_coverage is None:
                    resource_file.metadata.create_element('coverage', type="period",
                                                          value=temporal_coverage)

            keywords = file_serializer.data.pop("keywords", None)
            if keywords is not None:
                resource_file.metadata.keywords = keywords

            extra_metadata = file_serializer.data.pop("extra_metadata", None)
            if extra_metadata is not None:
                resource_file.metadata.extra_metadata = extra_metadata

            resource_file.metadata.save()
        except Exception as e:
            raise APIException(e)

        # TODO: How to leverage serializer for this?
        title = resource_file.metadata.logical_file.dataset_name \
            if resource_file.metadata.logical_file else ""
        keywords = resource_file.metadata.keywords \
            if resource_file.metadata else []
        spatial_coverage = resource_file.metadata.spatial_coverage.value \
            if resource_file.metadata.spatial_coverage else {}
        extra_metadata = resource_file.metadata.extra_metadata \
            if resource_file.metadata else {}
        temporal_coverage = resource_file.metadata.temporal_coverage.value if \
            resource_file.metadata.temporal_coverage else {}

        return Response({
            "title": title,
            "keywords": keywords,
            "spatial_coverage": spatial_coverage,
            "extra_metadata": extra_metadata,
            "temporal_coverage": temporal_coverage
        })
Exemplo n.º 27
0
def predict(request):
    """
    This endpoint handles predicting the data for a specific area over some number
    of days in the future. The expected query params are "country", "state" and "days",
    and the response is a list of data points, each represented as custom objects containing
    the date of infection, the value, and source (a string indicating whether this data point was
    predicted by our model or is from observed data) in a given number of future days.
    """
    country = request.query_params.get("country")
    state = request.query_params.get("state")
    days = int(request.query_params.get("days"))

    true_vals = ['True', 'true']
    current = request.query_params.get("current", None) in true_vals
    worst_effort = request.query_params.get("worst_effort", None) in true_vals
    best_effort = request.query_params.get("best_effort", None) in true_vals

    # Get the models from the URl query parameters.
    # Django expects it to be of the form: 'models=foo&models=bar&...'
    models = request.GET.getlist("models[]", [])

    # Get the area and raise an API exception if we can't.
    try:
        area = Area.objects.get(country=country, state=state)
    except Area.DoesNotExist:
        msg = "Could not find the area for country '{0}'".format(country)
        if state:
            msg += " and state '{0}'".format(state)
        raise APIException(msg)
    except Area.MultipleObjectsReturned:
        msg = "Found multiple areas for country '{0}'".format(country)
        if state:
            msg += " and state '{0}'".format(state)
        msg += ". This is most likely an error with data cleansing."
        raise APIException(msg)

    response = {
        "observed": [],
        "predictions": [],
        "observed_deaths": [],
    }

    # Pull observed data from database.
    observed = Covid19DataPoint.objects.filter(area=area)
    for d in observed:
        response["observed"].append({
            "date": d.date,
            "value": d.val,
        })

    observed_deaths = Covid19DeathDataPoint.objects.filter(area=area)
    for d in observed_deaths:
        response["observed_deaths"].append({
            "date": d.date,
            "value": d.val,
        })

    # Determine the time range for predictions.
    prediction_start_date = max([d.date for d in observed]) + timedelta(days=1)
    prediction_end_date = prediction_start_date + timedelta(days=days)

    for model_name in models:
        model = Covid19Model.objects.get(name=model_name)
        model_death = None
        if model_name[:10] == "SI-kJalpha":
            print(model_name + " (death prediction)")
            model_death = Covid19Model.objects.get(name=model_name +
                                                   " (death prediction)")
        if current:
            qs = Covid19PredictionDataPoint.objects.filter(
                model=model,
                social_distancing=1,
                area=area,
                date__range=(prediction_start_date, prediction_end_date))

            if model_death:
                qs_death = Covid19PredictionDataPoint.objects.filter(
                    model=model_death,
                    social_distancing=1,
                    area=area,
                    date__range=(prediction_start_date, prediction_end_date))

            response["predictions"].append({
                "model": {
                    "name": model.name,
                    "description": model.description
                },
                "distancing":
                "current",
                "time_series": [{
                    "date": d.date,
                    "value": d.val,
                } for d in qs]
            })

            if model_death:
                response["predictions"].append({
                    "model": {
                        "name": model_death.name,
                        "description": model_death.description
                    },
                    "distancing":
                    "current",
                    "time_series": [{
                        "date": d.date,
                        "value": d.val,
                    } for d in qs_death]
                })

        if worst_effort:
            qs = Covid19PredictionDataPoint.objects.filter(
                model=model,
                social_distancing=0,
                area=area,
                date__range=(prediction_start_date, prediction_end_date))

            if model_death:
                qs_death = Covid19PredictionDataPoint.objects.filter(
                    model=model_death,
                    social_distancing=0,
                    area=area,
                    date__range=(prediction_start_date, prediction_end_date))

            response["predictions"].append({
                "model": {
                    "name": model.name,
                    "description": model.description
                },
                "distancing":
                "worst_effort",
                "time_series": [{
                    "date": d.date,
                    "value": d.val,
                } for d in qs]
            })

            if model_death:
                response["predictions"].append({
                    "model": {
                        "name": model_death.name,
                        "description": model_death.description
                    },
                    "distancing":
                    "worst_effort",
                    "time_series": [{
                        "date": d.date,
                        "value": d.val,
                    } for d in qs_death]
                })

        if best_effort:
            qs = Covid19PredictionDataPoint.objects.filter(
                model=model,
                social_distancing=2,
                area=area,
                date__range=(prediction_start_date, prediction_end_date))

            if model_death:
                qs_death = Covid19PredictionDataPoint.objects.filter(
                    model=model_death,
                    social_distancing=2,
                    area=area,
                    date__range=(prediction_start_date, prediction_end_date))

            response["predictions"].append({
                "model": {
                    "name": model.name,
                    "description": model.description
                },
                "distancing":
                "best_effort",
                "time_series": [{
                    "date": d.date,
                    "value": d.val,
                } for d in qs]
            })

            if model_death:
                response["predictions"].append({
                    "model": {
                        "name": model_death.name,
                        "description": model_death.description
                    },
                    "distancing":
                    "best_effort",
                    "time_series": [{
                        "date": d.date,
                        "value": d.val,
                    } for d in qs_death]
                })

    return Response(response)
Exemplo n.º 28
0
def save_slack_token(request):
    """Get Slack token and redirect to authorization route"""
    logger.debug("Slack callback just landed")

    error = request.query_params.get('error', False)
    error_description = request.query_params.get('error_description', '')
    if error:
        raise APIException("Slack: " + error_description)

    original_payload = request.query_params.get('payload', None)
    payload = request.query_params.get('payload', None)
    if payload is None:
        raise ValidationError("No payload specified")
    else:
        try:
            payload = base64.b64decode(payload).decode("utf-8")
            payload = parse_qs(payload)
        except:
            raise ValidationError("Cannot decode payload in base64")

    if "url" not in payload:
        logger.exception(payload)
        raise ValidationError("No url specified from the slack payload")

    if "user" not in payload:
        logger.exception(payload)
        raise ValidationError("No user id specified from the slack payload")

    if "a" not in payload:
        logger.exception(payload)
        raise ValidationError("No academy id specified from the slack payload")

    try:
        academy = Academy.objects.get(id=payload["a"][0])
    except Exception as e:
        raise ValidationError("Not exist academy with that id") from e

    user = None
    try:
        user = User.objects.get(id=payload["user"][0])
    except Exception as e:
        raise ValidationError("Not exist user with that id") from e

    code = request.query_params.get('code', None)
    if code is None:
        raise ValidationError("No slack code specified")

    params = {
        'client_id': os.getenv('SLACK_CLIENT_ID', ""),
        'client_secret': os.getenv('SLACK_SECRET', ""),
        'redirect_uri':
        os.getenv('SLACK_REDIRECT_URL', "") + "?payload=" + original_payload,
        'code': code,
    }
    # print("params", params)
    resp = requests.post('https://slack.com/api/oauth.v2.access', data=params)
    if resp.status_code == 200:

        logger.debug("Slack responded with 200")

        slack_data = resp.json()
        if 'access_token' not in slack_data:
            print("Slack response body", slack_data)
            raise APIException("Slack error status: " + slack_data['error'])

        slack_data = resp.json()
        logger.debug(slack_data)

        # delete all previous credentials for the same team and cohort
        CredentialsSlack.objects.filter(app_id=slack_data['app_id'],
                                        team_id=slack_data['team']['id'],
                                        user__id=user.id).delete()
        credentials = CredentialsSlack(
            user=user,
            app_id=slack_data['app_id'],
            bot_user_id=slack_data['bot_user_id'],
            token=slack_data['access_token'],
            team_id=slack_data['team']['id'],
            team_name=slack_data['team']['name'],
            authed_user=slack_data['authed_user']['id'],
        )
        credentials.save()

        team = SlackTeam.objects.filter(
            academy__id=academy.id, slack_id=slack_data['team']['id']).first()
        if team is None:
            team = SlackTeam(slack_id=slack_data['team']['id'],
                             owner=user,
                             academy=academy)

        team.name = slack_data['team']['name']
        team.save()

        return HttpResponseRedirect(redirect_to=payload["url"][0])
Exemplo n.º 29
0
 def __init__(self, why="broadbandshield error", fields={}):
     APIException.__init__(self, {
         "error": "BBS_Failure",
         "specific_error": why,
         "fields": fields
     })
Exemplo n.º 30
0
 def __init__(self, detail):
     APIException.__init__(self, detail)
     self.status_code = status.HTTP_400_BAD_REQUEST
     self.message = detail
Exemplo n.º 31
0
def unsign_signed_blob(blob, timeout):
    signer = TimestampSigner()
    try:
        return signer.unsign(blob, timeout)
    except (BadSignature, SignatureExpired) as e:
        raise APIException(e)
Exemplo n.º 32
0
 def get(self, request):
     raise APIException('response')
Exemplo n.º 33
0
def openid_validate(data):
    if Users.objects.filter(openid=data).exists():
        return data
    else:
        raise APIException({'detail': 'User does not exists'})
Exemplo n.º 34
0
 def to_internal_value(self, data):
     if data.get('token') and data.get('zone_name') and data.get('time'):
         return data
     else:
         raise APIException({'error': 'Invalid data sended.'})
Exemplo n.º 35
0
 def create(self, request, *args, **kwargs):
     data = request.data
     data['openid'] = self.request.auth.openid
     data['unit_volume'] = round(
         (float(data['goods_w']) * float(data['goods_d']) *
          float(data['goods_h'])) / 1000000000, 4)
     if self.queryset.filter(openid=data['openid'],
                             goods_code=data['goods_code'],
                             is_delete=False).exists():
         raise APIException({"detail": "Data exists"})
     else:
         if supplier.objects.filter(openid=data['openid'],
                                    supplier_name=data['goods_supplier'],
                                    is_delete=False).exists():
             if goods_unit.objects.filter(openid=data['openid'],
                                          goods_unit=data['goods_unit'],
                                          is_delete=False).exists():
                 if goods_class.objects.filter(
                         openid=data['openid'],
                         goods_class=data['goods_class'],
                         is_delete=False).exists():
                     if goods_brand.objects.filter(
                             openid=data['openid'],
                             goods_brand=data['goods_brand'],
                             is_delete=False).exists():
                         if goods_color.objects.filter(
                                 openid=data['openid'],
                                 goods_color=data['goods_color'],
                                 is_delete=False).exists():
                             if goods_shape.objects.filter(
                                     openid=data['openid'],
                                     goods_shape=data['goods_shape'],
                                     is_delete=False).exists():
                                 if goods_specs.objects.filter(
                                         openid=data['openid'],
                                         goods_specs=data['goods_specs'],
                                         is_delete=False).exists():
                                     if goods_origin.objects.filter(
                                             openid=data['openid'],
                                             goods_origin=data[
                                                 'goods_origin'],
                                             is_delete=False).exists():
                                         serializer = self.get_serializer(
                                             data=data)
                                         serializer.is_valid(
                                             raise_exception=True)
                                         serializer.save()
                                         headers = self.get_success_headers(
                                             serializer.data)
                                         return Response(serializer.data,
                                                         status=200,
                                                         headers=headers)
                                     else:
                                         raise APIException({
                                             "detail":
                                             "Goods Origin does not exists or it has been changed"
                                         })
                                 else:
                                     raise APIException({
                                         "detail":
                                         "Goods Specs does not exists or it has been changed"
                                     })
                             else:
                                 raise APIException({
                                     "detail":
                                     "Goods Shape does not exists or it has been changed"
                                 })
                         else:
                             raise APIException({
                                 "detail":
                                 "Goods Color does not exists or it has been changed"
                             })
                     else:
                         raise APIException({
                             "detail":
                             "Goods Brand does not exists or it has been changed"
                         })
                 else:
                     raise APIException({
                         "detail":
                         "Goods Class does not exists or it has been changed"
                     })
             else:
                 raise APIException({
                     "detail":
                     "Goods Unit does not exists or it has been changed"
                 })
         else:
             raise APIException({
                 "detail":
                 "Supplier does not exists or it has been changed"
             })
Exemplo n.º 36
0
    def update(self, request, *args, **kwargs):  # pragma: no cover
        serializer = RepositoryTranslatedExporterSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        for_language = serializer.data.get("language", None)

        workbook = openpyxl.load_workbook(filename=request.data.get("file"))
        worksheet = workbook.get_sheet_by_name("Translate")
        columns = ["ID", "Repository Version", "Language"]

        examples_success = []

        find = False
        for count, row in enumerate(worksheet.iter_rows(), start=1):
            if (row[1].value in columns and row[2].value in columns
                    and row[3].value in columns):
                find = True
                continue
            if find:
                example_id = int(re.sub("[^0-9]", "", row[1].value))
                repository_version = int(row[2].value)
                text_translated = row[5].value

                if not int(kwargs.get("pk")) == repository_version:
                    raise APIException(  # pragma: no cover
                        {
                            "detail": "Import version is different from the selected version"
                        },
                        code=400,
                    )

                if text_translated:
                    example = RepositoryExample.objects.filter(
                        pk=example_id,
                        repository_version_language__repository_version=
                        repository_version,
                        repository_version_language__repository_version__repository
                        =kwargs.get("repository__uuid"),
                    )
                    if example.count() == 0:
                        worksheet.cell(row=count,
                                       column=7,
                                       value="Sentence does not exist")
                        continue

                    example = example.first()

                    entity_validation = False

                    for entity in utils.find_entities_in_example(
                            text_translated):
                        original_text_count_entity = (
                            RepositoryExampleEntity.objects.filter(
                                repository_example=example,
                                entity__repository_version=kwargs.get("pk"),
                                entity__value=entity.get("entity"),
                            ).count())

                        if original_text_count_entity == 0:
                            entity_validation = True
                            worksheet.cell(row=count,
                                           column=7,
                                           value="Entities must match")
                            break

                    if entity_validation:
                        continue

                    translated_examples = RepositoryTranslatedExample.objects.filter(
                        original_example=example, language=for_language)

                    if translated_examples.count() > 0:
                        translated_examples.delete()

                    version_language = example.repository_version_language.repository_version.get_version_language(
                        language=for_language)

                    translated = RepositoryTranslatedExample.objects.create(
                        repository_version_language=version_language,
                        original_example=example,
                        language=for_language,
                        text=utils.get_without_entity(text_translated),
                        clone_repository=True,
                    )

                    for translated_entity in utils.find_entities_in_example(
                            text_translated):
                        RepositoryTranslatedExampleEntity.objects.create(
                            repository_translated_example=translated,
                            start=translated_entity["start"],
                            end=translated_entity["end"],
                            entity=translated_entity["entity"],
                        )

                examples_success.append(count)

        for r in reversed(examples_success):
            worksheet.delete_rows(r)

        response = HttpResponse(
            content=save_virtual_workbook(workbook),
            content_type=
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        )
        response["Content-Disposition"] = "attachment; filename=bothub.xlsx"
        return response
Exemplo n.º 37
0
 def __init__(self, why="object not found", fields={}):
     APIException.__init__(self, {"error": "XOSNotFound",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 38
0
 def partial_update(self, request, pk):
     qs = self.get_object()
     if qs.openid != request.auth.openid:
         raise APIException(
             {"detail": "Cannot partial_update data which not yours"})
     else:
         data = request.data
         if supplier.objects.filter(openid=self.request.auth.openid,
                                    supplier_name=data['goods_supplier'],
                                    is_delete=False).exists():
             if goods_unit.objects.filter(openid=self.request.auth.openid,
                                          goods_unit=data['goods_unit'],
                                          is_delete=False).exists():
                 if goods_class.objects.filter(
                         openid=self.request.auth.openid,
                         goods_class=data['goods_class'],
                         is_delete=False).exists():
                     if goods_brand.objects.filter(
                             openid=self.request.auth.openid,
                             goods_brand=data['goods_brand'],
                             is_delete=False).exists():
                         if goods_color.objects.filter(
                                 openid=self.request.auth.openid,
                                 goods_color=data['goods_color'],
                                 is_delete=False).exists():
                             if goods_shape.objects.filter(
                                     openid=self.request.auth.openid,
                                     goods_shape=data['goods_shape'],
                                     is_delete=False).exists():
                                 if goods_specs.objects.filter(
                                         openid=self.request.auth.openid,
                                         goods_specs=data['goods_specs'],
                                         is_delete=False).exists():
                                     if goods_origin.objects.filter(
                                             openid=self.request.auth.
                                             openid,
                                             goods_origin=data[
                                                 'goods_origin'],
                                             is_delete=False).exists():
                                         serializer = self.get_serializer(
                                             qs, data=data, partial=True)
                                         serializer.is_valid(
                                             raise_exception=True)
                                         serializer.save()
                                         headers = self.get_success_headers(
                                             serializer.data)
                                         return Response(serializer.data,
                                                         status=200,
                                                         headers=headers)
                                     else:
                                         raise APIException({
                                             "detail":
                                             "Goods Origin does not exists or it has been changed"
                                         })
                                 else:
                                     raise APIException({
                                         "detail":
                                         "Goods Specs does not exists or it has been changed"
                                     })
                             else:
                                 raise APIException({
                                     "detail":
                                     "Goods Shape does not exists or it has been changed"
                                 })
                         else:
                             raise APIException({
                                 "detail":
                                 "Goods Color does not exists or it has been changed"
                             })
                     else:
                         raise APIException({
                             "detail":
                             "Goods Brand does not exists or it has been changed"
                         })
                 else:
                     raise APIException({
                         "detail":
                         "Goods Class does not exists or it has been changed"
                     })
             else:
                 raise APIException({
                     "detail":
                     "Goods Unit does not exists or it has been changed"
                 })
         else:
             raise APIException({
                 "detail":
                 "Supplier does not exists or it has been changed"
             })
Exemplo n.º 39
0
 def __init__(self, why="duplicate key", fields={}):
     APIException.__init__(self, {"error": "XOSDuplicateKey",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 40
0
    def _get_account_information(self, api_output):
        """
        Create a dict with account information based on the json response from Dataprovider.
        """
        phone_number_limit = 5
        email_limit = 5
        address_limit = 3

        # Expected API output is json.
        api_output_json = json.loads(api_output)

        # Return 404 when the api returned an error.
        if api_output_json.get('error'):
            raise Http404(api_output_json.get('error'))

        # Return error message when nothing was found.
        if api_output_json.get('total') == 0:
            raise APIException(
                _('I\'m so sorry, I couldn\'t find any data for this website.')
            )

        # Filter useful data.
        result = api_output_json['data'][0]

        # Get the keywords and convert to list.
        tags = result.get('keywords')
        if tags:
            tags = result.get('keywords').strip().rstrip(',').split(',')

        # Get email addresses as a list.
        emails = list(result.get('emailaddresses', []))

        # Determine primary email since Dataprovider doesn't provide it.
        primary_email = None
        if emails:
            primary_email = self._get_primary_email(emails)

            # Set primary email to the first in the list.
            emails.index(primary_email)
            emails.remove(primary_email)
            emails.insert(0, primary_email)

        phone_numbers = []

        # Get primary phone number and convert to a nicer representation.
        phone_number = result.get('phonenumber')

        if phone_number:
            phone_number = parse_phone_number(phone_number)
            phone_numbers.append(phone_number)

        # Get phone numbers as a list.
        raw_phone_numbers = list(result.get('phonenumbers', []))

        # Convert all phone numbers to a nicer representation.
        for raw_phone_number in raw_phone_numbers:
            phone_numbers.append(parse_phone_number(raw_phone_number))

        # Try to parse the address.
        address = result.get('address')
        address_line = ''
        if address:
            # Construct address_line, instead of assigning address to address_line directly,
            # because parse_address() also santizes the result.
            street, street_number, complement = parse_address(address)
            if street:
                address_line = street
            if street_number:
                address_line += ' ' + street_number
            if complement:
                address_line += complement

        # Make the full address.
        addresses = []
        if address or result.get('city') or result.get(
                'zipcode') or result.get('country'):
            addresses = [{
                'address': address_line,
                'city': result.get('city'),
                'country': result.get('country'),
                'postal_code': result.get('zipcode'),
            }]

        # Get social media profiles.
        social_profiles = result.get('socialprofiles')

        # Group profiles by platform.
        # Disregards the other platforms provided by Dataprovider: Facebook, Google Plus and Pinterest.
        social_media = {}
        for profile in social_profiles:
            if profile.startswith('twitter.com/'):
                if 'twitter' not in social_media:
                    social_media['twitter'] = []
                social_media['twitter'].append(profile)
            elif profile.startswith('www.linkedin.com/in/'):
                if 'linkedin' not in social_media:
                    social_media['linkedin'] = []
                social_media['linkedin'].append(profile)

        primary_twitter = ''
        if 'twitter' in social_media:
            primary_twitter = self._get_primary_profile(
                social_media['twitter'], result.get('company'))

        primary_linkedin = ''
        if 'linkedin' in social_media:
            primary_linkedin = self._get_primary_profile(
                social_media['linkedin'], result.get('company'))

        # Build dict with account information.
        account_information = {
            'name': result.get('company'),
            'description': result.get('description'),
            'tags': tags,
            'email_addresses': emails[:email_limit],
            'primary_email': primary_email,
            'phone_numbers': phone_numbers[:phone_number_limit],
            'phone_number': phone_number,
            'addresses': addresses[:address_limit],
            'legalentity': result.get('legalentity'),
            'taxnumber': result.get('taxnumber'),
            'bankaccountnumber': result.get('bankaccountnumber'),
            'cocnumber': result.get('cocnumber'),
            'iban': result.get('iban'),
            'bic': result.get('bic'),
            'social_media_profiles': social_media,
            'twitter': primary_twitter,
            'linkedin': primary_linkedin,
        }

        return account_information
Exemplo n.º 41
0
 def __init__(self, why="permission error", fields={}):
     APIException.__init__(self, {"error": "XOSPermissionDenied",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 42
0
 def __init__(self, why="conflicting field", fields={}):
     APIException.__init__(self, {"error": "XOSMissingField",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 43
0
 def __init__(self, why="you must be authenticated to use this api", fields={}):
     APIException.__init__(self, {"error": "XOSNotAuthenticated",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 44
0
 def __init__(self, errors, detail=None):
     APIException.__init__(self, detail)
     self.errors = errors
Exemplo n.º 45
0
 def __init__(self, why="programming error", fields={}):
     APIException.__init__(self, {"error": "XOSProgrammingError",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 46
0
    def create(self, validated_data):

        clienteCpf = validated_data['cliente']
        codServico = validated_data['servico']

        # Verifica se existe cliente ===================================================================================================
        url = 'http://127.0.0.1:8000/cliente_service/v1/clientes/?nome=&email=&cpf=' + str(
            clienteCpf)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response_clientes = requests.get(url, headers=headers)

        print(response_clientes.status_code)

        if response_clientes.status_code != 200 or response_clientes.json(
        )['count'] == 0:
            raise APIException(
                "Cliente não cadastrado. Para cadastrar um novo cliente acesse: http://127.0.0.1:8000/cliente_service/v1/clientes/?format=api"
            )

        # Verifica se existe o cliente encontra-se registrado no serviço ===================================================================================================
        url = 'http://127.0.0.1:8000/servicos/?cod_servico=' + str(codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response_servicos = requests.get(url, headers=headers)

        data_servico = response_servicos.json()
        if response_servicos.status_code != 200 or data_servico['count'] == 0:
            raise APIException(
                "Serviço não cadastrado. Para cadastrar um novo serviço acesse: http://127.0.0.1:8000/servicos/?format=api"
            )

        results = data_servico['results']
        qtdEntradas = results[0]['entradas']

        # validade da promoção
        validade = datetime.strptime(results[0]['validade'], '%Y-%m-%d').date()

        present = datetime.now().date()
        # present = datetime.strptime(validated_data['data'], '%Y-%m-%d')

        if (present > validade):
            self.resetarRegistros(clienteCpf, codServico)
            raise APIException(
                "Não é possível resgatar o prêmio. A promoção expirou em: " +
                validade.strftime('%d/%m/%Y'))

        # Verifica se ja bateo o valor ===================================================================================================

        #url = 'http://127.0.0.1:8000/registros/?cliente=' + str(clienteCpf) + '&limit='+ str(qtdEntradas)+'&servico=' + str(codServico)
        url = 'http://127.0.0.1:8000/registros/?data=&status=true&cliente=' + str(
            clienteCpf) + '&limit=' + str(qtdEntradas) + '&servico=' + str(
                codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        if response.json()['count'] < qtdEntradas:
            raise APIException(
                "Este cartão ainda não atingiu a quantidade de registros necessários para resgatar o prêmio"
            )

        #for result in response.json()['results']:
        #    print(result)
        #    obj = Registros.objects.get(pk=result['id'])
        #    obj.status = False
        #    obj.save()

        # quantidade de entrada para contemplação

        url = 'http://127.0.0.1:8000/premios/?cliente=' + str(
            clienteCpf) + '&servico=' + str(codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        # Verifica se ja bateo o valor ===================================================================================================
        data_servico = response.json()
        results = data_servico['results']

        if response.status_code != 200 or response.json(
        )['count'] > 0 and validated_data['baixado'] == True:
            raise APIException("Você já resgatou seu prêmio em: " +
                               results[0]['data'])

        self.resetarRegistros(clienteCpf, codServico)

        validated_data['baixado'] = True

        premio = Premios.objects.create(**validated_data)
        return premio
Exemplo n.º 47
0
 def __init__(self, why="configuration error", fields={}):
     APIException.__init__(self, {"error": "XOSConfigurationError",
                         "specific_error": why,
                         "fields": fields})
Exemplo n.º 48
0
    def create(self, validated_data):

        clienteCpf = validated_data['cliente']
        codServico = validated_data['servico']

        #Verifica se existe cliente ===================================================================================================
        url = 'http://127.0.0.1:8000/cliente_service/v1/clientes/?nome=&email=&cpf=' + str(
            clienteCpf)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        if response.status_code != 200 or response.json()['count'] == 0:
            raise APIException(
                "Cliente não cadastrado. Para cadastrar um novo cliente acesse: http://127.0.0.1:8000/cliente_service/v1/clientes/?format=api"
            )

        # Verifica se existe o serviço ===================================================================================================
        url = 'http://127.0.0.1:8000/servicos/?cod_servico=' + str(codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        data_servico = response.json()
        if response.status_code != 200 or data_servico['count'] == 0:
            raise APIException(
                "Serviço não cadastrado. Para cadastrar um novo serviço acesse: http://127.0.0.1:8000/servicos/?format=api"
            )

        # Verifica se ja bateo o valor ===================================================================================================
        results = data_servico['results']
        #quantidade de entrada para contemplação
        qtdEntradas = results[0]['entradas']
        #validade da promoção
        validade = datetime.strptime(results[0]['validade'], '%Y-%m-%d').date()

        present = datetime.now().date()
        #present = datetime.strptime(validated_data['data'], '%Y-%m-%d')

        if (present > validade):
            raise APIException(
                "Não é possível inserir o registro. A promoção expirou em: " +
                validade.strftime('%d/%m/%Y'))

        #url = 'http://127.0.0.1:8000/registros/?cliente=' + str(clienteCpf)+'&servico='+ str(codServico)
        url = 'http://127.0.0.1:8000/registros/?data=&status=true&cliente=' + str(
            clienteCpf) + '&servico=' + str(codServico)
        headers = {
            'Authorization': 'Token f6e1ab7af9980147efde3876ad1984fb7c64782c'
        }
        response = requests.get(url, headers=headers)

        if response.json()['count'] >= qtdEntradas:
            raise APIException(
                "Este cartão já alconçou o numero de entradas, seu prêmio já pode ser resgatado em: http://127.0.0.1:8000/premios/?format=api"
            )

        #raise APIException(validated_data)
        registro = Registros.objects.create(**validated_data)
        return registro
Exemplo n.º 49
0
def validate_or_raise(SerializerCls, data):
    serializer = SerializerCls(data=data)
    if not serializer.is_valid():
        logger.error(f"cannot serializer: cls:{SerializerCls} data:{data}")
        raise APIException("server validation error logged")
    return serializer
Exemplo n.º 50
0
 def __init__(self, why="broadbandshield error", fields={}):
     APIException.__init__(self, {"error": "BBS_Failure", "specific_error": why, "fields": fields})
Exemplo n.º 51
0
 def __init__(self, why="Service temporarily unavailable, try again later", fields={}):
     APIException.__init__(self, {"error": "XOSServiceUnavailable",
                         "specific_error": why,
                         "fields": fields})