Пример #1
0
def upload(request, customer_id):
    customer = get_object_or_404(Customer, pk=customer_id)
    if request.method == 'POST' and request.POST['content']:

        myfile = request.FILES['myfile']
        post = Post()
        post.content = request.POST['content']
        post.createtime = timezone.now()
        post.updatetime = timezone.now()
        post.customer = Customer.objects.get(id=customer_id)
        fs = FileSystemStorage()
        filename = fs.save(myfile.name, myfile)
        uploaded_file_url = fs.url(filename)

        # image = Image()
        post.save()
        for file in request.FILES.getlist('myfile'):
            image = Image()
            post.save()
            image.imageurl = file
            image.post = Post.objects.get(id=post.id)
            image.save()
        # image.imageurl = filename
        # image.post = Post.objects.get(id=post.id)
        # post.save()
        # image.save()
        return redirect('/customers/' + 'detail/' + str(customer_id))
    return render(request, 'customers/detail.html', {'customer': customer})
Пример #2
0
def create(request):
    if request.method == "POST":
        if request.user.is_authenticated:
            content = json.loads(request.POST['content'])
            establishment_uuid = uuid.uuid4()
            image_url = 'https://outtolunchstatic.s3.amazonaws.com/media/images/download.png'
            if request.user.elo >= 1000:
                if 'image' in request.FILES:
                    request.FILES['image'].name = uuid.uuid4().__str__()
                    image = Image(file=request.FILES['image'],
                                  type='E',
                                  uuid=establishment_uuid)
                    image.save()
                    image_url = image.file.url
                establishment = Establishment(
                    establishment_id=establishment_uuid,
                    name=content['name'],
                    location=content['location'],
                    description=content['description'],
                    rating=0,
                    owner=request.user,
                    rating_count=0,
                    image=image_url)
                establishment.save()
                return JsonResponse({"success": "success"})
            else:
                return JsonResponse({"error": "You do not have enough elo!"})
        else:
            return JsonResponse(
                {"error": "You are not logged in you silly goose!"})
    else:
        return redirect('/')
Пример #3
0
def images_add(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/staff/login/')
    elif request.user.has_perm('images.add_image'):
        if request.method == 'POST':
            form = ImageForm(request.POST, request.FILES)
            if form.is_valid():
                # save new image
                new_image = Image(name=form.cleaned_data['name'])
                if form.cleaned_data.get('caption'):
                    new_image.caption = form.cleaned_data['caption']
                if form.cleaned_data.get('credit'):
                    new_image.credit = form.cleaned_data['credit']
                new_image.image = form.cleaned_data['image']
                new_image.save()
                return HttpResponseRedirect(
                    reverse('images.views.images_add_to_markup',
                            args=[new_image.id]))
            else:
                return render_to_response(
                    'images/widget_add.html', {'form': form},
                    context_instance=RequestContext(request))
        else:
            form = ImageForm()
            return render_to_response('images/widget_add.html', {'form': form},
                                      context_instance=RequestContext(request))
    else:
        return render_to_response('staff/access_denied.html', {
            'missing': 'add photos to',
            'staffapp': 'this entry'
        },
                                  context_instance=RequestContext(request))
Пример #4
0
def update(request):
    if request.method == 'POST':
        if request.user.is_authenticated:
            if 'image' in request.FILES:
                request.FILES['image'].name = uuid.uuid4().__str__()
                try:
                    image = Image.objects.get(uuid=request.user.id, type='U')
                    image.file = request.FILES['image']
                    image.save()
                    request.user.image = image.file.url
                    request.user.save()
                except Image.DoesNotExist:
                    request.FILES['image'].name = uuid.uuid4().__str__()
                    image = Image(file=request.FILES['image'],
                                  type='U',
                                  uuid=request.user.id)
                    image.save()
                    request.user.image = image.file.url
                    request.user.save()
                return successful_message({})
            else:
                return error_message("No image provided!")
        else:
            return error_message("You must be signed in!")
    else:
        return redirect('/')
Пример #5
0
def create(request):
    if request.method == "POST":
        if request.user.is_authenticated:
            content = json.loads(request.POST['content'])
            post_id = uuid.uuid4().__str__()
            image_url = 'https://outtolunchstatic.s3.amazonaws.com/media/images/download.png'
            if 'image' in request.FILES:
                request.FILES['image'].name = uuid.uuid4().__str__()
                image = Image(file=request.FILES['image'], type='P', uuid=post_id)
                image.save()
                image_url = image.file.url
            post_event = Event(event_id=uuid.uuid4().__str__(),
                               type='PostCreatedEvent',
                               timestamp=datetime.now(),
                               data=Post(post_id=post_id,
                                         post_user=content['userId'],
                                         post_rating=content['rating'],
                                         post_subject=content['subject'],
                                         establishment_id=content['establishmentId'],
                                         post_content=content['content'],
                                         post_photo_location=image_url
                                         )
                               )
            post_event.save()
            establishment = Establishment.objects.get(establishment_id=content['establishmentId'])
            establishment.rating_count += 1
            establishment.rating = ((establishment.rating * (establishment.rating_count - 1)) + content[
                'rating']) / establishment.rating_count
            establishment.save()
            return JsonResponse({'success': 'success'})
        else:
            return JsonResponse({'error': 'You have to login first in order to post!'})
    else:
        return redirect('/')
Пример #6
0
    def create(self, request, *args, **kwargs):
        serializer = ImageNewSerializer(data=request.data)
        if serializer.is_valid():
            form_url = serializer.validated_data.get('form_url', None)
            form_file = serializer.validated_data.get('form_file', None)
            image_instance = Image()
            if form_url:
                file_name = os.path.basename(
                    urllib.parse.urlparse(form_url).path)
                req = urllib.request.Request(form_url)
                try:
                    response = urllib.request.urlopen(req)
                except urllib.error.HTTPError:
                    return Response(status=status.HTTP_400_BAD_REQUEST,
                                    data={"form_url": "error"})
                django_file = ContentFile(BytesIO(response.read()).getvalue())
                image_instance.file.save(file_name, django_file)

            elif form_file:
                image_instance.file = form_file
            image_instance.save()
            return Response(data=ImageSerializer(image_instance).data,
                            status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Пример #7
0
def update_picture_for_candidate(candidate_data, cache_directory, **options):
    picture_intro = 'Picture from the IEBC API for candidate'
    candidate_code = candidate_data['code']
    filename = os.path.join(cache_directory,
                            "candidate-%s.jpg" % (candidate_code, ))
    if not os.path.exists(filename):
        image_url = candidate_data['picture']
        r = requests.get(image_url)
        if r.status_code == 200:
            with open(filename, 'w') as fp:
                fp.write(r.content)
    # If that image now exists, use it:
    if os.path.exists(filename):
        # Find the position from the candidate code, so we can get the right person:
        positions = Position.objects.filter(
            external_id=candidate_code).currently_active()
        if not positions:
            print "#### Missing position for:", candidate_code
        elif len(positions) > 1:
            print "#### Multiple positions for:", candidate_code
        else:
            person = positions[0].person
            if options['commit']:
                # Remove old IEBC images for that person:
                person.images.filter(source__startswith=picture_intro).delete()
                # And now create the new one:
                new_image = Image(content_object=person,
                                  source="%s %s" %
                                  (picture_intro, candidate_code))
                with open(filename) as fp:
                    new_image.image.save(
                        name="%s-%s.jpg" %
                        (candidate_code, file_mtime_iso8601(filename)),
                        content=ContentFile(fp.read()))
Пример #8
0
def upload_image(id):
    url = IMAGE_ORIGINAL_URL.format(id)
    image = download_file(url)
    image = '{}/{}'.format(Image.src.field.upload_to, image)
    image = Image(src=image, order=99)
    image.save()
    return image
Пример #9
0
 def test_can_created_encrypted_key(self):
     """
     Tests that the DES key encrypts properly
     """
     i = Image(pk=1)
     self.assertEquals('fQj1bFDkn3g', i.generate_encrypted_key())
     i.pk = 2
     self.assertEquals('i76tPgXaavF', i.generate_encrypted_key())
Пример #10
0
def import_glance_image(request):
    """
        Imports Openstack Glance image into Wistar.

        :param request: JSON payload that contains a single object with the following properties:
            image_name, image_type, image_descr
        :return: a JSON object with at least the following properties: status (boolean) and message
        """

    logger.debug("<---- API call import_glance_images ---->")

    if openstackUtils.connect_to_openstack():

        json_string = request.body

        try:
            json_body = json.loads(json_string)
        except ValueError as ve:
            logger.error(
                'Could not parse json payload with error <{0}>'.format(
                    ve.message))
            return apiUtils.return_json(False, "Could not parse json payload!")

        logger.debug(json_body)
        required_fields = {'image_name', 'image_type', 'image_descr'}

        if not required_fields.issubset(json_body):
            logger.error("Invalid parameters in json body")
            return apiUtils.return_json(False,
                                        "Invalid parameters in json payload")

        image_name = json_body["image_name"]
        image_type = json_body["image_type"]
        image_decr = json_body["image_descr"]

        logger.debug(
            "<---- API call import_glance_image: <{0}> START ---->".format(
                image_name))

        if Image.objects.filter(name=image_name).exists():
            logger.info('image with name %s already exists' % image_name)
            return apiUtils.return_json(True, "Glance images already imported")

        image = Image()
        image.description = image_decr + ' image imported from Glance'
        image.name = image_name
        image.type = image_type
        image.save()
        logger.debug(
            "<---- API call import_glance_image: <{0}> DONE ---->".format(
                image_name))

        return apiUtils.return_json(True,
                                    "Glance images successfully imported")

    else:
        return apiUtils.return_json(False, "Failed to authenticate")
    def test_upload(self):
        i1 = Image()
        i1.title = "aaa"
        i1.thumb = File(open("static/images/comments4.png"))
        i1.save()

        p = Image.objects.get(id=1).thumb.path

        self.failUnless(open(p), 'file not found')
Пример #12
0
def importZip(zipfile, galleryName, galleryDescription):
    # Stuff bgins here ...
    imagesObj = imagesFromZip(zipfile)
    imagesList = imagesObj.listImages()
    # Is there images in this zip ?
    if len(imagesList) > 0:
        # regexp for extractiong name ...
        nameRe = re.compile('/([^/]+)$')
        # Create corresponding gallery
        gallery = Gallery()
        gallery.title = galleryName
        gallery.desc = galleryDescription
        gallery.save()  # Must save gallery
        # Now, for each images in it, create an image object and bind it to gallery
        for imgPath in imagesList:
            src = PILImage.open(imgPath)
            m = nameRe.search(imgPath)
            imgObj = Image()
            imgObj.gallery = gallery
            # First, put the original sized picture
            # use StringIO hack to save image to a string ...
            output = StringIO.StringIO()
            src.save(output, 'JPEG')
            imgObj.original.save(m.groups()[0], ContentFile(output.getvalue()))
            output.close()
            # Then, resize it to something like 1600*1200
            (orig_w, orig_h) = src.size
            orig_s = orig_w * orig_h
            new_s = 1600 * 1200
            ratio = orig_s / new_s
            # Resize only if requested size is lower than original
            if ratio > 1:
                (new_w, new_h) = (orig_w / (sqrt(ratio)),
                                  orig_h / (sqrt(ratio)))
                resized = src.resize((int(new_w), int(new_h)))
            else:  # Else, just keep original one ...
                (new_w, new_h) = (orig_w, orig_h)
                resized = src
            output = StringIO.StringIO()
            resized.save(output, 'JPEG')
            imgObj.screen.save(m.groups()[0], ContentFile(output.getvalue()))
            output.close()
            # Finally, get a thumb of 150px*150px, work on resized picture to be faster
            if new_w < new_h:
                maxi = new_w
            else:
                maxi = new_h
            thumb = resized.transform((150, 150), PILImage.EXTENT,
                                      (0, 0, maxi, maxi))
            output = StringIO.StringIO()
            thumb.save(output, 'JPEG')
            imgObj.thumb.save(m.groups()[0], ContentFile(output.getvalue()))
            output.close()
            imgObj.save()
        gallery.save()
        print "done !"
Пример #13
0
def create_from_instance(request, uuid):
    logger.debug("Creating new image from instance")
    domain = libvirtUtils.get_domain_by_uuid(uuid)

    logger.debug("got domain " + domain.name())
    domain_image = libvirtUtils.get_image_for_domain(uuid)
    logger.debug("got domain_image: " + domain_image)

    if osUtils.is_image_thin_provisioned(domain_image):
        logger.error(
            "Cannot clone disk that is thinly provisioned! Please perform a block pull before continuing"
        )
        context = {
            'error':
            "Cannot Clone thinly provisioned disk! Please perform a block pull!"
        }
        return render(request, 'error.html', context)

    domain_name = domain.name()

    # FIXME - make these variable names a bit more clear about their meaning
    # we need to get the path of the image relative to the MEDIA_ROOT
    media_root = settings.MEDIA_ROOT
    media_root_array = media_root.split("/")
    len_media_root = len(media_root_array)

    full_path_array = domain_image.split("/")
    full_path = "/".join(full_path_array[:full_path_array.index('instances')])

    # grab the file path of the domain image without the MEDIA_ROOT prepended
    file_path_array = domain_image.split('/')[len_media_root:]
    images_dir = "/".join(file_path_array[:file_path_array.index('instances')])

    new_relative_image_path = images_dir + "/image_" + str(
        domain.UUIDString()) + ".img"
    new_full_image_path = full_path + "/image_" + str(
        domain.UUIDString()) + ".img"

    if osUtils.check_path(new_full_image_path):
        logger.info("Image has already been cloned")
        context = {'error': "Instance has already been cloned!"}
        return render(request, 'error.html', context)

    logger.debug("Copying image from " + domain_image)

    logger.debug("To " + new_full_image_path)

    osUtils.copy_image_to_clone(domain_image, new_full_image_path)

    image = Image()
    image.name = "image_" + str(domain.UUIDString())
    image.description = "Clone of " + domain_name
    image.filePath = new_relative_image_path
    image.save()
    return HttpResponseRedirect('/images/')
Пример #14
0
 def test_if_no_title_uses_image_name(self):
     """
     If there's no title then the image's name should be the default.
     """
     with open(
             os.path.join(settings.BASE_DIR, 'images', 'tests', 'data',
                          'image.png'), "rb") as image_file:
         image = Image(
             image=SimpleUploadedFile("test.png", image_file.read()))
     image.set_title()
     self.assertEquals('test.png', image.title)
Пример #15
0
    def create(self, request, *args, **kwargs):

        image = Image()
        image.title = request.data['title']
        image.format = request.data['format']
        image.file = request.data['file']
        image.date_created = timezone.now()
        image.date_updated = timezone.now()
        #return super().create(request, *args, **kwargs)
        image.save()
        return Response({"message": "Image entry successful"},
                        status=status.HTTP_201_CREATED)
Пример #16
0
    def create(self, validated_data):
        user = None
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            user = request.user

        image = Image(
            comments=validated_data["comments"],
            data=validated_data["data"],
            uploaded_by=user,
        )
        image.save()

        return image
Пример #17
0
def populate_data_base_with_images(apps, schema_editor):

    context = {}

    with open('data/context.json') as file:
        context = json.load(file)

    products = []

    products = context["products"]

    for data in products:
        image = Image(name=data["image"], value=data["image"])
        image.save()
Пример #18
0
def _update_v1(request, name, os, payload):
    """Update API v1."""
    start_time = timezone.now()

    try:
        im = Image.objects.get(name=name)
        im.os = os
        im.save()  # Always update at least the modification time
        images_packages = {
            image_pkg.package.name: image_pkg
            for image_pkg in ImagePackage.objects.filter(image=im)
        }

    except Image.DoesNotExist:
        im = Image(name=name, os=os)
        im.save()
        images_packages = {}
        logger.info("Created image '%s'", name)

    existing_not_updated = []
    existing_upgradable_not_updated = []

    installed = payload.get('installed', [])
    for item in installed:
        _process_installed(im, os, images_packages, existing_not_updated, item)

    logger.info("Tracked %d installed packages for image '%s'", len(installed),
                name)

    uninstalled = payload.get('uninstalled', [])
    for item in uninstalled:
        existing = images_packages.get(item['name'], None)
        if existing is not None:
            existing.delete()

    logger.info("Untracked %d uninstalled packages for image '%s'",
                len(uninstalled), name)

    upgradable = payload.get('upgradable', [])
    for item in upgradable:
        _process_upgradable(im, os, images_packages,
                            existing_upgradable_not_updated, item)

    logger.info("Tracked %d upgradable packages for image '%s'",
                len(upgradable), name)

    if payload['update_type'] == 'full':
        _garbage_collection(im, name, start_time, existing_not_updated,
                            existing_upgradable_not_updated)
Пример #19
0
def create_account(request):
    if request.method == 'POST':
        content = json.loads(request.POST['content'])
        user_id = uuid.uuid4()
        image_url = 'https://outtolunchstatic.s3.amazonaws.com/media/images/download.png'
        if 'image' in request.FILES:
            request.FILES['image'].name = uuid.uuid4().__str__()
            image = Image(file=request.FILES['image'], type='U', uuid=user_id)
            image.save()
            image_url = image.file.url
        return register_user(user_id, content['username'], content['password'],
                             content['email'], content['FName'],
                             content['LName'], image_url)
    else:
        return redirect('/')
Пример #20
0
    def handle(self, *args, **options):
        img_formats = ('.jpg', '.jpeg', '.png')
        imgs_dir = options['directory']

        # path = os.path.join(settings.MEDIA_ROOT, imgs_dir)
        path = os.path.join(settings.BASE_DIR, imgs_dir)
        file_list = os.listdir(path)

        if options['del']:
            Image.objects.all().delete()

        for f in file_list:
            if f.endswith(img_formats):
                image = Image(name=f, img=f)
                image.save()
Пример #21
0
        def test_run(self):
            image = Image(**image_kwargs)

            # Make operation
            operation = self.operation_class(*filter_spec.split('-'))

            # Make operation recorder
            operation_recorder = WillowOperationRecorder(
                (image.width, image.height))

            # Run
            operation.run(operation_recorder, image, {})

            # Check
            self.assertEqual(operation_recorder.ran_operations,
                             expected_output)
Пример #22
0
    def setUp(self):
        self.category = Category(name="Test cat")
        self.category.save_category()
        self.location = Location(name="Test Loc")
        self.location.save_location()

        self.image = Image(
            name="Test Img",
            location_id=self.location,
            category_id=self.category,
            image=SimpleUploadedFile(
                name='image_test.jpg',
                content=open(
                    'photo_gallery/static/images/default_location.jpg',
                    'rb').read(),
                content_type='image/jpeg'))
Пример #23
0
    def transform(self, data):
        path = self.find_biggest_image(data['props']['srcset'])
        name = os.path.basename(path)

        image = Image(caption=data['props'].get('caption', ''),
                      title=data['props']['alt'] or self.page.title)

        # save temp file
        img_temp = NamedTemporaryFile()
        img_temp.write(self.get_image_data_from_file(path))
        img_temp.flush()

        # save file and image
        image.file.save(name, File(img_temp), save=True)
        image.save()

        return {'type': 'image', 'value': image.id}
Пример #24
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():

            im = Image()
            im.model_pic = form.cleaned_data['file']

            filename = '{0}{1}'.format(
                str(
                    base64.b64encode(
                        bytes(str(datetime.datetime.now().timestamp()),
                              'utf-8')))[2:-2],
                pathlib.Path(form.cleaned_data['file'].name).suffix)
            im.model_pic.name = filename

            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')

            if x_forwarded_for:
                ipaddress = x_forwarded_for.split(',')[-1].strip()
            else:
                ipaddress = request.META.get('REMOTE_ADDR')

            im.owner = None
            im.upload_ip_address = ipaddress
            im.lease = datetime.datetime.now().replace(
                microsecond=0) + datetime.timedelta(
                    seconds=int(form.cleaned_data['expiration'].split(".")[0]))

            im.name = filename
            if form.cleaned_data['your_name'] == "":
                im.custom_name = None
            else:
                im.custom_name = form.cleaned_data['your_name']

            im.save()

            for tag in request.POST.getlist('tagList'):
                tag = Tag(name=tag.split(":")[0], image=im)
                tag.save()

            return HttpResponseRedirect("/image/view/%s" % filename)
    else:
        form = UploadFileForm()
    return render(request, 'index.html', {'form': form})
Пример #25
0
def upload_images(request):
    """
    View to store upload images specific to an event.
    Models used: Folder, Image
    """
    try:
        is_loggedin, username = get_session_variables(request)

        # User is not logged in
        if not is_loggedin:
            return HttpResponseRedirect('/register/login')

        # User is logged in
        else:
            if request.method == 'POST':
                form = FolderForm(request.POST, request.FILES)

                # form is not valid
                if not form.is_valid():
                    error = "Invalid inputs"
                    return render(request, 'images/upload_images.html', \
                        {'form':form, 'error':error, }, \
                        RequestContext(request))

                # form is valid
                else:
                    cleaned_form_data = form.cleaned_data
                    folder_name = cleaned_form_data['folder_name']
                    # create a new folder
                    folder = form.save(commit=False)
                    folder.save()

                    # save images
                    image = request.FILES['image']
                    new_image_object = Image(img=image, \
                        folder_name = folder)
                    img_name = new_image_object.img.name
                    new_image_object.save()
                    return render(request, "images/success.html")
            else:
                return render(request, 'images/upload_images.html', \
                    {'form':FolderForm(), 'is_loggedin': is_loggedin },\
                     RequestContext(request))
    except KeyError:
        return error_key(request)
    def upload_base64(self, request, *args, **kwargs):
        if request.user.is_verified:
            data = request.data
            extension = 'jpg'
            if 'image' in data:
                if len(data['image']) > 0:
                    if re.compile('^data:image/jpeg;').match(
                            data['image']) is not None:
                        image_type = 'image/jpeg'
                        extension = 'jpg'

                    if re.compile('^data:image/png;').match(
                            data['image']) is not None:
                        image_type = 'image/png'
                        extension = 'png'

                    image_data = binascii.a2b_base64(data['image'].replace(
                        'data:' + image_type + ';base64,', ''))
                    f = BytesIO(image_data)
                    pil_image = PilImage.open(f)
                    f.seek(0)

                    # TODO: make them all jpegs
                    average_color = average_image_color(pil_image)
                    color = "rgb(%s,%s,%s)" % (average_color['R'],
                                               average_color['G'],
                                               average_color['B'])
                    image = Image(width=pil_image.width,
                                  height=pil_image.height,
                                  created_by=request.user,
                                  modified_by=request.user,
                                  color=color)

                    image.image = UploadedFile(file=f,
                                               name='%s.%s' %
                                               (image.id, extension),
                                               content_type=image_type,
                                               size=len(image_data))
                    image.save()

                    f.close()

                return Response(ImageSerializer(image).data)

        raise NotFound()
Пример #27
0
def save_latest_images(image_file=None, image_path=None):
    """
    Processes the file with images URLs and saves them into db
    :param image_file: The file containing image urls, if empty it defaults to the one in settings
    :param image_path: The place to store images, if empty it defaults to the one in settings
    """
    from images.tasks import logger
    images_file = image_file if image_file else image_settings.IMAGES_FILE
    saved_images_path = image_path if image_path else image_settings.IMAGES_PATH
    # Check if file is present, skip otherwise
    if os.path.isfile(images_file):
        # Open images file and process each line
        file = open(images_file, 'r')
        for image in file:
            image = image.rstrip('\n')
            response = requests.get(image, stream=True)
            # Get file name
            image_name = os.path.basename(image)
            try:
                with open(saved_images_path + image_name, 'xb') as out_file:
                    shutil.copyfileobj(response.raw, out_file)
                # Save object in bd if does not exist
                if not Image.objects.filter(image_url=image).exists():
                    image = Image(
                        title=image_name,
                        image_url=image,
                        location=saved_images_path + image_name,
                        created_on=datetime.datetime.utcnow(),
                    )
                    image.save()
                    logger.info(
                        'Saved image {0} correctly to db and to disk'.format(
                            image_name))
                del response
            except IOError:
                logger.error(
                    'An error occured trying to save image to disk for image {0}'
                    .format(image_name))
                continue
    else:
        logger.error(
            'Could not find file {0} with images urls'.format(images_file))
Пример #28
0
    def handle(self, *args, **options):
        try:
            project = Project.objects.get(pk=options['project_id'])
        except Project.DoesNotExist:
            raise CommandError('Project "%s" does not exist' %
                               options['project_id'])

        for path, dirs, files in os.walk(options['folder']):
            match = []
            match.extend(fnmatch.filter(files, '*.[Jj][Pp][Gg]'))
            match.extend(fnmatch.filter(files, '*.[Jj][Pp][Ee][Gg]'))
            match.extend(fnmatch.filter(files, '*.[Pp][Nn][Gg]'))
            match.extend(fnmatch.filter(files, '*.[Tt][Ii][Ff]'))
            match.extend(fnmatch.filter(files, '*.[Tt][Ii][Ff][Ff]'))

            for m in match:
                # FIXME: filename should be relative to settings.MEDIA_ROOT
                im = Image(project=project)
                im.image.save(m, File(open(os.path.join(path, m))))
                im.save()
                print '.',
Пример #29
0
def upload_tar(request, projectid):
    import tarfile

    if request.method == "POST":
        targzfile = request.FILES.get('tarfile', None)
        project = Project.objects.get(id=projectid)

        if tarfile:
            tar = tarfile.open(targzfile.temporary_file_path())
            tar.extractall()
            files = tar.getnames()
            tar.close()
            for image in files:
                i = Image(project=project)
                i.image.save(image, File(open(image, 'r')))
                i.save()

            return render(request, "images/upload_result.html", {
                "project": project,
                "files": files
            })
Пример #30
0
def import_from_glance(request, glance_id):
    """
    Creates a local db entry for the glance image
    Everything in Wistar depends on a db entry in the Images table
    If you have an existing openstack cluster, you may want to import those
    images here without having to physically copy the images to local disk
    :param request: HTTPRequest object
    :param glance_id: id of the glance image to import
    :return: redirect to /images/image_id
    """
    if openstackUtils.connect_to_openstack():
        image_details = openstackUtils.get_glance_image_detail(glance_id)
        image = Image()
        image.description = "Imported from Glance"
        image.name = image_details["name"]
        image.type = 'blank'
        image.save()
        logger.debug("All done")
        return HttpResponseRedirect('/images/%s' % image.id)

    context = {'error': "Could not connect to OpenStack"}
    return render(request, 'error.html', context)