Пример #1
0
    def create(self, request):
        data = JSONParser().parse(request)
        try:
            client = setup_client()
        except KeyError:
            return JsonResponse(
                {
                    "error":
                    "Cannot make razorpay plans. Check your credentials"
                },
                status=status.HTTP_403_FORBIDDEN,
            )
        name = (data["first_name"] if "first_name" in data.keys() else
                "Anonymous") + (data["last_name"]
                                if "last_name" in data.keys() else "")
        customer_data = {
            "name": name,
            "contact": data["phone"] if "phone" in data.keys() else "",
            "email": data["email"],
        }

        res = client.customer.create(data=customer_data)
        data["rzp_customer_id"] = res["id"]

        client_serializer = ClientSerializer(data=data,
                                             context={"request": request})
        if client_serializer.is_valid():
            client_serializer.save()
            return JsonResponse(client_serializer.data,
                                status=status.HTTP_200_OK)
        else:
            return JsonResponse(client_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
Пример #2
0
def storlet_list(request):
    """
    List all storlets, or create a new storlet.
    """

    try:
        r = get_redis_connection()
    except RedisError:
        return JSONResponse('Error connecting with DB',
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    if request.method == 'GET':
        keys = r.keys("filter:*")
        storlets = []
        for key in keys:
            storlet = r.hgetall(key)
            storlets.append(storlet)
        sorted_list = sorted(storlets, key=lambda x: int(itemgetter('id')(x)))
        return JSONResponse(sorted_list, status=status.HTTP_200_OK)

    if request.method == 'POST':
        try:
            data = JSONParser().parse(request)
        except ParseError:
            return JSONResponse("Invalid format or empty request",
                                status=status.HTTP_400_BAD_REQUEST)

        if (('filter_type' not in data)
                or ((data['filter_type'] == 'storlet'
                     or data['filter_type'] == 'native')
                    and not check_keys(data.keys(), FILTER_KEYS[2:-1])) or
            ((data['filter_type'] == 'global')
             and not check_keys(data.keys(), GLOBAL_FILTER_KEYS[2:-1]))):
            return JSONResponse("Invalid parameters in request",
                                status=status.HTTP_400_BAD_REQUEST)

        storlet_id = r.incr("filters:id")
        try:
            data['id'] = storlet_id
            r.hmset('filter:' + str(storlet_id), data)

            if data['filter_type'] == 'global':
                if data['enabled'] is True or data[
                        'enabled'] == 'True' or data['enabled'] == 'true':
                    to_json_bools(data, 'has_reverse', 'is_pre_get',
                                  'is_post_get', 'is_pre_put', 'is_post_put',
                                  'enabled')
                    r.hset("global_filters", str(storlet_id), json.dumps(data))

            return JSONResponse(data, status=status.HTTP_201_CREATED)

        except DataError:
            return JSONResponse("Error to save the object",
                                status=status.HTTP_400_BAD_REQUEST)
    return JSONResponse('Method ' + str(request.method) + ' not allowed.',
                        status=status.HTTP_405_METHOD_NOT_ALLOWED)
Пример #3
0
def url_list(request):
    if request.method == 'GET':
        urls = Url.objects.filter(status=1)
        url_serializer = UrlShortnerSerializer(urls, many=True)
        return JsonResponse(url_serializer.data, safe=False)

    elif request.method == 'POST':
        url_data = JSONParser().parse(request)
        if "original_url" in url_data.keys():
            count = Url.objects.filter(original_url=url_data["original_url"],
                                       status=0)
            if count:
                Url.objects.filter(original_url=url_data["original_url"],
                                   status=0).update(status=1)
                return JsonResponse({
                    'message':
                    'Existed Inactive URL status marked as 1 and is Active'
                })
            else:
                short_url = create_short_url(url_data)
                url_data["short_url"] = short_url
                url_serializer = UrlShortnerSerializer(data=url_data)
                if url_serializer.is_valid():
                    url_serializer.save()
                    return JsonResponse(url_serializer.data,
                                        status=status.HTTP_201_CREATED)
            return JsonResponse(url_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
        elif "short_url" in url_data.keys():
            urls = Url.objects.filter(short_url=url_data["short_url"],
                                      status=1)
            url_serializer = UrlShortnerSerializer(urls, many=True)
            return JsonResponse(url_serializer.data,
                                safe=False,
                                status=status.HTTP_200_OK)
        else:
            url_serializer = UrlShortnerSerializer(data=url_data, many=True)
            return JsonResponse(url_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        url_data = JSONParser().parse(request)
        count = Url.objects.filter(original_url=url_data["original_url"],
                                   status=1).update(status=0)
        if count == 1:
            return JsonResponse({
                'message':
                '{} URL deleted successfully and status marked as 0'
            })
        else:
            return JsonResponse({'message': 'URL already deleted'})
Пример #4
0
def forecast_list(request, format=None):
    if request.method == 'GET':
        forecasts = Forecasts.objects.all()

        serializer = forecastSerializer(forecasts, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)

        if ('getForecastWithDateTime' in data.keys()):
            dateTimeToGet = data['date']

            tz = get_current_timezone()
            dt = tz.localize(
                datetime.strptime(dateTimeToGet, '%d %m %Y %H:%M:%S'))

            forecasts = Forecasts.objects.filter(date=dt)
            serializer = forecastSerializer(forecasts)
            return JsonResponse(forecasts, safe=False)

        elif ('getLastForecast' in data.keys()):
            forecasts = Forecasts.objects.latest('id')
            serializer = forecastSerializer(forecasts)
            return JsonResponse(serializer.data, safe=False)

        elif ('deleteForecastWithDateTime' in data.keys()):
            dateTimeToDelete = data['date']
            tz = get_current_timezone()
            dt = tz.localize(
                datetime.strptime(dateTimeToDelete, '%d %m %Y %H:%M:%S'))
            Forecasts.objects.filter(date=dt).delete()
            return JsonResponse("Object Deleted", status=201, safe=False)

        else:
            dateTimeToChange = data['date']

            tz = get_current_timezone()
            dt = tz.localize(
                datetime.strptime(dateTimeToChange, '%d %m %Y %H:%M:%S'))
            data['date'] = dt

            serializer = forecastSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                return JsonResponse(serializer.data, status=201)
            return JsonResponse(serializer.errors, status=400)

    elif request.method == 'DELETE':
        Forecasts.objects.latest('id').delete()
        return JsonResponse("Object Deleted", status=201, safe=False)
Пример #5
0
def CreateAdvisor(request):
    advisor_data = JSONParser().parse(request)
    if not ('name' in advisor_data.keys() and 'pic' in advisor_data.keys()):
        return JsonResponse({
            "success": False,
            "message": "Missing Parameters"
        },
                            status=status.HTTP_400_BAD_REQUEST)

    advisor_serializer = AdvisorSerializer(data=advisor_data)
    if advisor_serializer.is_valid():
        advisor_serializer.save()
        return JsonResponse(advisor_serializer.data, status=status.HTTP_200_OK)
    return JsonResponse(advisor_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Пример #6
0
def add_client(request):
    if request.method == 'POST':
        client_data = JSONParser().parse(request)
        client_serializer = ClientSerializer(data=client_data)
        if client_serializer.is_valid():
            # Generate query
            cursor = connection.cursor()
            query = 'INSERT INTO clients_client('
            data_spc_query = ''
            data_query = []
            attrbs_table = list(client_data.keys())
            for a in attrbs_table:
                if a != attrbs_table[-1]:
                    query += a + ', '
                    data_spc_query += '%s, '
                else:
                    query += a + ') VALUES('
                    data_spc_query += '%s);'
                if a != 'password':
                    data_query.append(client_data.get(a))
                else:
                    pwd = make_password(client_data.get(a))
                    data_query.append(pwd)
            query += data_spc_query
            print(query)
            cursor.execute(query, tuple(data_query))
            connection.commit()
            return JsonResponse({
                "code": 201,
                "message": "Client Added"
            },
                                status=status.HTTP_201_CREATED)
        return JsonResponse(client_serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Пример #7
0
    def post(self, request):
        """Cadastra um novo usuário se o usuário que fez a requisição tem \
        permissão de staff

        Formato de entrada:
            {
                "username": string,
                "password": string
            }
        """
        data = JSONParser().parse(request)

        # Pega todos os campos passados, transfoma em uma lista e os ordena
        keys = list(data.keys())
        keys.sort()

        camposEsperados = ['username', 'password']
        camposEsperados.sort()

        if not (keys == camposEsperados):
            return Response(
                        {'error':
                            'passe todos e somente os campos obrigatórios'},
                        status=status.HTTP_400_BAD_REQUEST
                    )

        # Verifica as entradas de username e password
        try:
            usuario = User.objects.create_user(username=data['username'],
                                               password=data['password'])

        except IntegrityError:
            return Response(
                        {'error': 'esse username já foi registrado'},
                        status=status.HTTP_400_BAD_REQUEST
                    )

        except:
            return Response(
                        {'error':
                            'valor do username ou password não informado ou incorreto'},
                        status=status.HTTP_400_BAD_REQUEST
                    )

        criador = Usuario.objects.get(user=request.user.id)

        data = {
            'user': usuario.id,
            'criador': request.user.id,
            'cidade': criador.cidade.id
        }

        serializer = UsuarioSerializer(data=data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        usuario.delete()
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #8
0
def segments(request, mapId=None):
    if request.method == 'GET':
        """ This was used by API to get segments from 1 map at a time...
            Moved to getting all segments with maps """
        map = Map.objects.get(id=mapId)
        geoJson = makeGeoJsonFromMap(map)
        return JsonResponse(geoJson, safe=False)

    if request.method == 'POST':
        data = JSONParser().parse(request)
        #Try validation with serializers...

        if "map" in data.keys() and data["map"] is not None:
            map = Map.objects.get(id=int(data["map"]))
            startTime = None
            endTime = None
            if "startTime" in data.keys():
                startTime = data["startTime"]
            if "endTime" in data.keys():
                endTime = data["endTime"]

            distance = data["distance"]
            waypoints = data["waypoints"]

            #create segment
            mapSegment = Segment(map=map,
                                 startTime=startTime,
                                 endTime=endTime,
                                 distance=distance)

            mapSegment.save()
            #create waypoints
            for point in waypoints:
                waypointObj = WayPoint(segment=mapSegment,
                                       lat=point[1],
                                       lng=point[0])
                waypointObj.save()

            #return custom geoJson
            result = makeGeoJsonFromSegment(mapSegment)

            return JsonResponse(result, safe=False)
        else:
            return JsonResponse({"error": "Bad input"})
Пример #9
0
def CreateUser(request):
    user_data = JSONParser().parse(request)
    if not ('name' in user_data.keys() and 'email' in user_data.keys()
            and 'password' in user_data.keys()):
        return JsonResponse({
            "success": False,
            "message": "Missing Parameters"
        },
                            status=status.HTTP_400_BAD_REQUEST)

    oldUser = getUser(user_data['email'])
    if oldUser:
        return JsonResponse(
            {
                "success": False,
                "message": "User already exists"
            },
            status=status.HTTP_400_BAD_REQUEST)

    salt = gen_salt(6)
    passwordHash = getHash(salt=salt, password=user_data["password"])

    user_data["hash"] = passwordHash[0]
    user_data["salt"] = salt

    user_serializer = UserSerializer(data=user_data)
    if user_serializer.is_valid():
        user_serializer.save()
        token = generateToken(
            payload={
                "name": user_serializer.data["name"],
                "email": user_serializer.data["email"]
            })

        return JsonResponse(
            {
                "token": token,
                "user_id": user_serializer.data['id']
            },
            status=status.HTTP_200_OK,
            safe=False)
    return JsonResponse(user_serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
Пример #10
0
def LoginUser(request):
    login_data = JSONParser().parse(request)

    if not ('email' in login_data.keys() and 'password' in login_data.keys()):
        return JsonResponse({
            "success": False,
            "message": "Missing Parameters"
        },
                            status=status.HTTP_400_BAD_REQUEST)

    oldUser = getUser(login_data['email'])
    if not (oldUser):
        return JsonResponse(
            {
                "success": False,
                "message": "No User Found. Please register first."
            },
            status=status.HTTP_400_BAD_REQUEST)

    user = User.objects.get(email=login_data['email'])
    user_serializer = UserSerializer(user)
    passwordHash = getHash(salt=user_serializer.data['salt'],
                           password=login_data['password'])

    token = generateToken(
        payload={
            "name": user_serializer.data["name"],
            "email": user_serializer.data["email"]
        })

    if passwordHash[0] != user_serializer.data['hash']:
        return JsonResponse({
            "success": False,
            "message": "Incorrect Password"
        },
                            status=status.HTTP_400_BAD_REQUEST)

    return JsonResponse({
        "token": token,
        "user_id": user_serializer.data['id']
    },
                        status=status.HTTP_200_OK)
Пример #11
0
    def put(self, request, pk):
        """ Altera todos os campos de um usuário se ele estiver ativo

        Formato de entrada:
        {
            "password": string
        }
        """

        resposta = verificaUsuarioEAutorizacao(request, pk)

        # Verifica se alguma coisa foi retornada
        if resposta:
            return resposta

        usuario = Usuario.objects.get(pk=pk)

        data = JSONParser().parse(request)

        # Pega todos os campos passados, transfoma em uma lista e os ordena
        keys = list(data.keys())
        keys.sort()

        camposEsperados = ['password']
        camposEsperados.sort()

        if not (keys == camposEsperados):
            return Response(
                        {'error':
                            'passe todos e somente os campos obrigatórios'},
                        status=status.HTTP_400_BAD_REQUEST
                    )

        criador = Usuario.objects.get(user=request.user.id)

        data = {
            'user': usuario.user.id,
            'criador': usuario.criador.id,
            'password': data['password'],
            'cidade': criador.cidade.id
        }

        # Atualiza os campos do usuário passado
        serializer = UsuarioSerializer(usuario, data=data)

        if serializer.is_valid():
            user = User.objects.get(pk=usuario.user.id)
            user.set_password(data['password'])
            user.save()

            serializer.save()
            return Response(serializer.data)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #12
0
def filter_list(request):
    """
    List all filters, or create a new one.
    """

    try:
        r = get_redis_connection()
    except RedisError:
        return JSONResponse('Error connecting with DB', status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    if request.method == 'GET':
        keys = r.keys("filter:*")
        filters = []
        for key in keys:
            filter = r.hgetall(key)
            to_json_bools(filter, 'get', 'put', 'post', 'head', 'delete')
            filters.append(filter)
        sorted_list = sorted(filters, key=lambda x: int(itemgetter('id')(x)))
        return JSONResponse(sorted_list, status=status.HTTP_200_OK)

    if request.method == 'POST':
        try:
            data = JSONParser().parse(request)
        except ParseError:
            return JSONResponse("Invalid format or empty request", status=status.HTTP_400_BAD_REQUEST)

        if (('filter_type' not in data) or
           (data['filter_type'] == 'native' and not check_keys(data.keys(), settings.NATIVE_FILTER_KEYS[2:-1])) or
           (data['filter_type'] == 'storlet' and not check_keys(data.keys(), settings.STORLET_FILTER_KEYS[2:-1]))):
            return JSONResponse("Invalid parameters in request", status=status.HTTP_400_BAD_REQUEST)

        try:
            filter_id = r.incr("filters:id")
            data['id'] = filter_id
            r.hmset('filter:' + str(data['dsl_name']), data)

            return JSONResponse(data, status=status.HTTP_201_CREATED)

        except DataError:
            return JSONResponse("Error to save the object", status=status.HTTP_400_BAD_REQUEST)
    return JSONResponse('Method ' + str(request.method) + ' not allowed.', status=status.HTTP_405_METHOD_NOT_ALLOWED)
Пример #13
0
def retrieve(request):
    filters = {}
    try:
        filters = JSONParser().parse(request)
    except:
        pass

    if len(filters.keys()):
        days = Day.objects.filter(**filters)
    else:
        days = Day.objects.all()

    return JsonResponse(DaySerializer(days, many=True).data, safe=False)
Пример #14
0
def updateMember(request, authMember):
    try:
        body = JSONParser().parse(request)
        # Body contains no information about fields to update.
        if len(body.keys()) < 1:
            return JSONResponse({'msg': 'There is nothing to update'},
                                status=200)

        # Removes the read only fields from body if exists.
        if 'id' in body.keys():
            body.pop('id')
        if 'token' in body.keys():
            body.pop('token')
        if "is_active" in body.keys():
            body.pop("is_active")
        if "is_verified" in body.keys():
            body.pop("is_verified")

        if authMember.email is not "" and "email" in body.keys() and \
                        authMember.email == body["email"].lower():
            del body["email"]

        sendEmail = False
        if "email" in body.keys() and body["email"] is not "":
            body["email"] = body["email"].lower()
            if Member.objects.filter(email=body["email"]).exists():
                raise ValueError(
                    "Email already exists: {}".format(body["email"]))
            else:
                body["is_active"] = False
                body["ev_token"] = str(authMember.id) + binascii.b2a_hex(
                    os.urandom(12))
                sendEmail = True

        # Hash the password before update.
        if 'password' in body.keys():
            body['password'] = hashpassword(body['password'])

        # Finally mem's remaining provided fields will be updated if provided.
        memQuerySet = Member.objects.filter(token=authMember.token)
        memQuerySet.update(**body)
        if sendEmail:
            sendEmailVerification(authMember.id, body["email"], body["ev_token"], request)

        return JSONResponse(getCleanObject(json.loads(serialize('json', memQuerySet))), status=200)
    except:
        logging.error("Update mem failed: {}".format(reportError()))
        return JSONResponse(reportError(), status=400)
Пример #15
0
def create_project(request, id):
    """
    :param request:
    :param id: user_id
    :return:
    """
    result = {"data": None, "msg": "success", "code": 200}
    owner_id = id
    receive_data = JSONParser().parse(request)
    developer = receive_data.pop("developer")

    if not developer:
        result['msg'] = "failed"
        result['code'] = 1001
        return JsonResponse(data=result['data'],
                            code=result['code'],
                            msg=result['msg'])

    for k in list(receive_data.keys()):
        if receive_data.get(k) is None:
            receive_data.pop(k)
    group_data = dict(create_or_delete=False, update=True)
    #创建组
    group = GroupSerializer(data=group_data)

    if not group.is_valid():
        result['msg'] = "failed"
        result['code'] = 1002
        return JsonResponse(data=result['data'],
                            code=result['code'],
                            msg=result['msg'])

    g = group.save()
    receive_data.update({'owner_id': owner_id})
    #建立每个用户和组之间的关系
    for user_id in developer:
        GroupUser.objects.create(uid=user_id, gid=g.gid)
    p = ProjectSerializer(data=receive_data)
    if not p.is_valid():
        result['msg'] = "failed"
        result['code'] = 1003
        return JsonResponse(data=result['data'],
                            code=result['code'],
                            msg=result['msg'])
    project = p.save()
    data = ProjectSerializer(instance=project).data
    #建立项目和组的关系
    ProjectGroup.objects.create(pid=project.pid, gid=g.gid)
    data.update(dict(developer=developer))
    return JsonResponse(data=data, code=200, msg="success")
Пример #16
0
 def put(self, request, id):
     try:
         stream = StringIO.StringIO(request.body)
         data = JSONParser().parse(stream)
     except Exception as e:
         self.logger.error("Unable to decode object. Error: %s"%str(e))
         return Response({"detail": "Invalid object."},
                         status=status.HTTP_400_BAD_REQUEST,
                         exception=True)
     # If valid, update the user
     user = AppUser.objects.get(pk=id)
     for key in data.keys():
         setattr(user, key, data[key])
     user.save()
     return Response({"detail": "User data updated successfully"})
Пример #17
0
    def post(self, request):
        data = JSONParser().parse(request)
        check = Permission.objects.filter(name=data['name']).first()
        if check:
            return Response({"message": "permission name is duplicate"},
                            status=status.HTTP_400_BAD_REQUEST)

        query_data = {"name": data["name"]}
        if "parent" in data.keys():
            query_data["parent"] = Permission.objects.get(name=data['parent'])

        p = Permission.objects.create(**query_data)

        s = PermissionSerialzer(p)
        return Response(s.data, status=status.HTTP_200_OK)
Пример #18
0
def api_search(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        mails_list = Mail.objects.all()
        # Make a query object to collect search criteria
        query = Q()
        if "sender" in data.keys():
            sender_search = data["sender"]
            query = query & Q(sender__icontains=sender_search)
        if "receiver" in data.keys():
            receiver_search = data["receiver"]
            query = query & Q(receiver__icontains=receiver_search)
        if "text" in data.keys():
            body_search = data["text"]
            query = query & Q(text__icontains=body_search)

        # Apply the query
        mails_list = \
            Mail.objects.filter(
                query
            )

        serializer = MailSerializer(mails_list, many=True)
        return JsonResponse(serializer.data, safe=False)
Пример #19
0
 def post(self, request):
     try:
         data = JSONParser().parse(request)
         data = data.get(PARAMETER_DATA)
     except JSONDecodeError:
         raise ParseError(detail="No data found on the request")
     
     resolved_questions = {}
     ids = [int(key) for key in data.keys()]    
     if len(ids) > 0:
         questions = Question.objects(qid__in=ids)
         if len(questions) > 0:
             ''' compare result '''
             resolved_questions = self.resolve_question(data, questions)
     return Response(resolved_questions)
Пример #20
0
def update_student_attendance(request):
    if request.method == 'PUT':
        parsed = JSONParser().parse(request)
        subjects = parsed.keys()
        for subject in subjects:
            students_per_subject = parsed[subject]
            for i in range(len(students_per_subject)):
                student_fresh_data = students_per_subject[i]
                student = Students.objects.filter(
                    regdno=student_fresh_data['regdno'])
                subject_slot = get_subject_slot(subject)
                update_student_subject_attendance(student, subject_slot,
                                                  student_fresh_data)

        return (JsonResponse({'msg': 'successfull update'},
                             status=status.HTTP_200_OK))
Пример #21
0
def assign_orders(request):
    """
    Assigning orders so sum of weights of orders is not greater than carrying capacity of courier
    and regions and working hours matching with region and delivery hours
    """
    if request.method == 'POST' and request.body is not None:
        try:
            json = JSONParser().parse(request)
        except ParseError:
            return JsonResponse({'validation_error': 'Impossible to parse to JSON'}, status=400)
        if list(json.keys()) != ['courier_id'] or len(Courier.objects.filter(courier_id=json.get('courier_id'))) != 1:
            return HttpResponseBadRequest('Json should have only courier_id field with existing id of a courier')
        answer, timestamp = validated_assign_couriers(json)
        answer['assign_time'] = timestamp
        return JsonResponse(answer, status=200) if len(answer['orders']) != 0 else JsonResponse({"orders": []})

    return HttpResponseBadRequest('should be POST request with body')
def change_plan_modify(request):
    """
    Modify single existing change plan
    """
    data = JSONParser().parse(request)
    if "id" not in data:
        return JsonResponse(
            {
                "failure_message": Status.MODIFY_ERROR.value
                + GenericFailure.INTERNAL.value,
                "errors": "Must include 'id' when modifying a change plan",
            },
            status=HTTPStatus.BAD_REQUEST,
        )
    id = data["id"]
    (existing_change_plan, failure_response) = get_change_plan(id)
    if failure_response:
        return failure_response
    failure_response = get_cp_already_executed_response(existing_change_plan)
    if failure_response:
        return failure_response
    for field in data.keys():
        value = data[field]
        setattr(existing_change_plan, field, value)
    try:
        existing_change_plan.save()
        return JsonResponse(
            {
                "success_message": Status.SUCCESS.value
                + "Change Plan "
                + str(existing_change_plan.name)
                + " modified",
                "related_id": str(existing_change_plan.id),
            },
            status=HTTPStatus.OK,
        )
    except Exception as error:
        return JsonResponse(
            {
                "failure_message": Status.MODIFY_ERROR.value
                + parse_save_validation_error(error, "Asset"),
                "errors": str(error),
            },
            status=HTTPStatus.BAD_REQUEST,
        )
Пример #23
0
def change_subscribe_relation_status(request):
    try:
        data = JSONParser().parse(request)
        current_user = request.user
        # check if key in dict
        if not data.keys() >= {"status", "username"}:
            raise Http404('relationship status is required')
        # raise exception if not found
        following_account = Account.objects.get(username=data['username'])
        success_status_message = ''
        if data['status'] == FOLLOW:
            # add
            AccountSubscriber.objects.get_or_create(
                current_account=current_user,
                following_account=following_account)
            success_status_message = 'Account followed successfully !'
        elif data['status'] == UN_FOLLOW:
            #remove
            AccountSubscriber.objects.filter(
                current_account=current_user,
                following_account=following_account).delete()
            success_status_message = 'Account un-followed successfully !'
        else:
            return Response({
                'status':
                'FAILURE',
                'statusCode':
                status.HTTP_400_BAD_REQUEST,
                'statusMessage':
                'status is incorrect, set `FOLLOW` or `UN_FOLLOW`'
            })

        return Response({
            'status': 'SUCCESS',
            'statusCode': status.HTTP_204_NO_CONTENT,
            'statusMessage': success_status_message
        })
    except Exception as e:
        return Response({
            'status': 'FAILURE',
            'statusCode': status.HTTP_500_INTERNAL_SERVER_ERROR,
            'statusMessage': 'some internal server error occured'
        })
Пример #24
0
    def handle(self, *args, **options):
        for id_register in options['id']:
            try:
                self.book = Book.objects.get(pk=id_register)

                serializer = BookSerializer(self.book)
                json = JSONRenderer().render(serializer.data)
                stream = BytesIO(json)
                data = JSONParser().parse(stream)

                column_names = data.keys()
                if os.path.isfile('register.csv'):
                    insert_one_register_csv('register.csv', data, column_names)

                else:
                    create_one_register_csv('register.csv', data, column_names)

                self.stdout.write('Saved')

            except Book.DoesNotExist:
                self.stdout.write('Register {} NotExist'.format(id_register))
Пример #25
0
    def create(self, request):
        data = JSONParser().parse(request)
        try:
            client = setup_client()
        except KeyError:
            return JsonResponse(
                {
                    "error":
                    "Cannot make razorpay plans. Check your credentials"
                },
                status=status.HTTP_403_FORBIDDEN,
            )

        plan_data = {
            "period": get_period(data["duration"]),
            "interval": 1,
            "item": {
                "name": data["title"],
                "amount": int(data["amount"]) * 100,
                "currency": "INR",
                "description": data["desc"] if "desc" in data.keys() else "",
            },
            "notes": {
                "initial_letters_count": data["letters_count"],
                "initial_bureaus_count": data["bureaus_count"],
            },
        }
        res = client.plan.create(data=plan_data)
        data["rzp_plan_id"] = res["id"]

        pricing_serializer = PricingSerializer(data=data,
                                               context={"request": request})
        if pricing_serializer.is_valid():
            pricing_serializer.save()
            pricing_serializer.data['razorpay'] = res
            return JsonResponse(pricing_serializer.data,
                                status=status.HTTP_200_OK)
        else:
            return JsonResponse(pricing_serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
Пример #26
0
def set_likes(request):
    try:
        data = JSONParser().parse(request)
        current_user = request.user
        # check if key in dict
        if not data.keys() >= {"status", "blog_id"}:
            raise Http404('relationship status is required')
        current_blog = Blog.objects.get(pk=data['blog_id'])
        success_status_message = ''
        if data['status']:
            # add
            LikedBy.objects.get_or_create(user=current_user, blog=current_blog)
            success_status_message = 'Like added successfully !'
        elif not data['status']:
            #remove
            LikedBy.objects.filter(user=current_user,
                                   blog=current_blog).delete()
            success_status_message = 'Like removed successfully !'
        else:
            return Response({
                'status':
                'FAILURE',
                'statusCode':
                status.HTTP_400_BAD_REQUEST,
                'statusMessage':
                'status is incorrect, set `FOLLOW` or `UN_FOLLOW`'
            })

        return Response({
            'status': 'SUCCESS',
            'statusCode': status.HTTP_204_NO_CONTENT,
            'statusMessage': success_status_message
        })
    except Exception as e:
        return Response({
            'status': 'FAILURE',
            'statusCode': status.HTTP_500_INTERNAL_SERVER_ERROR,
            'statusMessage': 'some internal server error occured'
        })
Пример #27
0
def reservation_withid(request, reservation_id):

    if request.method == 'GET':
        token_payload = request.META.get('TOKEN_PAYLOAD')

        if not (token_payload.get('admin')):
            if token_payload.get('id'):
                try:
                    member = Member.objects.get(id=token_payload.get('id'))
                except Member.DoesNotExist:
                    return JsonResponse(
                        {'message': 'The member does not exist'},
                        status=status.HTTP_404_NOT_FOUND)
            else:
                return JsonResponse({'message': 'Permission Denied'},
                                    status=status.HTTP_403_FORBIDDEN)
        try:
            reservation = Reservation.objects.get(id=reservation_id)
        except Reservation.DoesNotExist:
            return JsonResponse({'message': 'The reservation does not exist'},
                                safe=False,
                                status=status.HTTP_404_NOT_FOUND)
        if not (token_payload.get('admin')):
            if reservation.member_id != member.id:
                return JsonResponse({'message': 'Permission Denied'},
                                    status=status.HTTP_403_FORBIDDEN)
        serializer = ReservationSerializer(reservation)
        return JsonResponse(serializer.data, safe=False)
    elif request.method == 'PUT':
        token_payload = request.META.get('TOKEN_PAYLOAD')
        if not token_payload.get('admin'):
            return JsonResponse({'message': 'Permission Denied'},
                                status=status.HTTP_403_FORBIDDEN)

        new_data = JSONParser().parse(request)

        try:
            reservation = Reservation.objects.get(id=reservation_id)
        except Reservation.DoesNotExist:
            return JsonResponse({'message': 'The reservation does not exist'},
                                status=status.HTTP_404_NOT_FOUND)
        if 'therapist_id' in new_data.keys():
            new_data['therapist_id'] = ObjectId(new_data['therapist_id'])

        if 'member_id' in new_data.keys():
            new_data['member_id'] = ObjectId(new_data['member_id'])

        if 'services_id' in new_data.keys():

            duration_min = 0
            for service in new_data["services_id"]:
                duration_min += service['duration']

        if 'start_time' in new_data.keys():
            new_data['start_time'] = int(new_data['start_time'])

            new_data['end_time'] = int(
                new_data['start_time']) + int(duration_min) * 60
        else:
            new_data['start_time'] = datetime.timestamp(reservation.start_time)
            new_data['end_time'] = datetime.timestamp(
                reservation.start_time) + (duration_min) * 60

        new_data['start_time'] = datetime.fromtimestamp(
            int(new_data['start_time']) + 3600 * 8)
        new_data['end_time'] = datetime.fromtimestamp(
            int(new_data['end_time']) + 3600 * 8)

        serializer = ReservationSerializer(reservation, data=new_data)
        if serializer.is_valid():
            serializer.save()
        else:
            return JsonResponse(serializer.errors,
                                status=status.HTTP_400_BAD_REQUEST)
        reservation_2 = Reservation.objects.get(id=reservation_id)
        reservation_2 = reservation_2.to_json()
        reservation_2 = json.loads(reservation_2, encoding='utf-8')
        reservation_2['start_time'] = int(
            datetime.timestamp(new_data['start_time'] - timedelta(hours=8)))
        reservation_2['end_time'] = int(
            datetime.timestamp(new_data['end_time'] - timedelta(hours=8)))
        reservation_2['id'] = reservation_2['_id']['$oid']
        reservation_2.pop('_id')
        reservation_2['member_id'] = reservation_2['member_id']['$oid']
        reservation_2['therapist_id'] = reservation_2['therapist_id']['$oid']
        return JsonResponse(reservation_2,
                            status=status.HTTP_200_OK,
                            safe=False)

    elif request.method == 'DELETE':

        token_payload = request.META.get('TOKEN_PAYLOAD')
        if not token_payload.get('admin'):
            return JsonResponse({'message': 'Permission Denied'},
                                status=status.HTTP_403_FORBIDDEN)
        try:
            reservation = Reservation.objects.get(id=reservation_id)
        except Reservation.DoesNotExist:
            return JsonResponse({'message': 'The reservation does not exist'},
                                status=status.HTTP_404_NOT_FOUND)
        reservation.delete()
        return JsonResponse({'message': 'The reservation has been deleted.'},
                            status=status.HTTP_200_OK)
Пример #28
0
def reservation_new(request):
    token_payload = request.META.get('TOKEN_PAYLOAD')
    if token_payload.get('id'):
        try:
            user = Member.objects.get(id=token_payload.get('id'))
        except Member.DoesNotExist:
            return JsonResponse({'message': 'The member does not exist'},
                                status=status.HTTP_404_NOT_FOUND)
    else:
        return JsonResponse({'message': 'Permission Denied'},
                            status=status.HTTP_403_FORBIDDEN)

    if request.method == 'GET':
        therapist_id = request.GET.get('therapist_id', '')
        duration = request.GET.get('duration', '')
        time = request.GET.get('time', '')
        if duration == '':
            return JsonResponse({'message': 'duration must be given.'},
                                status.HTTP_400_BAD_REQUEST)
        if time == '':
            return JsonResponse({'message': 'time must be given.'},
                                status.HTTP_400_BAD_REQUEST)

        time = int(time)
        time_near = time + (900 - time % 900)
        time_date = time - ((time + 28800) % 86400)
        time_10am = time_date + 3600 * 10
        begin = datetime.fromtimestamp(time_10am)
        end = datetime.fromtimestamp(time_10am + 3600 * 14)

        if therapist_id == '':
            reservations = Reservation.objects(
                __raw__={
                    '$or': [
                        {
                            'start_time': {
                                '$lte': end
                            },
                            'end_time': {
                                '$gte': end
                            }
                        },
                        {
                            'start_time': {
                                '$lte': begin
                            },
                            'end_time': {
                                '$gte': begin
                            }
                        },
                        {
                            'start_time': {
                                '$gte': begin
                            },
                            'end_time': {
                                '$lte': end
                            }
                        },
                        {
                            'start_time': {
                                '$lte': begin
                            },
                            'end_time': {
                                '$gte': end
                            }
                        },
                    ]
                })

            calendars = Calendar.objects(
                __raw__={
                    '$or': [
                        {
                            'time_begin': {
                                '$lte': end
                            },
                            'time_end': {
                                '$gte': end
                            }
                        },
                        {
                            'time_begin': {
                                '$lte': begin
                            },
                            'time_end': {
                                '$gte': begin
                            }
                        },
                        {
                            'time_begin': {
                                '$gte': begin
                            },
                            'time_end': {
                                '$lte': end
                            }
                        },
                        {
                            'time_begin': {
                                '$lte': begin
                            },
                            'time_end': {
                                '$gte': end
                            }
                        },
                    ]
                })
        elif therapist_id != '':
            reservations = Reservation.objects(
                __raw__={
                    '$or': [
                        {
                            'start_time': {
                                '$lte': end
                            },
                            'end_time': {
                                '$gte': end
                            }
                        },
                        {
                            'start_time': {
                                '$lte': begin
                            },
                            'end_time': {
                                '$gte': begin
                            }
                        },
                        {
                            'start_time': {
                                '$gte': begin
                            },
                            'end_time': {
                                '$lte': end
                            }
                        },
                        {
                            'start_time': {
                                '$lte': begin
                            },
                            'end_time': {
                                '$gte': end
                            }
                        },
                    ]
                }).filter(therapist_id=therapist_id)

            calendars = Calendar.objects(
                __raw__={
                    '$or': [
                        {
                            'time_begin': {
                                '$lte': end
                            },
                            'time_end': {
                                '$gte': end
                            }
                        },
                        {
                            'time_begin': {
                                '$lte': begin
                            },
                            'time_end': {
                                '$gte': begin
                            }
                        },
                        {
                            'time_begin': {
                                '$gte': begin
                            },
                            'time_end': {
                                '$lte': end
                            }
                        },
                        {
                            'time_begin': {
                                '$lte': begin
                            },
                            'time_end': {
                                '$gte': end
                            }
                        },
                    ]
                }).filter(therapist_id=therapist_id)
        if time_10am >= time_near:
            n = (3600 * 14 // 900)
        else:
            n = ((time_10am + 3600 * 14) - (time_near - time_10am) // 900)
        avliable_time = []
        if therapist_id == '':
            therapists = Therapist.objects.all()
            for i in range(n + 1):
                if time_10am > time_near:
                    start = time_10am + (i) * 900
                    over = start + int(duration) * 60 + 1800
                else:
                    start = time_near + (i) * 900
                    over = start + int(duration) * 60 + 1800
                start = datetime.fromtimestamp(start)
                over = datetime.fromtimestamp(over)
                if over > end:
                    break
                if len(reservations) == 0:
                    avliable_time.append(int(datetime.timestamp(start)) + 900)

                else:
                    therapists_list = []
                    for reservation in reservations:
                        start_time = reservation['start_time'] - \
                            timedelta(
                            minutes=(reservation['buffer_start']))
                        end_time = reservation['end_time'] + \
                            timedelta(
                            minutes=(reservation['buffer_end']))

                        if (start < start_time and over > start_time) or (
                                start == start_time and over > start_time
                        ) or (start < start_time and over > end_time) or (
                                start > start_time and over < end_time) or (
                                    start < end_time and over == end_time) or (
                                        start < end_time and over > end_time):
                            if reservation[
                                    'therapist_id'] not in therapists_list:
                                therapists_list.append(
                                    reservation['therapist_id'])

                    if len(therapists_list) != len(therapists):
                        avliable_time.append(
                            int(datetime.timestamp(start)) + 900)

            return JsonResponse(avliable_time,
                                safe=False,
                                status=status.HTTP_200_OK)

        elif therapist_id != '':
            for i in range(n):
                c = 0
                if time_10am > time_near:
                    start = time_10am + (i) * 900
                    over = start + int(duration) * 60 + 1800
                else:
                    start = time_near + (i) * 900
                    over = start + int(duration) * 60 + 1800
                start = datetime.fromtimestamp(start)
                over = datetime.fromtimestamp(over)
                if over > end:
                    break
                if len(reservations) == 0:
                    avliable_time.append(int(datetime.timestamp(start)) + 900)

                else:
                    for reservation in reservations:

                        start_time = reservation['start_time'] - \
                            timedelta(
                            minutes=(reservation['buffer_start']))
                        end_time = reservation['end_time'] + \
                            timedelta(
                            minutes=(reservation['buffer_end']))

                        if (start < start_time and over > start_time) or (
                                start == start_time and over > start_time
                        ) or (start < start_time and over > end_time) or (
                                start > start_time and over < end_time) or (
                                    start < end_time and over == end_time) or (
                                        start < end_time and over > end_time):
                            c += 1
                            break

                    if c == 0:
                        avliable_time.append(
                            int(datetime.timestamp(start)) + 900)
                        print(
                            datetime.fromtimestamp(
                                int(datetime.timestamp(start)) + 900))
            return JsonResponse(avliable_time,
                                safe=False,
                                status=status.HTTP_200_OK)

    elif request.method == 'POST':
        reservation_data = JSONParser().parse(request)
        reservation_data["member_id"] = user.id
        total_price = 0
        duration_min = 0
        if user['vip'] is True:
            for service_id in reservation_data["services_id"]:
                try:
                    service = Service.objects.get(id=service_id)
                    service['price'] *= service['vip_per']

                    total_price += service['price']
                    duration_min += service['duration']
                except Service.DoesNotExist:
                    return JsonResponse(
                        {'message': 'The service does not exist'},
                        status=status.HTTP_404_NOT_FOUND)
        else:
            for service_id in reservation_data["services_id"]:
                try:
                    service = Service.objects.get(id=service_id)

                    if service['minus'] != 0:
                        if service['price'] <= service['minus']:
                            service['price'] = 0
                        else:
                            service['price'] -= service['minus']
                    else:
                        service['price'] *= service['nor_per']

                    total_price += service['price']
                    duration_min += service['duration']
                except Service.DoesNotExist:
                    return JsonResponse(
                        {'message': 'The service does not exist'},
                        status=status.HTTP_404_NOT_FOUND)

        reservation_data['total_price'] = int(total_price)

        reservation_data['end_time'] = int(
            reservation_data['start_time']) + int(duration_min) * 60
        time = int(reservation_data['start_time'])
        time_date = time - ((time + 28800) % 86400)
        time_10am = time_date + 3600 * 10

        if not ('therapist_id' in reservation_data.keys()):
            avliable_therapist = []
            begin = datetime.fromtimestamp(time_date)
            end = datetime.fromtimestamp(time_10am + 3600 * 14)
            for therapist in Therapist.objects.all():
                c = 0
                reservations = Reservation.objects(therapist_id=therapist.id,
                                                   __raw__={
                                                       '$or': [
                                                           {
                                                               'start_time': {
                                                                   '$lte': end
                                                               },
                                                               'end_time': {
                                                                   '$gte': end
                                                               }
                                                           },
                                                           {
                                                               'start_time': {
                                                                   '$lte':
                                                                   begin
                                                               },
                                                               'end_time': {
                                                                   '$gte':
                                                                   begin
                                                               }
                                                           },
                                                           {
                                                               'start_time': {
                                                                   '$gte':
                                                                   begin
                                                               },
                                                               'end_time': {
                                                                   '$lte': end
                                                               }
                                                           },
                                                           {
                                                               'start_time': {
                                                                   '$lte':
                                                                   begin
                                                               },
                                                               'end_time': {
                                                                   '$gte': end
                                                               }
                                                           },
                                                       ]
                                                   })

                calendars = Calendar.objects(therapist_id=therapist.id,
                                             __raw__={
                                                 '$or': [
                                                     {
                                                         'time_begin': {
                                                             '$lte': end
                                                         },
                                                         'time_end': {
                                                             '$gte': end
                                                         }
                                                     },
                                                     {
                                                         'time_begin': {
                                                             '$lte': begin
                                                         },
                                                         'time_end': {
                                                             '$gte': begin
                                                         }
                                                     },
                                                     {
                                                         'time_begin': {
                                                             '$gte': begin
                                                         },
                                                         'time_end': {
                                                             '$lte': end
                                                         }
                                                     },
                                                     {
                                                         'time_begin': {
                                                             '$lte': begin
                                                         },
                                                         'time_end': {
                                                             '$gte': end
                                                         }
                                                     },
                                                 ]
                                             })

                if (len(reservations) + len(calendars)) == 0:
                    avliable_therapist.append(therapist.id)

                else:
                    start = datetime.fromtimestamp(
                        int(reservation_data['start_time']) - 900)
                    over = datetime.fromtimestamp(
                        int(reservation_data['end_time']) + 900)
                    for reservation in reservations:
                        start_time = reservation['start_time'] - \
                            timedelta(
                            minutes=(reservation['buffer_start']))
                        end_time = reservation['end_time'] + \
                            timedelta(
                            minutes=(reservation['buffer_end']))

                        if (start < start_time and over > start_time) or (
                                start == start_time and over > start_time
                        ) or (start < start_time and over > end_time) or (
                                start > start_time and over < end_time) or (
                                    start < end_time and over == end_time) or (
                                        start < end_time and over > end_time):
                            c += 1
                            break

                    if c == 0:
                        avliable_therapist.append(str(therapist.id))

            if avliable_therapist != []:
                random.shuffle(avliable_therapist)
                reservation_data['therapist_id'] = avliable_therapist[0]
            else:
                return JsonResponse(avliable_therapist,
                                    safe=False,
                                    status=status.HTTP_201_CREATED)

        begin = datetime.fromtimestamp(time_date)
        end = datetime.fromtimestamp(time_10am + 3600 * 14)

        reservations = Reservation.objects(
            __raw__={
                '$or': [
                    {
                        'start_time': {
                            '$lte': end
                        },
                        'end_time': {
                            '$gte': end
                        }
                    },
                    {
                        'start_time': {
                            '$lte': begin
                        },
                        'end_time': {
                            '$gte': begin
                        }
                    },
                    {
                        'start_time': {
                            '$gte': begin
                        },
                        'end_time': {
                            '$lte': end
                        }
                    },
                    {
                        'start_time': {
                            '$lte': begin
                        },
                        'end_time': {
                            '$gte': end
                        }
                    },
                ]
            }).filter(therapist_id=ObjectId(reservation_data['therapist_id']))

        calendars = Calendar.objects(
            __raw__={
                '$or': [
                    {
                        'time_begin': {
                            '$lte': end
                        },
                        'time_end': {
                            '$gte': end
                        }
                    },
                    {
                        'time_begin': {
                            '$lte': begin
                        },
                        'time_end': {
                            '$gte': begin
                        }
                    },
                    {
                        'time_begin': {
                            '$gte': begin
                        },
                        'time_end': {
                            '$lte': end
                        }
                    },
                    {
                        'time_begin': {
                            '$lte': begin
                        },
                        'time_end': {
                            '$gte': end
                        }
                    },
                ]
            }).filter(therapist_id=ObjectId(reservation_data['therapist_id']))

        if (len(calendars) + len(reservations)) != 0:
            start = datetime.fromtimestamp(
                int(reservation_data['start_time']) - 900)
            over = datetime.fromtimestamp(
                int(reservation_data['end_time']) + 900)
            for reservation in reservations:
                start_time = reservation['start_time'] - \
                    timedelta(
                    minutes=(reservation['buffer_start']))
                end_time = reservation['end_time'] + \
                    timedelta(
                    minutes=(reservation['buffer_end']))

                if (start < start_time and over > start_time) or (
                        start == start_time and over > start_time) or (
                            start < start_time and over > end_time) or (
                                start > start_time and over < end_time) or (
                                    start < end_time and over == end_time) or (
                                        start < end_time and over > end_time):

                    return JsonResponse(
                        {
                            'message':
                            'sorry! time interval had been taken by others.'
                        },
                        status=status.HTTP_400_BAD_REQUEST)

        if user['balance'] >= total_price >= 0:
            user['balance'] -= total_price
            user.save()

        else:
            return JsonResponse({'message': 'User balance not enough.'},
                                status=status.HTTP_402_PAYMENT_REQUIRED)

        reservation_fordb = reservation_data.copy()
        reservation_fordb['start_time'] = datetime.fromtimestamp(
            int(reservation_fordb['start_time']) + 3600 * 8)
        reservation_fordb['end_time'] = datetime.fromtimestamp(
            int(reservation_fordb['end_time']) + 3600 * 8)
        services = []
        for service_id in reservation_data['services_id']:
            try:
                service = Service.objects.get(
                    id=ObjectId(str(service_id))).to_json()

                service = json.loads(service, encoding='utf-8')
                service['id'] = str(service['_id']['$oid'])
                service.pop('_id')
                service.pop('long_description')
                services.append(service)
            except Service.DoesNotExist:
                return JsonResponse({'message': 'Service does not exists.'},
                                    status=status.HTTP_400_BAD_REQUEST)

        reservation_fordb['services_id'] = services
        reservation_data['services_id'] = services
        try:
            address = Address.objects.get(
                id=reservation_fordb['address']).to_json()
            reservation_fordb['address'] = json.loads(address,
                                                      encoding='utf-8')
            reservation_fordb['address']['id'] = str(
                reservation_fordb['address']['_id']['$oid'])
            reservation_fordb['address'].pop('_id')
            reservation_fordb['address'].pop('member_id')
            reservation_data['address'] = reservation_fordb['address']

        except Address.DoesNotExist:
            return JsonResponse({'message': 'Address does not exists'},
                                status=status.HTTP_400_BAD_REQUEST)
        serializer_2 = ReservationSerializer(data=reservation_fordb)

        if serializer_2.is_valid():
            serializer_2.save()
        reservation = Reservation.objects.get(id=serializer_2.data['id'])
        reservation_data['id'] = str(reservation.id)
        reservation_data['member_id'] = str(reservation.member_id)
        reservation_data['therapist_id'] = str(reservation.therapist_id)

        return JsonResponse(reservation_data, status=status.HTTP_201_CREATED)
Пример #29
0
def get_virtual_status_info():

    try:

        filelist_in_var_stats = glob.glob(USER_VAR_STATS + "*.virtual.stats")
        filelist_updated = []
        _result_ = {}

        for _loop1_ in Param_container.active_devices_list:

            active_device_ip = str(_loop1_)
            uncode_active_device_ip = unicode(str(active_device_ip).strip())
            _stats_db_ = USER_DATABASES_DIR + "stats.virtualserver." + str(
                active_device_ip) + ".txt"

            # file check, file is not exist, pass through
            if not os.path.isfile(_stats_db_):
                continue

            f = open(_stats_db_, 'r')
            _string_contents_ = f.readlines()
            f.close()
            stream = BytesIO(_string_contents_[0])

            if not len(_string_contents_):
                continue

            _data_from_file_ = JSONParser().parse(stream)

            if (u'origin_ctime' not in _data_from_file_.keys()) or (
                    u'origin_time' not in _data_from_file_.keys()):
                continue
            if (u'updated_ctime' not in _data_from_file_.keys()) or (
                    u'updated_time' not in _data_from_file_.keys()):
                continue

            # hostname define
            _host_defined_name_ = Param_container.active_devices_dict[
                uncode_active_device_ip]

            # get the time data to display
            start_current_time = str(_data_from_file_[u'origin_ctime'])
            end_current_time = str(_data_from_file_[u'updated_ctime'])

            start_time_time = float(_data_from_file_[u'origin_time'])
            end_time_time = float(_data_from_file_[u'updated_time'])

            # confirm the date varidation, time must be bigger
            if float(end_time_time - start_time_time) <= float(0):
                continue
            time_gab = abs(float(end_time_time - start_time_time))
            interval_string = start_current_time + "~" + end_current_time + "(" + str(
                time_gab) + ")"

            # inti the variable and make container to put in
            origin_inform = _data_from_file_[u'origin_items']
            updated_inform = _data_from_file_[u'updated_items']
            origin_inform_keys = origin_inform.keys()
            updated_inform_keys = updated_inform.keys()
            _result_[uncode_active_device_ip] = {}

            for _loop2_ in updated_inform_keys:

                virservername_keyname = str(
                    updated_inform[_loop2_][u'nestedStats'][u'entries']
                    [u'tmName'][u'description']).strip().split("/")[-1]
                _this_value_ = parsing_from_items_with_keyname(
                    _loop2_, origin_inform, updated_inform, time_gab,
                    interval_string, end_time_time)
                _result_[uncode_active_device_ip].update(_this_value_)

                # var/stats file update
                indiv_stats_filename = "%(fname)s@%(device_info)s.virtual.stats" % {
                    "device_info": str(_host_defined_name_),
                    "fname": virservername_keyname
                }
                writing_file_path = str(USER_VAR_STATS +
                                        indiv_stats_filename).strip()
                if indiv_stats_filename not in filelist_updated:
                    filelist_updated.append(writing_file_path)

                json_dumps_msg = json.dumps(_this_value_)

                if writing_file_path not in filelist_in_var_stats:
                    f = open(writing_file_path, 'w')
                    f.write(json_dumps_msg + "\n")
                    f.close()
                else:
                    f = open(writing_file_path, 'r')
                    linelist = f.readlines()
                    f.close()

                    linelist.append(json_dumps_msg + "\n")
                    index_start = int(0)
                    if len(linelist) > (int(STATS_VIEWER_COUNT) *
                                        int(STATS_SAVEDDATA_MULTI)):
                        index_start = int(
                            len(linelist) - (int(STATS_VIEWER_COUNT) *
                                             int(STATS_SAVEDDATA_MULTI)))

                    writing_msg_list = linelist[index_start:]

                    f = open(writing_file_path, 'w')
                    for _wmsg_ in writing_msg_list:
                        f.write(_wmsg_.strip() + "\n")
                    f.close()

        # file remove which currently not existed.
        for _fname_ in filelist_in_var_stats:
            if _fname_ not in filelist_updated:
                bash_command = "rm -rf %(file_path)s" % {"file_path": _fname_}
                get_info = os.popen(bash_command).read().strip()

        if len(_result_.keys()) == 0:
            _result_ = "data is not enough, need to update!"

    except:
        # except
        message = "data perhaps was reset, need to be update."
        return Response(message, status=status.HTTP_400_BAD_REQUEST)

    return _result_
Пример #30
0
def juniper_cachingpolicy(request, format=None):

    #JUNIPER_DEVICELIST_DBFILE = USER_DATABASES_DIR + "devicelist.txt"

    if request.method == 'POST':
        if re.search(r"system", system_property["role"], re.I):
            _input_ = JSONParser().parse(request)
            # confirm input type
            if type(_input_) != type({}):
                return_object = {
                    "items": [],
                    "process_status": "error",
                    "process_msg": "input wrong format"
                }
                return Response(json.dumps(return_object))

            # confirm auth
            if ('auth_key' not in _input_.keys()) and (u'auth_key'
                                                       not in _input_.keys()):
                return_object = {
                    "items": [],
                    "process_status": "error",
                    "process_msg": "no auth_password"
                }
                return Response(json.dumps(return_object))
            #
            auth_matched = re.match(ENCAP_PASSWORD, _input_['auth_key'])
            if auth_matched:

                _fileName_inDirectory_ = os.listdir(USER_VAR_POLICIES)
                policy_files_list = []
                for _fileName_ in _fileName_inDirectory_:
                    if re.search(_validFileName_, str(_fileName_), re.I):
                        _fullPathFileName_ = USER_VAR_POLICIES + str(
                            _fileName_)
                        if _fullPathFileName_ not in policy_files_list:
                            policy_files_list.append(_fullPathFileName_)

                #policy_files_list = os.listdir(USER_VAR_POLICIES)

                # queue generation
                #processing_queues_list = []
                #for _filename_ in policy_files_list:
                #   processing_queues_list.append(Queue(maxsize=0))
                #

                remove_collection('juniperSrx_cacheObjects')
                remove_collection('juniperSrx_cachePolicyTable')

                # run processing to get information
                count = 0
                _processor_list_ = []
                for _filename_ in policy_files_list:
                    #this_processor_queue = processing_queues_list[count]
                    #_processor_ = Process(target = caching_policy, args = (_filename_, this_processor_queue,))
                    _processor_ = Process(target=caching_policy,
                                          args=(_filename_, ))
                    _processor_.start()
                    _processor_list_.append(_processor_)
                    # for next queue
                    count = count + 1
                for _processor_ in _processor_list_:
                    _processor_.join()

                # get information from the queue
                #search_result = []
                #for _queue_ in processing_queues_list:
                #   while not _queue_.empty():
                #        search_result.append(_queue_.get())

                # get information from the queue
                #if not len(search_result):
                #  remove_collection('juniperSrx_cacheObjects')
                #  remove_collection('juniperSrx_cachePolicyTable')
                #  return_object = {
                #       "items":[],
                #       "process_status":"error",
                #       "process_msg":"no file to cache and clear database"
                #  }
                #  return Response(json.dumps(return_object))

                search_result = {
                    "items": [],
                    "process_status": "done",
                    "process_msg": "done"
                }
                return Response(json.dumps(search_result))
                #return Response(json.dumps({"items":search_result}))

            # end of if auth_matched:
            else:
                return_object = {
                    "items": [],
                    "process_status": "error",
                    "process_msg": "wrong auth_password"
                }
                return Response(json.dumps(return_object))
        # end of if re.search(r"system", system_property["role"], re.I):
        else:
            return_object = {
                "items": [],
                "process_status": "error",
                "process_msg": "host is not system"
            }
            return Response(json.dumps(return_object))
Пример #31
0
def transfer_restapi(active_device_ip):

    CURL_command = "curl -sk -u " + USER_NAME + ":" + USER_PASSWORD + " https://" + str(
        active_device_ip
    ) + "/mgmt/tm/ltm/virtual/stats/ -H 'Content-Type: application/json'"
    get_info = os.popen(CURL_command).read().strip()
    stream = BytesIO(get_info)
    data_from_CURL_command = JSONParser().parse(stream)
    virtual_stats = data_from_CURL_command[u'entries']

    # file update and data sorting
    _stats_db_ = USER_DATABASES_DIR + "stats.virtualserver." + str(
        active_device_ip) + ".txt"
    _result_data_ = {}

    # time information to create the files
    Param_container.time_parsed_ctime = str("_".join(
        time.ctime().strip().split()[1:])).strip()
    Param_container.time_time = float(time.time())

    if not os.path.exists(_stats_db_):
        _result_data_[u'origin_items'] = virtual_stats
        _result_data_[u'origin_ctime'] = Param_container.time_parsed_ctime
        _result_data_[u'origin_time'] = Param_container.time_time
    else:
        f = open(_stats_db_, 'r')
        _string_contents_ = f.readlines()
        f.close()

        # 2016 11 01 update : if len
        if len(_string_contents_):
            stream = BytesIO(_string_contents_[0])
            _data_from_file_ = JSONParser().parse(stream)

            if (u'updated_items' not in _data_from_file_.keys()) or (
                    u'updated_ctime' not in _data_from_file_.keys()) or (
                        u'updated_time' not in _data_from_file_.keys()):
                os.popen("rm -rf " + _stats_db_)
                default_items_dict = virtual_stats
                default_ctime = Param_container.time_parsed_ctime
                default_time_time = Param_container.time_time
            else:
                default_items_dict = _data_from_file_[u'updated_items']
                default_ctime = _data_from_file_[u'updated_ctime']
                default_time_time = _data_from_file_[u'updated_time']
            # final origin values
            _result_data_[u'origin_items'] = default_items_dict
            _result_data_[u'origin_ctime'] = default_ctime
            _result_data_[u'origin_time'] = default_time_time

    # final updates values
    _result_data_[u'updated_items'] = virtual_stats
    _result_data_[u'updated_ctime'] = Param_container.time_parsed_ctime
    _result_data_[u'updated_time'] = Param_container.time_time

    # exchange from dict to string
    result_string = json.dumps(_result_data_)
    f = open(_stats_db_, "w")
    f.write(result_string)
    f.close()

    # threading must have
    time.sleep(0)
Пример #32
0
def storlet_detail(request, storlet_id):
    """
    Retrieve, update or delete a Storlet.
    """

    try:
        r = get_redis_connection()
    except RedisError:
        return JSONResponse('Error connecting with DB',
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    if not r.exists("filter:" + str(storlet_id)):
        return JSONResponse('Object does not exist!',
                            status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        my_filter = r.hgetall("filter:" + str(storlet_id))

        to_json_bools(my_filter, 'has_reverse', 'is_pre_get', 'is_post_get',
                      'is_pre_put', 'is_post_put', 'enabled')
        return JSONResponse(my_filter, status=status.HTTP_200_OK)

    elif request.method == 'PUT':
        try:
            data = JSONParser().parse(request)
        except ParseError:
            return JSONResponse("Invalid format or empty request",
                                status=status.HTTP_400_BAD_REQUEST)

        my_filter = r.hgetall("filter:" + str(storlet_id))

        if (((my_filter['filter_type'] == 'storlet'
              or my_filter['filter_type'] == 'native')
             and not check_keys(data.keys(), FILTER_KEYS[3:-1])) or
            ((my_filter['filter_type'] == 'global')
             and not check_keys(data.keys(), GLOBAL_FILTER_KEYS[3:-1]))):
            return JSONResponse("Invalid parameters in request",
                                status=status.HTTP_400_BAD_REQUEST)

        try:
            r.hmset('filter:' + str(storlet_id), data)
            if my_filter['filter_type'] == 'global':
                if data['enabled'] is True or data[
                        'enabled'] == 'True' or data['enabled'] == 'true':
                    to_json_bools(data, 'has_reverse', 'is_pre_get',
                                  'is_post_get', 'is_pre_put', 'is_post_put',
                                  'enabled')
                    data['filter_type'] = 'global'  # Adding filter type
                    r.hset("global_filters", str(storlet_id), json.dumps(data))
                else:
                    r.hdel("global_filters", str(storlet_id))

            return JSONResponse("Data updated", status=status.HTTP_200_OK)
        except DataError:
            return JSONResponse("Error updating data",
                                status=status.HTTP_408_REQUEST_TIMEOUT)

    elif request.method == 'DELETE':
        try:
            keys = r.keys('dsl_filter:*')
            for key in keys:
                dsl_filter_id = r.hget(key, 'identifier')
                if dsl_filter_id == storlet_id:
                    return JSONResponse(
                        'Unable to delete filter, is in use by the Registry DSL.',
                        status=status.HTTP_403_FORBIDDEN)

            my_filter = r.hgetall("filter:" + str(storlet_id))
            r.delete("filter:" + str(storlet_id))
            if my_filter['filter_type'] == 'global':
                r.hdel("global_filters", str(storlet_id))
            return JSONResponse('Filter has been deleted',
                                status=status.HTTP_204_NO_CONTENT)
        except DataError:
            return JSONResponse("Error deleting filter",
                                status=status.HTTP_408_REQUEST_TIMEOUT)
    return JSONResponse('Method ' + str(request.method) + ' not allowed.',
                        status=status.HTTP_405_METHOD_NOT_ALLOWED)