예제 #1
0
class TasksFilter(filters.BaseFilterBackend):
    """Return tasks that satisfy given constraints"""

    template = os.path.join('celery_pantry', 'tasks_filter.html')
    schema = [
        coreapi.Field(
            name='with_data',
            required=False,
            location='query',
            schema=coreschema.Object(description='Data users must have',
                                     min_properties=1)),
        coreapi.Field(name='without_data',
                      required=False,
                      location='query',
                      schema=coreschema.Object(
                          description='Data users must not have',
                          min_properties=1)),
    ]

    @staticmethod
    def _filter__with_data(queryset, value):
        return queryset.filter(data__contains=json.loads(value))

    @staticmethod
    def _filter__without_data(queryset, value):
        return queryset.exclude(data__contains=json.loads(value))

    def filter_queryset(self, request, queryset, view):
        if view.action == 'list':
            for key, value in request.query_params.items():
                if value:
                    try:
                        filter_func = getattr(self, f'_filter__{key}')
                        queryset = filter_func(queryset, value)
                    except AttributeError:
                        continue
        return queryset

    def to_html(self, request, queryset, view) -> str:
        template = loader.get_template(self.template)
        context = self.get_template_context(request)
        return template.render(context)

    def get_template_context(self, request):
        return dict(
            conditions={
                field.name: request.query_params.get(field.name, '')
                for field in self.schema
            })
예제 #2
0
 def coreapi_schema(self):
     if self.request.method == 'GET':
         fields = [
             coreapi.Field("name",
                           required=False,
                           location="query",
                           schema=coreschema.String(max_length=30)),
             coreapi.Field("name_contains",
                           required=False,
                           location="query",
                           schema=coreschema.String(max_length=30))
         ]
     elif self.request.method == 'POST':
         fields = [
             coreapi.Field("params",
                           required=True,
                           location="body",
                           schema=coreschema.Object())
         ]
     else:
         fields = [
             coreapi.Field("name",
                           required=True,
                           location="body",
                           schema=coreschema.String(max_length=30))
         ]
     return schemas.ManualSchema(fields=fields)
예제 #3
0
class DumpFixtureAPIView(generics.CreateAPIView):
    permission_classes = (SuperuserRequiredPermission, )
    schema = schemas.ManualSchema(fields=[
        coreapi.Field("app_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=10)),
        coreapi.Field("model_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=50)),
        coreapi.Field("filter_options",
                      required=False,
                      location="form",
                      schema=coreschema.Object()),
        coreapi.Field("file_name",
                      required=True,
                      location="form",
                      schema=coreschema.String(max_length=50)),
    ])

    def post(self, request, *args, **kwargs):
        """
        Download model fixture
        """
        serializer = DumpFixtureSerializer(data=request.data)
        if not serializer.is_valid():
            return Response('Data is not valid')
        form_data = serializer.data
        file_name = form_data.pop('file_name')
        json_data = get_model_fixture_dump(**form_data)
        return download(json_data, file_name)
예제 #4
0
def form_for_link(link):
    import coreschema
    properties = OrderedDict([(field.name, field.schema or coreschema.String())
                              for field in link.fields])
    required = [field.name for field in link.fields if field.required]
    schema = coreschema.Object(properties=properties, required=required)
    return mark_safe(coreschema.render_to_form(schema))
예제 #5
0
class WebsiteReportFailure(viewsets.ViewSet):
    serializer_class = WebsiteReportingSerializer
    schema = AutoSchema(manual_fields=[
        coreapi.Field(
            "errors",
            location="body",
            schema=coreschema.Array(
                items=coreschema.Object(
                    properties={},
                    title="Error",
                )
            )
        ),
    ])

    @decorators.action(detail=True, methods=['post'])
    def report_failure(self, request, version, website_id=None):
        website: Website = Website.objects.filter(id=website_id).first()
        errors = request.data if isinstance(request.data, list) else []
        message = render_to_string('reporting_email.html', {'errors': errors, 'website': website})

        if not website.notification_sent_date \
                or website.notification_sent_date < timezone.now() - timedelta(seconds=website.notification_cooldown):
            website.notification_sent_date = datetime.now()
            website.save()
            send_mail(
                f'SeoSnap Reporting - {website.name}',
                message,
                os.getenv('ADMIN_EMAIL', '*****@*****.**'),
                [website.notification_email],
                fail_silently=False,
                html_message=message
            )

        return Response([])
예제 #6
0
 def render_form(link: coreapi.Link) -> str:
     properties = dict([
         (field.name, field.schema or coreschema.String())
         for field in link.fields
     ])
     required = []  # type: typing.List[str]
     schema = coreschema.Object(properties=properties, required=required)
     return coreschema.render_to_form(schema)
예제 #7
0
 def get_manual_fields(self, path, method):
     if method not in ['POST', 'PUT', 'PATCH']:
         return []
     return [
         coreapi.Field("data",
                       required=False,
                       location="form",
                       schema=coreschema.Object())
     ]
예제 #8
0
 def get_schema_fields(self, view):
     fields = super(PaymentFilterBackend, self).get_schema_fields(view)
     extra_fields = [
         coreapi.Field(
             name="created_before",
             location="query",
             required=False,
             schema=coreschema.Object(),
         ),
         coreapi.Field(
             name="created_after",
             location="query",
             required=False,
             schema=coreschema.Object(),
         ),
     ]
     fields.extend(extra_fields)
     return fields
예제 #9
0
def test_ref():
    child = coreschema.Object(properties={
        'a': coreschema.String(),
        'b': coreschema.Integer()
    })
    schema = coreschema.Ref('Child')
    context = {'refs': {'Child': child}}

    assert schema.validate({'a': 'abc', 'b': 123}, context) == []
    assert schema.validate({
        'a': 'abc',
        'b': 'abc'
    }, context) == [('Must be an integer.', ['b'])]
예제 #10
0
    def fallback_schema_from_field(self, field):
        """ Fallback schema for field that isn't inspected properly by DRF
        and probably won't land in upstream canon due to its hacky nature only for doc purposes
        """
        title = force_text(field.label) if field.label else ''
        description = force_text(field.help_text) if field.help_text else ''

        # since we can't really inspect dictfield and jsonfield, at least display object as type
        # instead of string
        if isinstance(field, (serializers.DictField, serializers.JSONField)):
            return coreschema.Object(properties={},
                                     title=title,
                                     description=description)
예제 #11
0
class ServiceAreaViewSet(viewsets.ModelViewSet):
    permission_classes = (ServiceAreaPermissions, )
    queryset = ServiceArea.objects
    instance_class = ServiceArea
    lookup_field = '_id'

    schema = MongoSchema(manual_fields=[
        MethodField(
            "body",
            required=True,
            location="body",
            schema=coreschema.Object(),
            methods=['POST', 'PUT', 'PATCH'],
        ),
        MethodField(
            "lat",
            required=False,
            location="query",
            schema=coreschema.Number(),
            methods=['GET'],
        ),
        MethodField(
            "lng",
            required=False,
            location="query",
            schema=coreschema.Number(),
            methods=['GET'],
        ),
    ])

    def filter_queryset(self, queryset):
        if 'lat' in self.request.query_params and 'lng' in self.request.query_params:
            lat = float(self.request.query_params['lat'])
            lng = float(self.request.query_params['lng'])

            return queryset.raw({
                'geometry': {
                    '$geoIntersects': {
                        '$geometry': {
                            'type': 'Point',
                            'coordinates': [lat, lng]
                        }
                    }
                }
            })
        else:
            return queryset

    def perform_create(self, instance):
        instance.user_id = self.request.user.pk
        super(ServiceAreaViewSet, self).perform_create(instance)
예제 #12
0
    def fallback_schema_from_field(self, field):

        import coreschema
        # Using django default `force_text` instead of inconsistent drf_openapi
        from django.utils.encoding import force_text

        title = force_text(field.label) if field.label else ''
        description = force_text(field.help_text) if field.help_text else ''

        if isinstance(field, (serializers.DictField, serializers.JSONField)):
            return coreschema.Object(properties={},
                                     title=title,
                                     description=description)

        return None
예제 #13
0
class PageWebsiteUpdate(viewsets.ViewSet):
    schema = AutoSchema(manual_fields=[
        coreapi.Field("items",
                      location="body",
                      schema=coreschema.Array(items=coreschema.Object(
                          properties={},
                          title="Page",
                          description="Page",
                      ))),
    ])

    @decorators.action(detail=True, methods=['put'])
    def update_pages(self, request, version, website_id=None):
        website = Website.objects.filter(id=website_id).first()
        allowed = request.user.has_perm('seosnap.view_website', website)
        if not allowed or not website: return Response([])

        items = request.data if isinstance(request.data, list) else []
        addresses = [item['address'] for item in items if 'address' in item]

        existing = {
            page.address: page
            for page in Page.objects.filter(address__in=addresses,
                                            website_id=website_id)
        }
        allowed_fields = set(PageSerializer.Meta.fields) - set(
            PageSerializer.Meta.read_only_fields)
        for item in items:
            item = {k: item[k] for k in allowed_fields if k in item}
            if item['address'] in existing:
                page = existing[item['address']]
                for k, v in item.items():
                    setattr(page, k, v)
            else:
                existing[item['address']] = Page(**item)

        with transaction.atomic():
            cache_updated_at = website.cache_updated_at
            for page in existing.values():
                page.website_id = website_id
                cache_updated_at = page.cached_at
                page.save()
            website.cache_updated_at = cache_updated_at
            website.save()

        serializer = PageSerializer(list(existing.values()), many=True)
        return Response(serializer.data)
예제 #14
0
 def schema(self):
     field_name = "params"
     location = "body"
     required = True
     schema = coreschema.String(max_length=30)
     if self.request.method == 'GET':
         field_name = "name"
         location = "query"
         required = False
     elif self.request.method == 'POST':
         schema = coreschema.Object()
     return schemas.ManualSchema(fields=[
         coreapi.Field(field_name,
                       required=required,
                       location=location,
                       schema=schema)
     ])
    def add_object_definitions(self, method, view):
        """Create an Object definition from serializer
        It will create a different definitions depending on the method, definition name is
        {serializer class name}_{read|write}
        POST, PUT, PATCH is write
        GET, DELETE, HEAD is read
        write methods will not include read only fields
        read methods will not include write only fields
        Note that for write methods it will also return a read definition because by default this is the definition
        object returned by write methods
        :param str method: GET, POST etc
        :param rest_framework.generics.GenericAPIView view:
        """
        if not hasattr(view, 'get_serializer'):
            return None
        try:
            serializer = view.get_serializer()
        except AssertionError:  # Default behaviour of GenericAPIView is to raise AssertionError
            return None
        if method in ('POST', 'PUT', 'PATCH'):
            write = True
            # also generate a read definition, because it is commonly used as response for write actions
            self.add_object_definitions('GET', view)
            name = '%s_write' % serializer.__class__.__name__
        elif method in ('GET', 'DELETE', 'HEAD'):
            write = False
            name = '%s_read' % serializer.__class__.__name__
        else:
            assert False, 'Can not recognize method %s' % method
        if name in self.definitions:
            return
        fields = []
        for field in serializer.fields.values():
            if isinstance(field, serializers.HiddenField) or write and field.read_only or \
                            not write and field.write_only:
                continue

            # required = bool(field.required)  # field.required is a list
            field = field_to_schema(field)
            fields.append(field)

        self.definitions[name] = coreschema.Object(title=name,
                                                   properties=fields)
        return self.definitions[name]
예제 #16
0
    def field_to_schema(self, field):
        import coreschema
        import django.forms as django_forms
        from django.utils.encoding import force_str
        title = force_str(field.label) if field.label else ''
        description = force_str(field.help_text) if field.help_text else ''

        schema = None

        if isinstance(field, django_forms.MultipleChoiceField):
            schema = coreschema.Array(
                items=coreschema.Enum(enum=list(field.choices)),
                title=title,
                description=description)
        elif isinstance(field, django_forms.ChoiceField) and not isinstance(
                field, django_forms.ModelChoiceField):
            choices = list(
                map(
                    lambda choice: choice[0]
                    if isinstance(choice, tuple) else choice, field.choices))
            choices.remove('')
            schema = coreschema.Enum(enum=choices,
                                     title=title,
                                     description=description)
        elif isinstance(field, django_forms.BooleanField):
            schema = coreschema.Boolean(title=title, description=description)
        elif isinstance(field,
                        (django_forms.DecimalField, django_forms.FloatField)):
            schema = coreschema.Number(title=title, description=description)
        elif isinstance(field, django_forms.IntegerField):
            schema = coreschema.Integer(title=title, description=description)
        elif isinstance(field, django_forms.DateField):
            schema = coreschema.String(title=title,
                                       description=description,
                                       format='date')
        elif isinstance(field, django_forms.DateTimeField):
            schema = coreschema.String(title=title,
                                       description=description,
                                       format='date-time')
        elif isinstance(field, django_forms.JSONField):
            schema = coreschema.Object(title=title, description=description)

        return schema or coreschema.String(title=title,
                                           description=description)
예제 #17
0
def render_form(link):
    properties = dict([(field.name, field.schema or coreschema.String())
                       for field in link.fields])
    required = []
    schema = coreschema.Object(properties=properties, required=required)
    return coreschema.render_to_form(schema)
예제 #18
0
파일: views.py 프로젝트: pfroad/lfd
from frontend import common
from frontend.common import Result
from frontend.settings import DEBUG
from msg.models import SmsCode
from user.models import User


@api_view(['POST'])
@schema(
    AutoSchema(manual_fields=[
        coreapi.Field(
            'data',
            location='body',
            schema=coreschema.Object(
                description=
                '{"mobile": "176666622222","verify_code(optional)":"5462"}'),
            required=True),
        # coreapi.Field('verifyCode', location='form', schema=coreschema.String(description='verifyCode(optional)'))
    ]))
def sms_reg(request):
    data = request.data

    code = random.randint(100000, 999999)
    send_code(data["mobile"], code)

    if DEBUG:
        result = Result(data=code)
    else:
        result = Result()
    return Response(json.dumps(result))
예제 #19
0
파일: schema.py 프로젝트: xunyuw/ECS
        "user_name",
        required=False,
        location="form",  #form
        schema=coreschema.String(),
        # schema=coreschema.String(),
        description="用户名称",
    ),
])

PermissionUpdateSchema = AutoSchema([
    # token_field,
    coreapi.Field(
        "permission",
        required=True,
        location="form",  # from,query,url
        schema=coreschema.Object(),
        # schema=coreschema.String(),
        description="权限",
    ),
])

UserUpdateSchema = AutoSchema([
    # token_field,
    coreapi.Field(
        "user",
        required=True,
        location="form",  # from,query,url
        schema=coreschema.Object(),
        # schema=coreschema.String(),
        description="用户",
    ),
예제 #20
0
 coreschema.Object(
     properties={
         # Meta
         "id":
         coreschema.String(format="uri"),
         "$schema":
         coreschema.String(format="uri"),
         "title":
         coreschema.String(),
         "description":
         coreschema.String(),
         "default":
         coreschema.Anything(),
         "definitions":
         coreschema.Ref("SchemaMap"),
         # Type
         "type":
         coreschema.Ref("SimpleTypes")
         | coreschema.Array(items=coreschema.Ref("SimpleTypes"),
                            min_items=1,
                            unique_items=True),
         # Number validators
         "minimum":
         coreschema.Number(),
         "maximum":
         coreschema.Number(),
         "exclusiveMinimum":
         coreschema.Boolean(default=False),
         "exclusiveMaximum":
         coreschema.Boolean(default=False),
         "multipleOf":
         coreschema.Number(minimum=0, exclusive_minimum=True),
         # String validators
         "minLength":
         coreschema.Integer(minimum=0, default=0),
         "maxLength":
         coreschema.Integer(minimum=0),
         "pattern":
         coreschema.String(format="regex"),
         "format":
         coreschema.String(),
         # Array validators
         "items":
         coreschema.Ref("Schema")
         | coreschema.Ref("SchemaArray"),  # TODO: default={}
         "additionalItems":
         coreschema.Boolean()
         | coreschema.Ref("Schema"),  # TODO: default={}
         "minItems":
         coreschema.Integer(minimum=0, default=0),
         "maxItems":
         coreschema.Integer(minimum=0),
         "uniqueItems":
         coreschema.Boolean(default=False),
         # Object validators
         "properties":
         coreschema.Ref("SchemaMap"),
         "patternProperties":
         coreschema.Ref("SchemaMap"),
         "additionalProperties":
         coreschema.Boolean() | coreschema.Ref("Schema"),
         "minProperties":
         coreschema.Integer(minimum=0, default=0),
         "maxProperties":
         coreschema.Integer(minimum=0),
         "required":
         coreschema.Ref("StringArray"),
         "dependancies":
         coreschema.Object(
             additional_properties=coreschema.Ref("Schema")
             | coreschema.Ref("StringArray")),
         # Enum validators
         "enum":
         coreschema.Array(min_items=1, unique_items=True),
         # Composites
         "allOf":
         coreschema.Ref("SchemaArray"),
         "anyOf":
         coreschema.Ref("SchemaArray"),
         "oneOf":
         coreschema.Ref("SchemaArray"),
         "not":
         coreschema.Ref("Schema"),
     },
     # dependancies=..., TODO
     default={},
 ),
예제 #21
0
                      location='path',
                      schema=coreschema.Integer(
                          description='Identifier of the booking')),
        coreapi.Field(
            name='token',
            required=True,
            location='form',
            schema=coreschema.String(
                description=
                'Temporary authorization token assigned during booking')),
        coreapi.Field(
            name='client_data',
            required=True,
            location='form',
            schema=coreschema.Object(
                description=
                'Client data like first name, last name, email and phone number',
            ))
    ]))
@permission_classes(())
@authentication_classes(())
def replace_client_data(request, booking_id, format=None):
    """
        Removes old and creates new client information instance
    """
    try:
        booking = Booking.objects.get(pk=booking_id)
        check_booking_token(booking, request.data.get('token'))
        client_data = request.data.get('client_data', {})
        client_data['username'] = secrets.token_urlsafe(10)
        serializer = ClientSerializer(data=client_data)
        with transaction.atomic():
예제 #22
0
class FileManagerView(object):
    """
    FileManager View.

    * Requires token authentication.
    * Only authenticated users are able to access this view.
    """
    @staticmethod
    def register():
        return [
            url(r'^fileManager/getMainFolders/$',
                FileManagerView.getMainFolders),
            url(r'^fileManager/getFiles/$',
                FileManagerView.getFoldersAndFiles),
            url(r'^fileManager/createFolder/$', FileManagerView.createFolder),
            url(r'^fileManager/copyFileOrFolder/$',
                FileManagerView.copyFileOrFolder),
            url(r'^fileManager/renameFile/$', FileManagerView.renameFile),
            url(r'^fileManager/duplicateFiles/$',
                FileManagerView.duplicateFiles),
            url(r'^fileManager/moveFiles/$', FileManagerView.moveFiles),
            url(r'^fileManager/copyFiles/$', FileManagerView.copyFiles),
            url(r'^fileManager/copyToMyWorkspace/$',
                FileManagerView.copyToMyWorkspace),
            url(r'^fileManager/deleteFiles/$', FileManagerView.deleteFiles),
            url(r'^fileManager/upload/$', FileManagerView.upload),
            url(r'^fileManager/download/$', FileManagerView.download),
            url(r'^fileManager/unzipFile/$', FileManagerView.unzipFile),
            url(r'^fileManager/zipFiles/$', FileManagerView.zipFiles),
            url(r'^fileManager/getHome/', FileManagerView.getHome),
            url(r'^fileManager/optimizeTemplates/$',
                FileManagerView.optimizeTemplates),
        ]

    @staticmethod
    @api_view(['GET'])
    @permission_required('pyplan.list_folders', raise_exception=True)
    def getMainFolders(request, *args, **kargs):
        """
        list:
        Return a list of all folders.
        """
        try:
            service = FileManagerService(request)
            folders = service.getMainFolders()
            serializer = FileEntrySerializer(
                folders,
                many=True,
                context={'client_session': service.client_session})
            return Response(serializer.data)
        except FileNotFoundError:
            raise exceptions.NotFound('Folder Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field('folder',
                          required=False,
                          location='query',
                          description='folder name'),
        ]))
    @permission_required('pyplan.list_folders', raise_exception=True)
    def getFoldersAndFiles(request, *args, **kargs):
        """
        list:
        Return a list of all folders and files.
        """
        serializer = GetFoldersAndFilesSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        folder = request.query_params.get('folder', '')
        try:
            service = FileManagerService(request)
            files = service.getFoldersAndFiles(folder)
            serializer = FileEntrySerializer(
                files,
                many=True,
                context={'client_session': service.client_session})
            return Response(serializer.data)
        except FileNotFoundError:
            raise exceptions.NotFound('Folder Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['POST'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("data",
                          required=True,
                          location="body",
                          description='{"folder_path":str, "folder_name":str}',
                          schema=coreschema.Object()),
        ]))
    @permission_required('pyplan.add_folder', raise_exception=True)
    def createFolder(request, *args, **kargs):
        """
        create:
        Creates a folder inside provided path.
        """
        serializer = CreateFolderSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            folder_path = serializer['folder_path'].value
            folder_name = serializer['folder_name'].value

            path = FileManagerService().createFolder(folder_path, folder_name)
            return Response({'path': path})
        except FileNotFoundError:
            raise exceptions.NotFound('Folder Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['POST'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("data",
                          required=True,
                          location="body",
                          description='{"folder_path":str, "folder_name":str}',
                          schema=coreschema.Object()),
        ]))
    @permission_required('pyplan.copy_file_or_folder', raise_exception=True)
    def copyFileOrFolder(request, *args, **kargs):
        """
        create:
        Duplicate file or Folder.
        """
        serializer = CopyFileOrFolderSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            source = serializer['source'].value
            destination = serializer['destination'].value
            result = FileManagerService().copyFileOrFolder(source, destination)

            return Response({'path': result})
        except FileNotFoundError:
            raise exceptions.NotFound('Folder Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("source", required=True, location="query"),
            coreapi.Field("newName", required=True, location="query"),
        ]))
    @permission_required('pyplan.copy_file_or_folder', raise_exception=True)
    def renameFile(request, *args, **kargs):
        """
        Rename File
        """
        source = request.query_params.get('source', None)
        new_name = request.query_params.get('newName', None)

        try:
            result = FileManagerService().renameFile(source, new_name)
            return Response({'path': result})
        except FileNotFoundError:
            raise exceptions.NotFound('Folder or File Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources", required=True, location="query"),
        ]))
    @permission_required('pyplan.copy_file_or_folder', raise_exception=True)
    def duplicateFiles(request, *args, **kargs):
        """
        Duplicate Files
        """
        sources = request.query_params.getlist('sources', [])

        try:
            if len(sources) > 0:
                result = FileManagerService().duplicateFiles(sources)
                return Response({'path': result})
            return Response(status=status.HTTP_204_NO_CONTENT)
        except FileNotFoundError:
            raise exceptions.NotFound('Folder or File Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources", required=True, location="query"),
            coreapi.Field("target", required=True, location="query"),
        ]))
    @permission_required('pyplan.copy_file_or_folder', raise_exception=True)
    def moveFiles(request, *args, **kargs):
        """
        Move Files
        """
        sources = request.query_params.getlist('sources', [])
        target = request.query_params.get('target', None)

        try:
            if len(sources) > 0 and target:
                result = FileManagerService().moveFiles(sources, target)
                return Response()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except FileNotFoundError:
            raise exceptions.NotFound('Folder or File Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources", required=True, location="query"),
            coreapi.Field("target", required=True, location="query"),
        ]))
    @permission_required('pyplan.copy_file_or_folder', raise_exception=True)
    def copyFiles(request, *args, **kargs):
        """
        Copy Files
        """
        sources = request.query_params.getlist('sources', [])
        target = request.query_params.get('target', None)

        try:
            if len(sources) > 0 and target:
                result = FileManagerService().copyFiles(sources, target)
                return Response()
            return Response(status=status.HTTP_204_NO_CONTENT)
        except FileNotFoundError:
            raise exceptions.NotFound('Folder or File Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("source", required=True, location="query"),
        ]))
    @permission_required('pyplan.copy_file_or_folder', raise_exception=True)
    def copyToMyWorkspace(request, *args, **kargs):
        """
        Copy to My Workspace
        """
        source = request.query_params.get('source', None)

        try:
            if source:
                result = FileManagerService(request).copyToMyWorkspace(source)
                return Response(result)
            return Response(status=status.HTTP_204_NO_CONTENT)
        except FileNotFoundError:
            raise exceptions.NotFound('Folder or File Not Found')
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['DELETE'])
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources", required=True, location="query"),
        ]))
    @permission_required('pyplan.delete_files', raise_exception=True)
    def deleteFiles(request, *args, **kargs):
        """
        create:
        Duplicate file or Folder.
        """
        serializer = DeleteFilesSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            sources = serializer['sources'].value
            result = FileManagerService().deleteFiles(sources)

            return Response(status=status.HTTP_200_OK)
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['POST'])
    @permission_classes((permissions.IsAuthenticated, ))
    @parser_classes((
        parsers.MultiPartParser,
        parsers.FormParser,
    ))
    def upload(request, *args, **kargs):
        """
        uploads multiple files
        """
        serializer = UploadFilesSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        try:
            service = FileManagerService(request)
            service.createFile(request.FILES["files"],
                               serializer.data.get("folder_path"),
                               serializer.data.get("name"),
                               serializer.data.get("chunk"))
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_200_OK)

    @staticmethod
    @api_view(['GET'])
    @authentication_classes((QueryStringTokenAuthentication, ))
    @permission_required('pyplan.download_files', raise_exception=True)
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources",
                          required=True,
                          location="query",
                          schema=coreschema.Array()),
            coreapi.Field("auth_token",
                          required=True,
                          location="query",
                          schema=coreschema.String()),
        ]))
    def download(request, *args, **kargs):
        """
        download multiple files
        """
        serializer = SourcesListSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        try:
            service = FileManagerService(request)
            file_stream, file_name = service.download(
                serializer.data.get('sources'), )
            return FileResponse(file_stream,
                                as_attachment=True,
                                filename=file_name)
        except Exception as ex:
            raise exceptions.NotAcceptable(detail=ex)

    @staticmethod
    @api_view(['GET'])
    @permission_classes((permissions.IsAuthenticated, ))
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("source", required=True, location="query"),
            coreapi.Field("targetFolder", required=True, location="query"),
        ]))
    def unzipFile(request, *args, **kargs):
        """
        unzip file
        """
        serializer = UnzipFileSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        try:
            service = FileManagerService(request)
            service.unzipFile(serializer.data.get("source"),
                              serializer.data.get("targetFolder"))
            return Response(status=status.HTTP_200_OK)
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @permission_classes((permissions.IsAuthenticated, ))
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources",
                          required=True,
                          location="query",
                          schema=coreschema.Array()),
        ]))
    def zipFiles(request, *args, **kargs):
        """
        zip files
        """
        serializer = SourcesListSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        try:
            service = FileManagerService(request)
            response = service.zipFiles(serializer.data.get("sources"))
            return Response(response, status=status.HTTP_200_OK)
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)

    @staticmethod
    @api_view(['GET'])
    @permission_classes((permissions.IsAuthenticated, ))
    def getHome(request, *args, **kargs):
        """
        Return home json definition of the current company
        """
        service = FileManagerService(request)
        return Response(service.getHome())

    @staticmethod
    @api_view(['GET'])
    @permission_classes((permissions.IsAuthenticated, ))
    @schema(
        AutoSchema(manual_fields=[
            coreapi.Field("sources",
                          required=True,
                          location="query",
                          schema=coreschema.Array()),
        ]))
    def optimizeTemplates(request, *args, **kargs):
        """
        Optimice templates for speed up future reads
        """
        serializer = SourcesListSerializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        try:
            service = FileManagerService(request)
            service.optimizeTemplates(serializer.data.get("sources"), )
        except Exception as ex:
            return Response(str(ex), status=status.HTTP_400_BAD_REQUEST)
        return Response(status=status.HTTP_200_OK)
예제 #23
0
class UpdateProfilePic(APIView):
    """
    post:
        API for update user profile picture. Auth token required.
    """
    # Parameter description for API documentation starts here
    schema = schemas.ManualSchema(fields=[
        coreapi.Field(
            "profile_pic",
            required=False,
            location="form",
            schema=coreschema.Object(
                description="Test this API with Postmen"
            )
        )
    ])

    # Parameter description for API documentation ends here
    permission_classes = (permissions.IsAuthenticated,)

    def post(self, request):

        try:
            user = User.objects.get(id=request.user.id)

        except ValidationError as v:
            return Response(
                {
                    'status': status.HTTP_401_UNAUTHORIZED,
                    'message': 'invalid token',
                    'data': ''
                }
            )

        if 'profile_pic' not in self.request.data:
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'Invalid file given',
                    'data': ''
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        file_name = self.request.data['profile_pic']
        if not file_name.name.lower().endswith(('.jpg', '.jpeg')):
            return Response(
                {
                    'status': status.HTTP_400_BAD_REQUEST,
                    'message': 'Invalid image format is given',
                    'data': ''
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        rndm = random.randint(100000, 9999999)
        upload_dir = make_dir(
            settings.MEDIA_ROOT + settings.CUSTOM_DIRS.get('USER_IMAGE') + '/' + str(rndm) + '/'
        )

        file_name = file_upload_handler(file_name, upload_dir)

        profile_pic = settings.MEDIA_URL + settings.CUSTOM_DIRS.get('USER_IMAGE') + '/' + str(
            rndm) + '/' + file_name

        user.profile_pic = profile_pic
        user.save()

        return Response(
            {
                'status': status.HTTP_201_CREATED,
                'message': 'Profile picture updated.',
                'data': {
                    'profile_pic': profile_pic,
                    'user_name': user.username
                }
            },
            status=status.HTTP_201_CREATED
        )
예제 #24
0
파일: jsonschema.py 프로젝트: EUNS00/TIL
 'Schema': coreschema.Object(
     properties={
         # Meta
         'id': coreschema.String(format='uri'),
         '$schema': coreschema.String(format='uri'),
         'title': coreschema.String(),
         'description': coreschema.String(),
         'default': coreschema.Anything(),
         'definitions': coreschema.Ref('SchemaMap'),
         # Type
         'type': coreschema.Ref('SimpleTypes') | coreschema.Array(items=coreschema.Ref('SimpleTypes'), min_items=1, unique_items=True),
         # Number validators
         'minimum': coreschema.Number(),
         'maximum': coreschema.Number(),
         'exclusiveMinimum': coreschema.Boolean(default=False),
         'exclusiveMaximum': coreschema.Boolean(default=False),
         'multipleOf': coreschema.Number(minimum=0, exclusive_minimum=True),
         # String validators
         'minLength': coreschema.Integer(minimum=0, default=0),
         'maxLength': coreschema.Integer(minimum=0),
         'pattern': coreschema.String(format='regex'),
         'format': coreschema.String(),
         # Array validators
         'items': coreschema.Ref('Schema') | coreschema.Ref('SchemaArray'), # TODO: default={}
         'additionalItems': coreschema.Boolean() | coreschema.Ref('Schema'),  # TODO: default={}
         'minItems': coreschema.Integer(minimum=0, default=0),
         'maxItems': coreschema.Integer(minimum=0),
         'uniqueItems': coreschema.Boolean(default=False),
         # Object validators
         'properties': coreschema.Ref('SchemaMap'),
         'patternProperties': coreschema.Ref('SchemaMap'),
         'additionalProperties': coreschema.Boolean() | coreschema.Ref('Schema'),
         'minProperties': coreschema.Integer(minimum=0, default=0),
         'maxProperties': coreschema.Integer(minimum=0),
         'required': coreschema.Ref('StringArray'),
         'dependancies': coreschema.Object(additional_properties=coreschema.Ref('Schema') | coreschema.Ref('StringArray')),
         # Enum validators
         'enum': coreschema.Array(min_items=1, unique_items=True),
         # Composites
         'allOf': coreschema.Ref('SchemaArray'),
         'anyOf': coreschema.Ref('SchemaArray'),
         'oneOf': coreschema.Ref('SchemaArray'),
         'not': coreschema.Ref('Schema')
     },
     # dependancies=..., TODO
     default={},
 ),
예제 #25
0
class HistoryViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Command History to be viewed or edited.
    """
    permission_classes = (IsAuthenticated, )
    serializer_class = HistorySerializer
    lookup_field = 'command_id'

    permissions = {
        'create': (IsAuthenticated, ),
        'destroy': (IsAdminUser, ),
        'partial_update': (IsAdminUser, ),
        'retrieve': (IsAuthenticated, ),
        'update': (IsAdminUser, ),
        # Custom Views
        'send': (IsAuthenticated, ),
    }

    queryset = SentHistory.objects.order_by('-received_on')
    filter_backends = (filters.OrderingFilter, )
    ordering_fields = ('command_id', 'user', 'received_on', 'actuators',
                       'status', 'details')

    schema = utils.OrcSchema(send_fields=[
        coreapi.Field(
            "actuator",
            required=False,
            location="json",
            schema=coreschema.String(
                description='Actuator/Type that is to receive the command.')),
        coreapi.Field(
            "command",
            required=True,
            location="json",
            schema=coreschema.Object(
                description='Command that is to be sent to the actuator(s).'))
    ])

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        """
        return [
            permission() for permission in self.permissions.get(
                self.action, self.permission_classes)
        ]

    def list(self, request, *args, **kwargs):
        """
        Return a list of all commands that the user has executed, all commands if admin
        """
        self.pagination_class.page_size_query_param = 'length'
        self.pagination_class.max_page_size = 100
        queryset = self.filter_queryset(self.get_queryset())

        if not request.user.is_staff:  # Standard User
            queryset = queryset.filter(user=request.user)

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        """
        Return a specific command that the user has executed, command if admin
        """
        command = self.get_object()

        if not request.user.is_staff:  # Standard User
            if command.user is not request.user:
                raise PermissionDenied(
                    detail='User not authorised to access command', code=401)

        serializer = self.get_serializer(command)
        return Response(serializer.data)

    @action(methods=['PUT'], detail=False)
    def send(self, request, *args, **kwargs):
        """
        Sends the specified command to the specified orchestrator in the command or in the request
        """
        rslt = action_send(
            usr=request.user,
            cmd=request.data.get('command', {}),
            actuator=request.data.get('actuator', None),
            channel=request.data.get('channel', {}),
        )

        return Response(*rslt)
예제 #26
0
    uid = request.query_params['uid']
    page = request.query_params['page']
    print(page)
    user = User.objects.filter(user_id=uid).first()
    return Response(user)


@api_view(['POST'])
@transaction.atomic
@schema(
    AutoSchema(manual_fields=[
        coreapi.Field(
            'data',
            location='body',
            schema=coreschema.Object(
                description=
                '{"mobile":"18665411234", "password":"******", "verify_code":"123456"}'
            ),
            required=True),
    ]))
@check_required(["mobile", "password", "verify_code"])
def register(request):
    """
    user register api
    :param request:
    :return:
    """
    data = request.data
    mobile = data["mobile"]
    code = data["verify_code"]
    password = data["password"]
    #