Beispiel #1
0
 def test_field_to_native_request_POST(self):
     request = Request(self.factory.post('/'))
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = TranslationSerializerField()
     field.initialize(mock_serializer, 'name')
     self._test_expected_dict(field)
Beispiel #2
0
    def __init__(self, *args, **kwargs):
        Serializer.__init__(self, *args, **kwargs)
        ctx = kwargs.get("context", {})
        columns = set(ctx.get("columns", []))
        queries = ctx.get("queries", [])

        if ctx.get('minimal'):
            for fn in list(self.fields):
                if fn != 'id' and fn not in columns:
                    del self.fields[fn]

        for column in columns:
            if column not in self.fields:
                self.fields[column] = CharField()

        if "hits" in columns and queries:
            for q in queries:
                self.fields[q.label] = ScoreField()

        if "text" in columns:
            self.fields['text'] = CharField()

        if "projectid" in columns:
            self.fields['projectid'] = IntegerField()

        if "lead" in columns:
            self.fields['lead'] = HighlightField()

        if "kwic" in columns:
            self.fields['left'] = KWICField(kwic='left')
            self.fields['keyword'] = KWICField(kwic='keyword')
            self.fields['right'] = KWICField(kwic='right')
Beispiel #3
0
 def test_field_to_native_request_GET(self):
     request = Request(self.factory.get('/'))
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     field.initialize(mock_serializer, 'name')
     self._test_expected_dict(field)
Beispiel #4
0
    def post(self, request):
        Serializer = UserSerializer(data=request.data)
        if Serializer.is_valid(raise_exception=True):
            Serializer.save()

            # generate a token and login
            email = request.data['email']
            password = request.data['password']
            user = User.objects.filter(email=email).first()
            payload = {
                'id': user.id,
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
                'iat': datetime.datetime.utcnow()
            }
            token = jwt.encode(payload, 'secret',algorithm='HS256').decode('utf-8')

            response = Response({}, status=status.HTTP_200_OK)

            response.set_cookie(key='jwt', value=token, httponly=True)
            response.data = {
                'jwt': token,
                'id': user.id
            }
            return response
        return Response(Serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #5
0
 def test_field_to_native_request_POST(self):
     request = Request(self.factory.post('/'))
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = TranslationSerializerField()
     field.initialize(mock_serializer, 'name')
     self._test_expected_dict(field)
Beispiel #6
0
 def test_field_to_native_request_GET(self):
     request = Request(self.factory.get("/"))
     mock_serializer = Serializer()
     mock_serializer.context = {"request": request}
     field = TranslationSerializerField()
     field.initialize(mock_serializer, "name")
     self._test_expected_dict(field)
Beispiel #7
0
 def test_field_to_native_request_GET(self):
     request = Request(self.factory.get('/'))
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     field.initialize(mock_serializer, 'name')
     self._test_expected_dict(field)
Beispiel #8
0
    def register(s, f):
        Serializer = serializers.LoginSerializer(data=f.POST)
        if Serializer.is_valid(raise_exception=True):
            Serializer.save()
            return response.Response(Serializer.data)

        else:
            return response.Response(Serializer.errors)
Beispiel #9
0
 def test_moves_field_under_new_name(self):
     serializer = Serializer()
     field = CharField()
     serializer.fields['foo'] = field
     rename_serializer_field(serializer, 'foo', 'bar')
     with self.assertRaises(KeyError):
         _ = serializer.fields['foo']
     self.assertEqual(field, serializer.fields['bar'])
Beispiel #10
0
 def post(self, request, format='json'):
     Serializer = UserSerializer(data=request.data) #serializer object
     if Serializer.is_valid():
         user = Serializer.save()
         if user:
             return Response(Serializer.data, status=status.HTTP_201_CREATED)
     
     return Response(Serializer.errors, status=status.HTTP_400_BAD_REQUEST) #handles the bad request
Beispiel #11
0
    def perform_create(self, serializer: Serializer):
        if serializer.is_valid():
            password = serializer.validated_data.get('password')
            new_user = serializer.save()
            new_user.set_password(password)
            new_user.save()
            return Response(serializer.data, status.HTTP_201_CREATED)

        super().perform_create(serializer)
Beispiel #12
0
 def post(self, request, user_id, advisor_id):
     recieved_data = request.data
     recieved_data["advId"] = advisor_id
     recieved_data["userId"] = user_id
     Serializer = BookingSerializer(data=recieved_data)
     if Serializer.is_valid():
         Serializer.save()
         return Response(None, status=status.HTTP_200_OK)
     return Response(Serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #13
0
 def post(self, request):
     Serializer = AdvisorSerializer(data=request.data)
     if Serializer.is_valid():
         Serializer.save()
         test_res = {}
         test_res["name"] = Serializer.data["name"]
         test_res["picture_url"] = Serializer.data["picture_url"]
         return Response(test_res, status=status.HTTP_200_OK)
     return Response(Serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #14
0
    def generic_verify_url(self):

        serializer = Serializer(settings.SECRET_KEY, 3600)

        # 加载用户信息
        token = serializer.dumps({'user_id': self.id, 'email': self.email})
        # 注意拼接的过程中对 token进行decode操作
        verify_url = 'http://www.meiduo.site:8080/success_verify_email.html?token=' + token.decode()

        return verify_url
Beispiel #15
0
 def perform_create(self, serializer: Serializer) -> None:
     try:
         message, signature = extract_authorization_components(self.request)
         address = extract_address_from_authorization(message, signature)
     except Exception:
         logger.exception('Failure processing credentials')
         raise APIException('Invalid credentials')
     if serializer.validated_data['address'] != address:
         raise ValidationError('Addresses do not match')
     serializer.save()
Beispiel #16
0
 def __init__(self, *args, **kwargs):
     Serializer.__init__(self, *args, **kwargs)
     ctx = kwargs.get("context", {})
     columns = ctx.get("columns", [])
     queries = ctx.get("queries", None)
     
     if "hits" in columns and queries:
         for q in queries:
             self.fields[q.label] = ScoreField()
     if "text" in columns:
         self.fields['text'] = CharField()
     if "lead" in columns:
         self.fields['lead'] = HighlightField()
Beispiel #17
0
        def __init__(self, *args, **kwargs):
            Serializer.__init__(self, *args, **kwargs)
            ctx = kwargs.get("context", {})
            columns = ctx.get("columns", [])
            queries = ctx.get("queries", None)

            if "hits" in columns and queries:
                for q in queries:
                    self.fields[q.label] = ScoreField()
            if "text" in columns:
                self.fields['text'] = CharField()
            if "lead" in columns:
                self.fields['lead'] = HighlightField()
Beispiel #18
0
 def perform_update(self, serializer: Serializer):
     serializer.is_valid(raise_exception=True)
     if serializer.validated_data['is_default']:
         # default may change
         previous_instance = self.get_object()  # Currency
         if not previous_instance.is_default:
             # default currency is changing, adjusting exchange rates
             rate_to_old_default = previous_instance.rate
             for currency in Currency.objects.all():
                 currency.rate = currency.rate / rate_to_old_default
                 currency.is_default = currency.code == previous_instance.code
                 currency.save()
     else:
         super().perform_update(serializer)
Beispiel #19
0
    def extract_id_field(self, fields, serializer: serializers.Serializer):
        # Included in fields and explicitly named "id"
        if 'id' in fields:
            serializer_id = fields['id']
            model_pk = get_serializer_model_primary_key(serializer)
            if model_pk and model_pk.name != 'id' and get_field_by_source(
                    fields.values(), model_pk.name):
                raise JSONAPIDeclarationError(
                    'if serializer includes primary key it cannot define other field as id'
                )
            return serializer_id

        if not isinstance(serializer, serializers.ModelSerializer):
            return None

        # Included in fields, but not as "id", find by model primary key
        model_pk = get_serializer_model_primary_key(serializer)
        serializer_id = get_field_by_source(fields.values(), model_pk.name)
        if serializer_id:
            return serializer_id

        # Not included in fields, create "temporary" field based on model primary key
        id_field_class, id_field_kwargs = serializer.build_standard_field(
            'id', model_pk)
        serializer_id: serializers.Field = id_field_class(
            **id_field_kwargs,
            source=model_pk.name if model_pk.name != 'id' else None)
        # NOTE: emulating binding, this is one-way binding
        # This field is safe to use and pass anywhere, but it won't be visible from serializer
        serializer_id.bind('id', serializer)
        return serializer_id
Beispiel #20
0
def api_paging(objs, request, Serializer):
    """
    objs : 实体对象
    request : 请求对象
    Serializer : 对应实体对象的序列化
    """
    try:
        page_size = int(request.GET.get('page_size', 2))
        page = int(request.GET.get('page', 1))
    except (TypeError, ValueError):
        return JsonResponse(
            code=status.HTTP_400_BAD_REQUEST,
            desc='page and page_size must be integer!'
        )

    paginator = Paginator(objs, page_size) # paginator对象
    total = paginator.num_pages #总页数
    try:
        objs = paginator.page(page)
    except PageNotAnInteger:
        objs = paginator.page(1)
    except EmptyPage:
        objs = paginator.page(paginator.num_pages)

    serializer = Serializer(objs, many=True) #序列化操作

    return JsonResponse(
        data={
            'detail': serializer.data,
            'page': page,
            'total': total
        },
        code=status.HTTP_200_OK,
        desc='page success'
    ) #返回
Beispiel #21
0
 def test_field_to_native_request_GET_lang(self):
     """
     Pass a lang in the query string, expect to have a single string
     returned instead of an object.
     """
     # Note that we don't go through the middlewares etc so the actual
     # language for the process isn't changed, we don't care as
     # _expect_single_string() method simply tests with the current language,
     # whatever it is.
     request = Request(self.factory.get('/', {'lang': 'lol'}))
     eq_(request.GET['lang'], 'lol')
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     field.initialize(mock_serializer, 'name')
     self._test_expected_single_string(field)
Beispiel #22
0
 def setUp(self):
     self.field = UserField()
     self.serializer = Serializer(context={
         'request': APIRequestFactory().get('/'),
     })
     self.field.bind('user', self.serializer)
     self.user = UserFactory()
Beispiel #23
0
 def test_field_to_native_request_GET_lang(self):
     """
     Pass a lang in the query string, expect to have a single string
     returned instead of an object.
     """
     # Note that we don't go through the middlewares etc so the actual
     # language for the process isn't changed, we don't care as
     # _expect_single_string() method simply tests with the current language,
     # whatever it is.
     request = Request(self.factory.get("/", {"lang": "lol"}))
     eq_(request.GET["lang"], "lol")
     mock_serializer = Serializer()
     mock_serializer.context = {"request": request}
     field = TranslationSerializerField()
     field.initialize(mock_serializer, "name")
     self._test_expected_single_string(field)
Beispiel #24
0
 def test_field_to_native_request_GET_lang(self):
     """
     Pass a lang in the query string, expect to have a single string
     returned instead of an object.
     """
     # Note that we don't go through the middlewares etc so the actual
     # language for the process isn't changed, we don't care as
     # _expect_single_string() method simply tests with the current
     # language, whatever it is.
     request = Request(self.factory.get('/', {'lang': 'lol'}))
     eq_(request.GET['lang'], 'lol')
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     field.initialize(mock_serializer, 'name')
     self._test_expected_single_string(field)
Beispiel #25
0
def horseview(request, horsename=None):
    try:
        horse_ = de_sluggify(horsename)
        queryset = Horse.objects.filter(horses__contains=[horse_])
        serializer = Serializer(queryset, many=True)
        return Response(serializer.data)
    except:
        raise Http404("Whoops... Try again")
Beispiel #26
0
def predict_results(request, pk=None):
    race = get_object_or_404(Horse.objects.filter(category='TCR', pk=pk))
    try:
        race.results = RacePredictor(race.horses)
        serializer = Serializer(race, many=False)
    except:
        raise Http404("Whoops... try again")
    return Response(serializer)
Beispiel #27
0
 def get_last_message(self, instance):
     try:
         last_message = instance.messages.select_related('user', 'chat').prefetch_related('images', 'user__images')\
                 .latest('date_created')
     except Message.DoesNotExist:
         last_message = None
     return MessageSerializer(
         last_message).data if last_message else Serializer(None).data
Beispiel #28
0
    def generic_user_info(self,token):

        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            result = serializer.loads(token)
        except BadData:
            return None
        else:
            id = result.get('id')
            email = result.gte('email')

            try:
                user = User.objects.grt(id=id,email=email)
            except User.DoesNotExist:
                 return None
            else:
                return user
Beispiel #29
0
 def to_representation(self, instance):
     """flatten recipe"""
     recipe = Serializer.to_representation(self, instance)
     if 'ingredients' in recipe:
         flattened_recipe = dict(**recipe['recipe'],
                                 ingredients=recipe['ingredients'])
     else:
         flattened_recipe = dict(**recipe['recipe'])
     return flattened_recipe
Beispiel #30
0
def results(request, pk=None):
    try:
        race = get_object_or_404(Race.objects.all(), pk=pk)
        assert (race['category'] in ['Pre', 'Past'])
    except:
        raise Http404("We don't have results for that race")

    serializer = Serializer(race, many=False)
    return Response(serializer.data)
Beispiel #31
0
def category(request, cat=None):
    try:
        assert (cat in Race.CATEGORY_CHOICES)
    except:
        raise Http404("Whoops... Try again")
    else:
        queryset = Race.objects.filter(category=cat)
        serializer = Serializer(queryset, many=True)
        return Response(serializer.data)
Beispiel #32
0
def from_serializer(
    serializer: serializers.Serializer,
    api_type: str,
    *,
    id_field: str = "",
    **kwargs: Any,
) -> Type[ResourceObject]:
    """
    Generate a schema from a DRF serializer.

    :param serializer: The serializer instance.
    :param api_type: The JSON API resource type.
    :param id_field: The 'id" field of the resource.
        If left empty, it is either "id" for non-model serializers, or
        for model serializers, it is looked up on the model.
    :param kwargs: Extra options (like links and transforms) passed to the schema.
    :return: The new schema class.
    """

    # get_fields() should return them in the order of Meta.fields
    serializer_name = type(serializer).__name__

    attrs: List[str] = []
    rels: List[str] = []

    if not id_field:
        # If this is a model serializer, we can reach in to the model
        # and look for the model's PK.
        if isinstance(serializer, serializers.ModelSerializer):
            model = serializer.Meta.model
            for db_field in model._meta.get_fields():
                if getattr(db_field, "primary_key", False):
                    id_field = db_field.attname
                    break

            if not id_field:
                raise ValueError(
                    f"Unable to find primary key from model: {model}")
        else:
            # Otherwise, just assume it's "id"
            id_field = "id"

    for field_name, field in serializer.get_fields().items():
        if field_name != id_field:
            if isinstance(field, serializers.RelatedField):
                rels.append(field_name)
            else:
                attrs.append(field_name)

    values: Dict[str, Any] = {
        "id": id_field,
        "type": api_type,
        "attributes": attrs,
        "relationships": rels,
    }
    values.update(**kwargs)
    return type(f"{serializer_name}_AutoSchema", (ResourceObject, ), values)
Beispiel #33
0
 def perform_update(self, serializer: Serializer) -> None:
     instance = serializer.save()
     if not self.AUDITOR_EVENT_TYPES:
         return instance
     event_type = self.AUDITOR_EVENT_TYPES.get('UPDATE')
     if event_type and is_user(self.request.user):
         auditor.record(event_type=event_type,
                        instance=instance,
                        actor_id=self.request.user.id,
                        actor_name=self.request.user.username)
Beispiel #34
0
 def to_internal_value(self, data):
     """split into recipe and ingredients"""
     new_recipe = {
         'recipe': {
             key: value
             for (key, value) in data.items() if key != 'ingredients'
         }
     }
     if 'ingredients' in data:
         new_recipe['ingredients'] = data['ingredients']
     return Serializer.to_internal_value(self, new_recipe)
Beispiel #35
0
    def perform_update(self, serializer: Serializer):
        if serializer.is_valid(raise_exception=True):
            previous_instance = self.get_object()  # type: Domain
            registration_period = serializer.validated_data[
                'registration_period']

            if registration_period and registration_period != previous_instance.registration_period:
                # registration period changed, update price cycle
                service = previous_instance.service
                new_cycle = service.product.cycles.filter(
                    cycle_multiplier=registration_period).first()

                if new_cycle:
                    service.cycle = new_cycle
                    service.save()
                else:
                    raise ValidationError({
                        'registration_period':
                        _('No price defined for this registration period. Check TLD pricing'
                          )
                    })

            new_name = serializer.validated_data['name']
            if new_name and new_name != previous_instance.name:
                if not DomainUtils.validate_domain_name(domain_name=new_name):
                    raise ValidationError({'name': _('Invalid domain name')})

                try:
                    new_tld_name = DomainUtils.get_tld_name(new_name)
                except ValueError:
                    new_tld_name = None

                if previous_instance.tld.name != new_tld_name:
                    raise ValidationError({
                        'name':
                        _('New domain name should have the same TLD({})').
                        format(previous_instance.tld.name)
                    })

            serializer.save()
Beispiel #36
0
    def __init__(self, *args, **kwargs):
        Serializer.__init__(self, *args, **kwargs)
        ctx = kwargs.get("context", {})
        columns = set(ctx.get("columns", []))
        if not columns:
            columns = self.default_columns
        queries = ctx.get("queries", [])
        if ctx.get('minimal'):
            for fn in list(self.fields):
                if fn != 'id' and fn not in columns:
                    del self.fields[fn]


        for column in columns:
            if column not in self.fields:
                self.fields[column] = CharField()

        if "hits" in columns and queries:
            for q in queries:
                self.fields[q.label] = ScoreField()

        if "text" in columns:
            self.fields['text'] = CharField()

        if "date" in columns:
            self.fields['date'] =  DateTimeField(input_formats=("iso-8601",))

        if "projectid" in columns:
            self.fields['projectid'] = IntegerField()

        if "lead" in columns:
            self.fields['lead'] = HighlightField()

        if "kwic" in columns:
            self.fields['left'] = KWICField(kwic='left')
            self.fields['keyword'] = KWICField(kwic='keyword')
            self.fields['right'] = KWICField(kwic='right')
def _get_serializers_to_check(
    include_apps: Optional[Iterable[str]] = None,
) -> Tuple[Iterator[Type[Serializer]], Iterator[Type[ModelSerializer]]]:
    serializer_classes = _filter_app_serializers(
        _collect_serializers(s for s in Serializer.__subclasses__()
                             if s is not ModelSerializer  # type: ignore
                             ),
        include_apps,
    )
    model_serializer_classes = _filter_app_serializers(
        _collect_serializers(ModelSerializer.__subclasses__()), include_apps)
    return (
        serializer_classes,
        cast(Iterator[Type[ModelSerializer]], model_serializer_classes),
    )
Beispiel #38
0
    def __init__(self, *args, **kwargs):
        Serializer.__init__(self, *args, **kwargs)
        ctx = kwargs.get("context", {})
        columns = ctx.get("columns", [])
        queries = ctx.get("queries", [])

        if ctx.get('minimal'):
            for fn in list(self.fields):
                if fn != 'id' and fn not in list(columns):
                    del self.fields[fn]

        if "hits" in columns and queries:
            for q in queries:
                self.fields[q.label] = ScoreField()
        if "text" in columns:
            self.fields['text'] = CharField()
        if "projectid" in columns:
            self.fields['projectid'] = IntegerField()
        if "lead" in columns:
            self.fields['lead'] = HighlightField()
        if "kwic" in columns:
            self.fields['left'] = KWICField(kwic='left')
            self.fields['keyword'] = KWICField(kwic='keyword')
            self.fields['right'] = KWICField(kwic='right')
Beispiel #39
0
 def __init__(self, *args, **kwargs):
     Serializer.__init__(self, *args, **kwargs)
     for x in kwargs["context"]["axes"]:
         self.fields[x] = CharField()
Beispiel #40
0
 def test_field_to_native_empty_context(self):
     mock_serializer = Serializer()
     mock_serializer.context = {}
     field = self.field_class()
     self._test_expected_dict(field, mock_serializer)
Beispiel #41
0
 def test_field_to_native_request_POST(self):
     request = Request(self.factory.post('/'))
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     self._test_expected_dict(field)
Beispiel #42
0
 def test_field_to_native_empty_context(self):
     mock_serializer = Serializer()
     mock_serializer.context = {}
     field = TranslationSerializerField()
     field.initialize(mock_serializer, "name")
     self._test_expected_dict(field)
Beispiel #43
0
 def test_get_attribute_empty_context(self):
     mock_serializer = Serializer()
     mock_serializer.context = {}
     field = self.field_class()
     self._test_expected_dict(field, mock_serializer)
Beispiel #44
0
 def test_get_attribute_request_GET(self):
     request = Request(self.factory.get('/'))
     mock_serializer = Serializer()
     mock_serializer.context = {'request': request}
     field = self.field_class()
     self._test_expected_dict(field)
Beispiel #45
0
 def test_field_to_native_empty_context(self):
     mock_serializer = Serializer()
     mock_serializer.context = {}
     field = self.field_class()
     field.initialize(mock_serializer, 'name')
     self._test_expected_dict(field)