def test_render_dict_abc_obj(self):
        class Dict(MutableMapping):
            def __init__(self):
                self._dict = {}

            def __getitem__(self, key):
                return self._dict.__getitem__(key)

            def __setitem__(self, key, value):
                return self._dict.__setitem__(key, value)

            def __delitem__(self, key):
                return self._dict.__delitem__(key)

            def __iter__(self):
                return self._dict.__iter__()

            def __len__(self):
                return self._dict.__len__()

            def keys(self):
                return self._dict.keys()

        x = Dict()
        x['key'] = 'string value'
        x[2] = 3
        ret = JSONRenderer().render(x)
        data = json.loads(ret.decode('utf-8'))
        self.assertEqual(data, {'key': 'string value', '2': 3})
    def test_renders_openapi_json_schema(self):
        expected_out = {
            "openapi": "3.0.0",
            "info": {
                "version": "",
                "title": "",
                "description": ""
            },
            "servers": [
                {
                    "url": ""
                }
            ],
            "paths": {
                "/": {
                    "get": {
                        "operationId": "list"
                    }
                }
            }
        }
        call_command('generateschema',
                     '--format=openapi-json',
                     stdout=self.out)
        out_json = json.loads(self.out.getvalue())

        self.assertDictEqual(out_json, expected_out)
Exemplo n.º 3
0
    def render(self, data, media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        request = renderer_context['request']
        template = request.query_params.get('template', 'export')
        view = renderer_context['view']
        data = json.loads(json.dumps(data, cls=encoders.JSONEncoder))
        if template == 'import':
            data = [data[0]] if data else data

        try:
            serializer = view.get_serializer()
            self.set_response_disposition(serializer, renderer_context)
        except Exception as e:
            logger.debug(e, exc_info=True)
            value = 'The resource not support export!'.encode('utf-8')
        else:
            fields = serializer.get_fields()
            header = self._get_header(fields, template)
            labels = {k: v.label for k, v in fields.items() if v.label}
            table = self._gen_table(data, header, labels)

            csv_buffer = BytesIO()
            csv_buffer.write(codecs.BOM_UTF8)
            csv_writer = unicodecsv.writer(csv_buffer, encoding='utf-8')
            for row in table:
                csv_writer.writerow(row)

            value = csv_buffer.getvalue()

        return value
Exemplo n.º 4
0
def test_relay_mutation_update_permission_classes_without_permission(
    user_factory, graphql_client
):
    user = user_factory()
    graphql_client.force_authenticate(user)

    response = graphql_client.execute(
        UPDATE_MUTATION,
        {"input": {"id": to_global_id("BookType", 1), "title": "new title"}},
    )

    assert response.status_code == 200
    assert json.loads(response.content) == {
        "data": {"updateRelayBookAdmin": None},
        "errors": [
            {
                "locations": [{"column": 5, "line": 3}],
                "message": "You do not have permission to perform this action.",
                "path": ["updateRelayBookAdmin"],
            }
        ],
    }
Exemplo n.º 5
0
 def get_qq_login_openid(self, access_token):
     params = {
         'access_token': access_token,
     }
     url = 'https://graph.qq.com/oauth2.0/me?' + urlencode(params)
     response = urlopen(url)
     print(222222222222)
     print(response)
     print(222222222222)
     response_data = response.read().decode()
     print(111111111111)
     print(response_data)
     print(111111111111)
     try:
         data = json.loads(response_data[10:-4])
     except Exception:
         data = parse_qs(response_data)
         logger.error('code=%s msg=%s' %
                      (data.get('code'), data.get('msg')))
         raise QQAPIError
     openid = data.get('openid', None)
     return openid
Exemplo n.º 6
0
def test_realtor_can_patch_own_agency(realtor_a, setup):
    client = APIClient()
    _, agency, _, token = realtor_a

    data = {'name': 'Agency Alpha', 'phone': str(agency.phone), 'mls_numbers': []}

    response = perform_api_action(client.patch, data, '/api/v1/agencies/{}/'.format(agency.id), token)

    assert response.status_code == status.HTTP_200_OK

    assert json.loads(response.render().content) == {'name': 'Agency Alpha',
                                                     'address': agency.address.to_dict(),
                                                     'phone': str(agency.phone),
                                                     'mls_numbers': [],
                                                     'id': agency.id}

    agency.refresh_from_db()

    assert agency.name == 'Agency Alpha'
    assert agency.id == agency.id
    assert agency.phone == agency.phone
    assert agency.address == agency.address
Exemplo n.º 7
0
 def post(self, request):
     json_data = json.loads(request.body)
     if "username" in json_data:
         if "password" in json_data:
             user = authenticate(username=json_data["username"],
                                 password=json_data["password"])
             if user is not None:
                 user = User.objects.filter(username=json_data["username"])
                 serializer = UserSerializer(user)
                 return Response(
                     {
                         "user": serializer.data,
                         "login": "******"
                     },
                     status=200)
             else:
                 return Response({"login": "******"}, status=401)
         else:
             return Response({"login": "******"}, status=401)
     else:
         return Response({"login": "******"}, status=401)
     '''
Exemplo n.º 8
0
    def post(self, request, format=None):
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        id = body['questionaireID']
        questionCounter = body['QuestionID']
        #answer = body['answer']
        if id == 1:
            allQuestions = FoodQuestion.objects.get(pk=questionCounter)
            serializer = FoodQuestionSerialzer(allQuestions)
            return Response(serializer.data)
        if id == 2:
            allQuestions = GKQuestion.objects.get(pk=questionCounter)
            serializer = GKQuestionSerialzer(allQuestions, many=False)
            return Response(serializer.data)
        if id == 3:
            allQuestions = DjangoQuestion.objects.get(pk=questionCounter + 3)
            serializer = DjangoQuestionSerialzer(allQuestions)
            return Response(serializer.data)

        #id = request.POST.get('questionaireID')

        print("hello")
Exemplo n.º 9
0
    def post(self, request):
        payload = {
            'access_token': request.data.get("token")
        }  # validate the token
        r = requests.get('https://www.googleapis.com/oauth2/v2/userinfo',
                         params=payload)
        data = json.loads(r.text)

        if 'error' in data:
            content = {
                'message':
                'wrong google token / this google token is already expired.'
            }
            return Response(content)

        try:
            user = MyUser.objects.get(email=data['email'])
        except Exception:
            if 'hd' in data:
                if data['hd'] == 'thapar.edu':
                    user = MyUser()
                    user.password = make_password(
                        BaseUserManager().make_random_password())
                    user.email = data['email']
                    user.username = data['given_name']
                    user.firstName = data['given_name']
                    user.lastName = data['family_name']
                    user.save()
                else:
                    return Response({"error": "Not a thapar.edu email"})
            else:
                return Response({"error": "invalid email"})

        token = RefreshToken.for_user(user)
        response = {}
        response['username'] = user.username
        response['access_token'] = str(token.access_token)
        response['refresh_token'] = str(token)
        return Response(response)
Exemplo n.º 10
0
def student_istaken(request):

    # 수업참가버튼을 누를때 이미 참가버튼을 눌렀었던 학생은 True를 반환합니다
    print('istaken start')
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    # 어떤학생으로 부터의 응답인지, 어떤 강의를 참가하고싶은지 키값을 받습니다.
    student_id = body['student_id']
    lecture_id = body['lecture_id']

    lec = Lecture.objects.get(id=lecture_id)
    print(lec)
    try:
        # 수업에 참여한 학생이라고 기록되어있는경우,
        if lec.students.get(student_id=student_id):
            print("로그확인중입니다.")
            print(lec.students.get(student_id=student_id))
            return JsonResponse({'isExist': True, 'msg': 'already exist'})
    except Student.DoesNotExist:
        # 수업에 참여하지 않은 학생 , False를 반환.
        return JsonResponse({'isExist': False, 'msg': 'need participate in'})
Exemplo n.º 11
0
def student_changeimg(request):
    # 사용자는 이미지 url을 바꿀수있음.

    print('student changeurl start')
    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    # student_id 와 img_url을 받아서 update합니다.
    student_id = body['student_id']
    img_url = body['img_url']

    try:
        stu = Student.objects.get(student_id=student_id)
        stu.img_url = img_url
        stu.save()
        return JsonResponse({
            'isExist': True,
            'msg': 'student img_url is changed'
        })

    except Student.DoesNotExist:
        return JsonResponse({'isExist': False, 'msg': 'student exist error'})
Exemplo n.º 12
0
def updateFamily(request):
    try:
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        idFamily = body['idFamily']
        familyName = body['familyName']
        relationship = body['relationship']
        objFamily = Family.objects.filter(pk=idFamily)
        objFamily.update(familyName=familyName, relationship=relationship)
        serializer = MySerialiser()
        qs_json = serializer.serialize(objFamily)

        response = JsonResponse(
            (GenericResult(True, HTTP_200_OK, "family member update",
                           {'idFamily': qs_json})).__dict__)
    except Exception as e:
        s = str(e)
        logger.info(">>ERROR: " + s)
        response = JsonResponse((GenericResult(False, HTTP_400_BAD_REQUEST,
                                               "error: " + s, {})).__dict__)

    return response
Exemplo n.º 13
0
 def post(self, request, *args, **kwargs):
     if request.content_type == 'text/plain;charset=UTF-8':
         data = json.loads(request.body.decode('utf-8'))
     else:
         data = request.data
     user = get_user_from_request(request)
     # todo: validation throuth forms
     title = data['title']
     authors = data['authors']
     genre = data['genre']
     existing_books = Book.objects.filter(title__contains=title, authors__contains=authors)
     if existing_books:
         book = existing_books[0]
     else:
         book = Book(title=title, authors=authors, genre=genre)
         book.save()
     book_item = BookItem.objects.create(book=book, owner=user)
     if data.get('image'):
         path = 'books/{}/{}.jpg'.format(user.id, book_item.id)
         if data.get('image').find('data:image') != -1:
             image = data['image']
             upload_file(path, image)
             book_item.image = MEDIA_URL + path
             if not book.image:
                 book.image = MEDIA_URL + path
                 book.save()
             book_item.save()
         else:
             book_item.image = data['image']
             if not book.image:
                 book.image = MEDIA_URL + path
                 book.save()
             book_item.save()
     if data.get('isbn'):
         book_item.isbn = data['isbn']
         book_item.save()
     serializer = self.get_serializer(book_item)
     return Response(serializer.data)
Exemplo n.º 14
0
 def post(self, request, *args, **kwargs):
   def takeSecond(elem):
     print(elem['week'])
     return elem['week']
   ret = {'code': 1000, 'msg': None}
   try:      
     reqData = json.dumps(request.data)
     resData = json.loads(reqData)
     # current_page = resData['current_page']
     # page_obj = Pager(current_page)
     # search_dict = dict()
     # for item in resData:
     #   if item != 'current_page':
     #     search_dict[item] = resData[item]
     # searchRes = WeekOrder.objects.filter(**search_dict)
     # count = searchRes.count()
     # resList = searchRes[page_obj.start : page_obj.end]
     resList = WeekOrder.objects.all()
     resDataSer = WeekOrderSerializers(resList, many=True)
     currentWeek = []
     lastWeek = []
     for item in resDataSer.data:
       if item['mark'] == 'current':
         currentWeek.append(item)
       else:
         lastWeek.append(item)
     ret['list'] = dict()
     ret['list']['currentWeek'] = currentWeek
     ret['list']['lastWeek'] = lastWeek
     # ret['list'] = resDataSer.data
     # ret['total'] = count
     ret['code'] = 1001
     ret['msg'] = 'success'
   except Exception as e:
     ret['code'] = 1002
     ret['msg'] = e
     print(e)
   return JsonResponse(ret)
Exemplo n.º 15
0
 def post(self, request, *args, **kwargs):
     try:
         house = House.objects.get(pk=kwargs['pk'])
     except House.DoesNotExist:
         return Response(data={'response': ERROR_HOUSE_DOES_NOT_EXIST})
     sender = request.user
     students_list: Final[List[str]] = json.loads(request.data['students'])
     if not students_list:
         student_object_list: Union[None, List[CustomUser]] = None
     else:
         # Should only work if all emails belong to students and the students are different from the sender
         # Emails can't be repeated
         student_object_list: Union[None, List[CustomUser]] = []
         for st in students_list:
             try:
                 student = CustomUser.objects.get(email=st)
             except ObjectDoesNotExist:
                 return Response(
                     data={'response': ERROR_STUDENT_DOES_NOT_EXIST},
                     status=status.HTTP_400_BAD_REQUEST)
             else:
                 if is_email_of_unique_student_in_application(
                         sender=sender,
                         student=student,
                         accumulated_students=student_object_list):
                     student_object_list.append(student)
                 else:
                     return Response(
                         data={"response": ERROR_REPEATED_STUDENT},
                         status=status.HTTP_400_BAD_REQUEST)
     application = Application.objects.create(house=house, submitted=False)
     if student_object_list:
         application.students.add(*student_object_list)
         application.save()
     sender_info = ApplicationInfo.objects.create(student=sender,
                                                  application=application)
     serializer = ApplicationInfoSerializer(sender_info)
     return Response(data=serializer.data, status=status.HTTP_302_FOUND)
Exemplo n.º 16
0
def set_equipa(request):
    if request.method == 'POST':
        values = json.loads(request.body.decode('utf-8'))
        equipa_serializer = EquipaSerializer(data=values)
        if equipa_serializer.is_valid():
            equipa_serializer.save()
            return JsonResponse(
                {
                    'success': True,
                    'message': 'Equipa criada com sucesso.'
                },
                status=status.HTTP_201_CREATED)
        return JsonResponse(
            {
                'success': False,
                'message': 'Ocorreu um erro ao criar a equipa.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        Equipa.objects.get(id=request.DELETE['id']).delete()
        return JsonResponse(
            {
                'success': True,
                'message': 'Equipa apagada com sucesso.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        Equipa.objects.filter(id=request.PUT['id']).update(
            NomeEquipa=request.PUT['NomeEquipa'],
            Descricao=request.PUT['Descricao'],
            Modalidade=request.PUT['Modalidade'],
            FaixaEtaria=request.PUT['FaixaEtaria'])
        return JsonResponse(
            {
                'success': True,
                'message': 'Atualizado com sucesso.'
            },
            status=status.HTTP_200_OK)
Exemplo n.º 17
0
    def post(self, request):
        payload = {"access_token": request.data.get("token")}  # validate token
        try:
            res = requests.get(GOOGLE_VALIDATE_URL, params=payload)
        except HTTPError as e:
            content = {"error": "Invalid Google token" + str(e)}
            return Response(content, status=400)
        if not res.ok:
            content = {"error": "Invalid Google token"}
            return Response(content, status=401)

        data = json.loads(res.text)

        # create user if doesn't exist
        try:
            user = User.objects.get(email=data["email"])
        except User.DoesNotExist:
            user = User(
                username=data["email"],
                password=make_password(
                    BaseUserManager().make_random_password()),
                email=data["email"],
                first_name=data["given_name"],
                last_name=data["family_name"],
            )
            user.save()
            profile = UserProfile(picture=data['picture'], user=user)
            profile.save()

        refresh_token = RefreshToken.for_user(
            user)  # generate token without username & password
        response = {
            "id": user.id,
            "email": user.email,
            "access_token": str(refresh_token.access_token),
            "refresh_token": str(refresh_token)
        }
        return Response(response)
Exemplo n.º 18
0
def customer_register(request):
    # Check if Request is POST
    if request.method != 'POST':
        raise Exception('Http Method is not POST')

    # Get JSON Data from request
    json_data = json.loads(request.body)

    # Create a customer

    user = User.objects.create_user(username=json_data['username'],
                                    password=json_data['password'],
                                    first_name=json_data['first_name'],
                                    last_name=json_data['last_name'],
                                    email=json_data['email'])
    customer = Customer.objects.create(user=user)
    customer.phone = json_data['phone']
    customer.address = json_data['address']
    customer.balance = 10000
    # Save customer
    user.save()
    customer.save()
    return JsonResponse({"id": customer.id}, status=201)
Exemplo n.º 19
0
def test_min_price(client):
    # given
    user_id = 1
    user = UserFactory(id=user_id)
    VehicleFactory(price=100, owner=user)
    expected_vehicle_1 = VehicleFactory(price=200, owner=user)
    expected_vehicle_2 = VehicleFactory(price=300, owner=user)
    expected_number_of_vehicles = 2
    token = 'Token ' + str(pm.get_token_from_user_id(user_id))

    # when
    response = client.get(urls_factory.url_not_detail(urls_factory.VEHICLES),
                          data={'min_price': 150},
                          HTTP_AUTHORIZATION=token)
    vehicles = list()

    for x in json.loads(response.content)['results']:
        vehicles.append(x['id'])

    # then
    assert response.status_code == 200
    assert expected_number_of_vehicles == len(vehicles)
    assert set(vehicles) == {expected_vehicle_1.id, expected_vehicle_2.id}
Exemplo n.º 20
0
def test_city(client):
    # given
    user_id = 1
    user = UserFactory(id=user_id)
    VehicleFactory(city='Kraków', owner=user)
    VehicleFactory(city='Warszawa', owner=user)
    expected_vehicle_1 = VehicleFactory(city='Opole', owner=user)
    expected_number_of_vehicles = 1
    token = 'Token ' + str(pm.get_token_from_user_id(user_id))

    # when
    response = client.get(urls_factory.url_not_detail(urls_factory.VEHICLES),
                          data={'city': 'Opole'},
                          HTTP_AUTHORIZATION=token)
    vehicles = list()

    for x in json.loads(response.content)['results']:
        vehicles.append(x['id'])

    # then
    assert response.status_code == 200
    assert expected_number_of_vehicles == len(vehicles)
    assert set(vehicles) == {expected_vehicle_1.id}
Exemplo n.º 21
0
def __invites_post(request):
    print_origin(request, 'Invites')

    json_dict = json.loads(request.body)

    # Create a database entry
    return_data = InviteDatabase.create_return_serialized(json_dict)

    # if it returns a string, send a missing property json back
    if isinstance(return_data, str):
        return missing_property_in_json(request, return_data,
                                        CORRECT_INVITE_JSON)

    # Prepare jsonResponse data
    json_data = {
        'requested-url': '[' + request.method + '] ' + request.get_full_path(),
        'message': 'You have posted a new invite',
        'invite': return_data
    }
    return JsonResponse(data=json_data,
                        status=status.HTTP_201_CREATED,
                        safe=False,
                        encoder=DjangoJSONEncoder)
Exemplo n.º 22
0
def reactMemmberDetails(request):
    retstatus = {"status": "1", "message": "Successfully Saved"}
    try:
        print("From AngularMember")
        a = json.loads(request.body)
        print(a)
        print("hai")
        obj = Address(name=a["name1"],
                      place=a["place1"],
                      city=a["city1"],
                      image=a["image"])

        print(obj)
        if Address.objects.filter(name=a["name1"]):
            retstatus = {"status": "0", "message": "Name Already Exist"}
        else:
            obj.save()
            print(obj)
    except Exception as e:
        print(e)
        retstatus = {"status": "0", "message": "Error Occured"}

    return JsonResponse(retstatus)
Exemplo n.º 23
0
    def nbiot_engineering_create(self, request):
        data = JSONParser().parse(request)
        if "messages" not in data or len(
                data["messages"]) == 0 or "payload" not in data["messages"][0]:
            return JsonResponse(status=400, data={"error": "Missing payload."})
        payload_encoded = data["messages"][0]["payload"]
        payload_string = b64decode(payload_encoded).decode("utf-8")
        try:
            payload_data = json.loads(payload_string)
        except ValueError as ex:
            raise ParseError("JSON parse error - {ex}".format(ex=ex))

        serializer = MeasurementCreateSerializer(data=payload_data,
                                                 context={"request": request})
        serializer.is_valid(raise_exception=True)

        response = self.allowed_create(request, serializer.validated_data)
        if response:
            return response

        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=201, headers=headers)
Exemplo n.º 24
0
def __single_player_put(request, player_id):
    print_origin(request, 'Single player')

    json_body = json.loads(request.body)

    # Update a database entry
    return_data = PlayerDatabase.update_return_serialized(json_body, player_id)

    # if it returns a string, send a missing property json back
    if isinstance(return_data, str):
        return missing_property_in_json(request, return_data,
                                        CORRECT_PLAYER_JSON)

    # Prepare jsonResponse data
    json_data = {
        'requested-url': '[' + request.method + '] ' + request.get_full_path(),
        'message': 'You have changed player with id: \'' + player_id + '\'',
        'player': return_data,
    }
    return JsonResponse(data=json_data,
                        status=status.HTTP_202_ACCEPTED,
                        safe=False,
                        encoder=DjangoJSONEncoder)
Exemplo n.º 25
0
def forgot_password_email(request):
    user_data = json.loads(request)
    subject = 'Forgot your password? Well, that happens sometimes.'
    body = 'Here is your new password: '******'new_password']
    email_from = settings.EMAIL_HOST_USER
    recipient_list = [user_data['mail']]
    if send_mail(subject,
                 body,
                 email_from,
                 recipient_list,
                 fail_silently=False) == 1:
        status = "success"
        message = "email sent successfully"
    else:
        status = "error"
        message = "email cannot be sent"
    new_password = user_data['new_password']
    json_data = {
        "status": status,
        "message": message,
        "new_password": new_password
    }
    return JsonResponse(json_data)
Exemplo n.º 26
0
    def findGoodsThemeById(self, request):
        data = json.loads(request.body)
        theme_id = data.get('theme_id')
        theme = list(GoodsTheme.objects.values().filter(Q(theme_id=theme_id)))
        print(theme)
        data = []
        res = {}
        id = theme[0]["theme_id"]
        pic = theme[0]["theme_pic"]
        name = theme[0]["theme_name"]
        child = list(GoodsInfo.objects.values().filter(Q(goods_theme_id=id)))
        res.update({
            'theme_id': id,
            'theme_pic': pic,
            'theme_name': name,
            'child': child,
        })
        data.append(res)

        if res != '':
            return JsonResponse({'status': 200, 'data': data}, safe=False)
        else:
            return JsonResponse({'status': 500, 'message': '服务器发生错误'})
Exemplo n.º 27
0
 def registerListener(request):
     data = request.body
     body = json.loads(data)
     username = body['username']
     password = body['password']
     firstname = body['firstname']
     lastname = body['lastname']
     email = body['email']
     print(username, password, firstname, lastname, password)
     try:
         user_instance = User.objects.create_user(username=username,
                                                  password=password,
                                                  first_name=firstname,
                                                  last_name=lastname,
                                                  email=email)
         user_instance.save()
         print(user_instance.id)
         listener_instance = Listener.objects.create(
             uid_id=user_instance.id)
         listener_instance.save()
         return Response("ok", 200)
     except:
         return Response("register error", 400)
Exemplo n.º 28
0
def handle_comments_for_post(request, post_id):
    session_service = SessionService()
    if request.method == 'GET':  # retrieves existing comments for a post
        session_token = request.GET['token']
        session = session_service.retrieve_session(session_token)
        if session is None:
            return JsonResponse(
                {'error': 'SESSION TIME OUT: ' + session_token}, status=401)
        else:
            session_service.update_session_data(session)
        return handle_get_comments_for_post(post_id)

    if request.method == 'POST':
        form_data = json.loads(request.body.decode())
        session_token = form_data['token']
        session = session_service.retrieve_session(session_token)
        if session is None:
            return JsonResponse(
                {'error': 'SESSION TIME OUT: ' + session_token}, status=401)
        else:
            session_service.update_session_data(session)
        return handle_post_comment_for_post(request, post_id)
    return JsonResponse({'error': 'BAD REQUEST'}, status=401)
Exemplo n.º 29
0
 def post(self, request):
     postdata = json.loads(request.body)
     name = postdata.get("name")
     options = postdata.get("options")
     correctOption = postdata.get("correct_option")
     quiz = Quizdata.objects.filter(pk=postdata.get("quiz")).first()
     points = postdata.get("points")
     question = Questions.objects.create(name=name,
                                         options=options,
                                         correct_option=correctOption,
                                         quiz=quiz,
                                         points=points)
     data = {
         "id": question.id,
         "name": question.name,
         "options": question.options,
         "correct_option": question.correct_option,
         "quiz": quiz.id,
         "points": question.points
     }
     return HttpResponse(json.dumps(data),
                         content_type="application/json",
                         status=201)
Exemplo n.º 30
0
def set_campeonatos(request):
    if request.method == 'POST':
        values = json.loads(request.body.decode('utf-8'))
        campeonato_serializer = CampeonatoSerializer(data=values)
        if campeonato_serializer.is_valid():
            campeonato_serializer.save()
            return JsonResponse(
                {
                    'success': True,
                    'message': 'Campeonato criado com sucesso.'
                },
                status=status.HTTP_201_CREATED)
        return JsonResponse(
            {
                'success': False,
                'message': 'Ocorreu um erro ao criar o campeonato.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        Campeonato.objects.get(id=request.DELETE['id']).delete()
        return JsonResponse(
            {
                'success': True,
                'message': 'Campeonato apagado com sucesso.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        Campeonato.objects.filter(id=request.PUT['id']).update(
            NomeCampeonato=request.PUT['NomeCampeonato'],
            DescricaoCampeonato=request.PUT['DescricaoCampeonato'],
            Epoca=request.PUT['Epoca'])
        return JsonResponse(
            {
                'success': True,
                'message': 'Atualizado com sucesso.'
            },
            status=status.HTTP_200_OK)
Exemplo n.º 31
0
def set_tipo_acao_disciplinar(request):
    if request.method == 'POST':
        values = json.loads(request.body.decode('utf-8'))
        tipo_acao_disciplinar_serializer = TipoAcaoDisciplinarSerializer(
            data=values)
        if tipo_acao_disciplinar_serializer.is_valid():
            tipo_acao_disciplinar_serializer.save()
            return JsonResponse(
                {
                    'success': True,
                    'message': 'Tipo de ação disciplinar criado com sucesso.'
                },
                status=status.HTTP_201_CREATED)
        return JsonResponse(
            {
                'success': False,
                'message':
                'Ocorreu um erro ao criar o tipo de ação disciplinar.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        TipoAcaoDisciplinar.objects.get(id=request.DELETE['id']).delete()
        return JsonResponse(
            {
                'success': True,
                'message': 'Tipo de ação disciplinar apagado com sucesso.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        TipoAcaoDisciplinar.objects.filter(id=request.PUT['id']).update(
            TipoAcaoDisciplinar=request.PUT['TipoAcaoDisciplinar'])
        return JsonResponse(
            {
                'success': True,
                'message': 'Atualizado com sucesso.'
            },
            status=status.HTTP_200_OK)
Exemplo n.º 32
0
def set_pontos(request):
    if request.method == 'POST':
        values = json.loads(request.body.decode('utf-8'))
        pontos_serializer = PontosSerializer(data=values)
        if pontos_serializer.is_valid():
            pontos_serializer.save()
            return JsonResponse(
                {
                    'success': True,
                    'message': 'Pontos adicionados com sucesso.'
                },
                status=status.HTTP_201_CREATED)
        return JsonResponse(
            {
                'success': False,
                'message': 'Ocorreu um erro ao adicionar os pontos.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        Pontos.objects.get(id=request.DELETE['id']).delete()
        return JsonResponse(
            {
                'success': True,
                'message': 'Ponto apagado com sucesso.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        Pontos.objects.filter(id=request.PUT['id']).update(
            Pontos=request.PUT['Pontos'],
            TipoPontuacao=request.PUT['TipoPontuacao'],
            Participante=request.PUT['Participante'])
        return JsonResponse(
            {
                'success': True,
                'message': 'Atualizado com sucesso.'
            },
            status=status.HTTP_200_OK)
Exemplo n.º 33
0
def set_participante(request):
    if request.method == 'POST':
        values = json.loads(request.body.decode('utf-8'))
        participante_serializer = ParticipanteSerializer(data=values)
        if participante_serializer.is_valid():
            participante_serializer.save()
            return JsonResponse(
                {
                    'success': True,
                    'message': 'Participante criado com sucesso.'
                },
                status=status.HTTP_201_CREATED)
        return JsonResponse(
            {
                'success': False,
                'message': 'Ocorreu um erro ao criar o participante.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'DELETE':
        Participante.objects.get(id=request.DELETE['id']).delete()
        return JsonResponse(
            {
                'success': True,
                'message': 'Participante apagado com sucesso.'
            },
            status=status.HTTP_200_OK)
    elif request.method == 'PUT':
        Participante.objects.filter(id=request.PUT['id']).update(
            Jogador=request.PUT['Jogador'],
            Equipa=request.PUT['Equipa'],
            Jogo=request.PUT['Jogo'])
        return JsonResponse(
            {
                'success': True,
                'message': 'Atualizado com sucesso.'
            },
            status=status.HTTP_200_OK)
Exemplo n.º 34
0
 def test_regex_url_path_detail(self):
     pk = '1'
     kwarg = '1234'
     response = self.client.get('/regex/{}/detail/{}/'.format(pk, kwarg))
     assert response.status_code == 200
     assert json.loads(response.content.decode('utf-8')) == {'pk': pk, 'kwarg': kwarg}
Exemplo n.º 35
0
 def test_regex_url_path_list(self):
     kwarg = '1234'
     response = self.client.get('/regex/list/{}/'.format(kwarg))
     assert response.status_code == 200
     assert json.loads(response.content.decode('utf-8')) == {'kwarg': kwarg}
Exemplo n.º 36
0
 def test_empty_prefix_detail(self):
     response = self.client.get('/empty-prefix/1/')
     assert response.status_code == 200
     assert json.loads(response.content.decode('utf-8')) == {'uuid': '111', 'text': 'First'}
Exemplo n.º 37
0
 def test_empty_prefix_list(self):
     response = self.client.get('/empty-prefix/')
     assert response.status_code == 200
     assert json.loads(response.content.decode('utf-8')) == [{'uuid': '111', 'text': 'First'},
                                                             {'uuid': '222', 'text': 'Second'}]
 def test_render_queryset_values_list(self):
     o = DummyTestModel.objects.create(name='dummy')
     qs = DummyTestModel.objects.values_list('id', 'name')
     ret = JSONRenderer().render(qs)
     data = json.loads(ret.decode('utf-8'))
     self.assertEqual(data, [[o.id, o.name]])
Exemplo n.º 39
0
    def test_loads(self):
        with self.assertRaises(ValueError):
            json.loads("Infinity")

        with self.assertRaises(ValueError):
            json.loads("NaN")