示例#1
0
    def create(self, request):
        """
        Create new file

        Create new file
        """
        serializer = FileCreateSerializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            name = serializer.validated_data.get("name")
            file_type = serializer.validated_data.get("type")
            file = serializer.validated_data.get("file")

            self._validate_organization(request)

            file = File(
                name=name,
                type=file_type,
                file=file,
                organization=request.user.organization,
            )
            file.save()
            response = FileIDSerializer(data=file.__dict__)
            if response.is_valid(raise_exception=True):
                return Response(
                    response.validated_data, status=status.HTTP_201_CREATED
                )
示例#2
0
    def post(self, user_id):
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('name', type=str, help="This should be the folder name if creating a folder")
            parser.add_argument('parent_id', type=str, help="This should be the parent folder id")
            parser.add_argument('is_folder', type=str, help="This indicates whether you are trying to create a folder or not")

            args = parser.parse_args()

            name = args.get('name', None)
            parent_id = args.get('parent_id', None)
            is_folder = args.get('is_folder', False)

            parent = None

            # Are we adding this to a oarent folder?
            if parent_id is not None:
                parent = File.find(parent_id)
                if parent is None:
                    raise Exception("This folder does not exist")
                if not parent['is_folder']:
                    raise Exception("Select a valid folder to upload to")

            # Are we creating a folder?
            if is_folder:
                if name is None:
                    raise Exception("You need to specify a name for this folder")

                return Folder.create(
                    name=name,
                    parent=parent,
                    is_folder=is_folder,
                    creator=user_id
                )
            else:
                files = request.files['file']

                if files and is_allowed(files.filename):
                    _dir = os.path.join(BASE_DIR, 'upload/{}/'.format(user_id))

                    if not os.path.isdir(_dir):
                        os.mkdir(_dir)

                    filename = secure_filename(files.filename)
                    to_path = os.path.join(_dir, filename)
                    files.save(to_path)
                    fileuri = os.path.join('upload/{}/'.format(user_id), filename)
                    filesize = os.path.getsize(to_path)

                    return File.create(
                        name=filename,
                        uri=fileuri,
                        size=filesize,
                        parent=parent,
                        creator=user_id
                    )
                raise Exception("You did not supply a valid file in your request")
            except Exception as e:
                abort(500, message="There was an error while processing your request --> {}".format(e.message))
示例#3
0
    def put(self, user_id, file_id):
        try:
            update_fields = {}
            parser = reqparse.RequestParser()

            parser.add_argument('name',
                                type=str,
                                help="New name for the file/folder")
            parser.add_argument('parent_id',
                                type=str,
                                help="New parent folder for the file/folder")

            args = parser.parse_args()

            name = args.get('name', None)
            parent_id = args.get('parent_id', None)

            if name is not None:
                update_fields['name'] = name

            if parent_id is not None and g.file['parent_id'] != parent_id:
                if parent_id != '0':
                    folder_access = Folder.filter({
                        'id': parent_id,
                        'creator': user_id
                    })
                    if not folder_access:
                        abort(
                            404,
                            message=
                            "You don't have access to the folder you're trying to move this object to"
                        )

                if g.file['is_folder']:
                    update_fields['tag'] = g.file[
                        'id'] if parent_id == '0' else '{}#{}'.format(
                            folder_access['tag'], folder['last_index'])
                    Folder.move(g.file, folder_access)
                else:
                    File.move(g.file, folder_access)

                update_fields['parent_id'] = parent_id

            if g.file['is_folder']:
                Folder.update(file_id, update_fields)
            else:
                File.update(file_id, update_fields)

            return File.find(file_id)
        except Exception as e:
            abort(500,
                  message="There was an while processing your request --> {}".
                  format(e.message))
示例#4
0
def update_user(request):
    """Updates the authenticated user with given data"""
    payload = request.data
    user = request.user
    try:
        if 'profile_picture' in payload.keys():
            payload['profile_picture'] = File.create(
                file=payload['profile_picture'])

        print(payload)

        user_item = models.CustomUser.objects.filter(id=request.user.id)
        payload = dict([(i, payload[i]) for i in payload])
        user_item.update(**payload)  # returns 0 or 1
        u = models.CustomUser.objects.get(id=user.id)

        serializer = serializers.UserSerializer(u)
        return JsonResponse({"user": serializer.data},
                            safe=False,
                            status=status.HTTP_200_OK)
    except ObjectDoesNotExist as e:
        return JsonResponse({"error": str(e)},
                            safe=False,
                            status=status.HTTP_404_NOT_FOUND)
    except Exception:
        return JsonResponse(
            {"error": "Something went wrong"},
            safe=False,
            status=status.HTTP_500_INTERNAL_SERVER_ERROR,
        )
示例#5
0
 def get(self, user_id):
     try:
         return File.filter({'creator': user_id})
     except Exception as e:
         abort(500,
               message=
               "There was an error while trying to get your files --> {}".
               format(e.message))
示例#6
0
 def func(*args, **kwargs):
     file_id = kwargs.get('file_id')
     user_id = kwargs.get('user_id')
     file = File.find(file_id, True)
     if not file or file['creator'] != user_id:
         abort(404, message="The file you are trying to access was not found")
     g.file = file
     return f(*args, **kwargs)
def file_upload():
  if request.method == 'GET':
    files = File.query.all()
    files= list(map(lambda x: x.serialize(), files))

    response_body = {
      "files": files 
    }

  elif request.method == 'POST':
    filename = request.json.get("filename", None)
    uploaded_by = request.json.get("uploadedBy", None)
    uploaded_at = request.json.get("uploadedAt", None)
    file_format = request.json.get("fileFormat", None)
    url = request.json.get("url", None)

    if not filename:
      return "Se requiere nombre de archivo", 401
    
    if not uploaded_by:
      return "Debes estar registrado", 401

    newFile = File()
    newFile.filename = filename
    newFile.uploaded_by = uploaded_by
    newFile.uploaded_at = uploaded_at
    newFile.file_format = file_format
    newFile.url = url

    db.session.add(newFile)
    db.session.commit()

    response_body = {
      "msg": "Archivo almacenado con exito"
    }

  return jsonify(response_body), 200
示例#8
0
 def get(self, user_id):
     try:
         return File.filter({'creator': user_id, 'parent_id': 0})
     except Exception as e:
         abort(500, message="Error getting files -> {}".format(str(e)))
示例#9
0
    def delete(self, user_id, file_id):
        try:
            hard_delete = request.args.get('hard_delete', False)
            if not g.file['is_folder']:
                if hard_delete == 'true':
                    os.remove(g.file['uri'])
                    File.delete(file_id)
                else:
                    File.update(file_id, {'status': False})
            else:
                if hard_delete == 'true':
                    folders = Folder.filter(
                        lambda folder: folder['tag'].startswith(g.file['tag']))
                    for folder in folders:
                        files = File.filter({
                            'parent_id': folder['id'],
                            'is_folder': False
                        })
                        File.delete_where({
                            'parent_id': folder['id'],
                            'is_folder': False
                        })
                        for f in files:
                            os.remove(f['uri'])
                else:
                    File.update(file_id, {'status': False})
                    File.update_where({'parent_id': file_id},
                                      {'status': False})

            return "File has been deleted successfully", 204
        except Exception as e:
            abort(500, message="Error processing request -->{}".format(str(e)))
示例#10
0
 def SaveFile(cls, files):
     print(files)
     _file = files.get("file")
     print(_file)
     File(file=_file).save()
     return cls.answer