Exemplo n.º 1
0
 def save(self):
     tag = Tag(wealth=self.wealth,
               name=self.cleaned_data['name'],
               modified_date=datetime.utcnow(),
               created_date=datetime.utcnow())
     tag.save()
     return tag
Exemplo n.º 2
0
def addTag(name, objtype, objid):
    query = Tag.objects.filter(name=name, objtype=objtype, objid=objid)
    if query.count() == 0:
        tag = Tag(name=name, objtype=objtype, objid=objid)
        tag.save()
        return tag
    return None
Exemplo n.º 3
0
def add_tags_to_page(tag_text, page):
    tag_list = Tag.select().where(Tag.id << tag_text)

    tags_to_delete = TagAssociation.delete().where(
        TagAssociation.page == page, ~TagAssociation.tag << (tag_list))

    tags_to_delete.execute()

    tags_in_page = page.tags.select(Tag.id).tuples()

    tags_to_add = tag_list.select().where(~Tag.id << (tags_in_page))

    for n in tags_to_add:
        add_tag = TagAssociation(tag=n, page=page)

        add_tag.save()

    new_tags = json.loads(request.forms.getunicode('new_tags'))

    for n in new_tags:
        new_tag = Tag(tag=n, blog=page.blog)
        new_tag.save()

        add_tag = TagAssociation(tag=new_tag, page=page)

        add_tag.save()

    return tags_to_add, tags_to_delete, new_tags
Exemplo n.º 4
0
 def save(self):
   tag = Tag(
       wealth=self.wealth,
       name=self.cleaned_data['name'],
       modified_date=datetime.utcnow(),
       created_date=datetime.utcnow())
   tag.save()
   return tag
Exemplo n.º 5
0
    def test_get_existing_tag(self):
        """Tests that gets a tag instead of creating a new one"""
        name = 'comida'
        old_tag = Tag(name=name)
        old_tag.save()

        tag = Tag.objects.get_or_create_tag(name=name)

        self.assertEqual(tag.name, name)
        self.assertEqual(tag.id, old_tag.id)
Exemplo n.º 6
0
def add_tags_to_page (tag_text, page, no_delete=False):
    '''
    Takes a list of tags, in JSON text format, and adds them to the page in question.
    Any tags not already in the system will be added.

    :param tag_text:
        List of tags to add.
    :param page:
        Page object to add the tags to.
    :param no_delete:
        When set to True, this will preserve tags already in the page if they are
        not found in tag_text. By default this is False, so any tags not specified in
        tag_text that exist in the page will be removed.
    '''
    tag_list = Tag.select().where(Tag.id << tag_text)

    if no_delete is False:

        tags_to_delete = TagAssociation.delete().where(
            TagAssociation.page == page,
            ~ TagAssociation.tag << (tag_list))

        tags_to_delete.execute()
    else:
        tags_to_delete = None

    tags_in_page = page.tags_all.select(Tag.id).tuples()

    tags_to_add = tag_list.select().where(~Tag.id << (tags_in_page))

    for n in tags_to_add:
        add_tag = TagAssociation(
           tag=n,
           page=page)

        add_tag.save()

    import json
    new_tags = json.loads(request.forms.getunicode('new_tags'))

    for n in new_tags:
        if n != '':
            new_tag = Tag(
                tag=n,
                blog=page.blog)
            new_tag.save()

            add_tag = TagAssociation(
                tag=new_tag,
                page=page)

            add_tag.save()

    return tags_to_add, tags_to_delete, new_tags
Exemplo n.º 7
0
 def node_tag_default(self, o, node, tagname, default):
     tags = Tag.select_by_content_object(node).filter(name=tagname)
     if tags:
         value = tags[0].value
     else:
         value = default
         logger.info("node %s: saving default value %s for tag %s" % (node.name, value, tagname))
         service = self.get_onos_service(o)
         tag = Tag(service=service, content_object=node, name=tagname, value=value)
         tag.save()
     return value
Exemplo n.º 8
0
 def test_can_create_simple_tag(self):
     
     tag = Tag()
     tag.name = 'shouldBeName'
     tag.slug = 'shouldBeSlug'
     tag.save()
     
     tag_find = Tag.objects.get(name=tag.name)
     self.assertEquals(tag_find.name, tag.name)
     self.assertEquals(tag_find.slug, tag.slug)
     self.assertEquals(tag_find.id, tag.id)
     
     tag.delete()
Exemplo n.º 9
0
        def save_m2m():
            """Handle the m2m relation between Post and Tags. This function
            will erase and add tags for every actions on a post."""

            instance.tags.clear()
            for tagname in self.cleaned_data['tags'].split(','):
                tagname = tagname.lower().strip()
                if len(tagname) > 0:
                    try:
                        tag = Tag.objects.get(name=tagname)
                    except Tag.DoesNotExist:
                        tag = Tag(name=tagname)
                        tag.save()
                    instance.tags.add(tag)
Exemplo n.º 10
0
def add_tags_to_page(tag_text, page, no_delete=False):
    '''
    Takes a list of tags, in JSON text format, and adds them to the page in question.
    Any tags not already in the system will be added.

    :param tag_text:
        List of tags to add.
    :param page:
        Page object to add the tags to.
    :param no_delete:
        When set to True, this will preserve tags already in the page if they are
        not found in tag_text. By default this is False, so any tags not specified in
        tag_text that exist in the page will be removed.
    '''
    tag_list = Tag.select().where(Tag.id << tag_text)

    if no_delete is False:

        tags_to_delete = TagAssociation.delete().where(
            TagAssociation.page == page, ~TagAssociation.tag << (tag_list))

        tags_to_delete.execute()
    else:
        tags_to_delete = None

    tags_in_page = page.tags_all.select(Tag.id).tuples()

    tags_to_add = tag_list.select().where(~Tag.id << (tags_in_page))

    for n in tags_to_add:
        add_tag = TagAssociation(tag=n, page=page)

        add_tag.save()

    import json
    new_tags = json.loads(request.forms.getunicode('new_tags'))

    for n in new_tags:
        if n != '':
            new_tag = Tag(tag=n, blog=page.blog)
            new_tag.save()

            add_tag = TagAssociation(tag=new_tag, page=page)

            add_tag.save()

    return tags_to_add, tags_to_delete, new_tags
Exemplo n.º 11
0
    def save_instance(self, instance):
        with transaction.atomic():
            instance.volumes = "/etc/dnsmasq.d,/etc/ufw"
            super(VSGTenant, self).save_instance(instance)

            if instance.isolation in ["container", "container_vm"]:
                lan_network = self.get_lan_network(instance)
                port = self.find_or_make_port(instance, lan_network, ip="192.168.0.1", port_id="unmanaged")
                port.set_parameter("c_tag", self.volt.c_tag)
                port.set_parameter("s_tag", self.volt.s_tag)
                port.set_parameter("device", "eth1")
                port.set_parameter("bridge", "br-lan")

                wan_networks = [x for x in instance.slice.networks.all() if "wan" in x.name]
                if not wan_networks:
                    raise XOSProgrammingError("No wan_network")
                port = self.find_or_make_port(instance, wan_networks[0])
                port.set_parameter("next_hop", value="10.0.1.253")   # FIX ME
                port.set_parameter("device", "eth0")

            if instance.isolation in ["vm"]:
                lan_network = self.get_lan_network(instance)
                port = self.find_or_make_port(instance, lan_network)
                port.set_parameter("c_tag", self.volt.c_tag)
                port.set_parameter("s_tag", self.volt.s_tag)
                port.set_parameter("neutron_port_name", "stag-%s" % self.volt.s_tag)
                port.save()

            # tag the instance with the s-tag, so we can easily find the
            # instance later
            if self.volt and self.volt.s_tag:
                tags = Tag.objects.filter(name="s_tag", value=self.volt.s_tag)
                if not tags:
                    tag = Tag(service=self.provider_service, content_object=instance, name="s_tag", value=self.volt.s_tag)
                    tag.save()

            # VTN-CORD needs a WAN address for the VM, so that the VM can
            # be configured.
            if CORD_USE_VTN:
                tags = Tag.select_by_content_object(instance).filter(name="vm_vrouter_tenant")
                if not tags:
                    vrouter = self.get_vrouter_service().get_tenant(address_pool_name="addresses_vsg", subscriber_service = self.provider_service)
                    vrouter.set_attribute("tenant_for_instance_id", instance.id)
                    vrouter.save()
                    tag = Tag(service=self.provider_service, content_object=instance, name="vm_vrouter_tenant", value="%d" % vrouter.id)
                    tag.save()
Exemplo n.º 12
0
    def save_instance(self, instance):
        with transaction.atomic():
            instance.volumes = "/etc/dnsmasq.d,/etc/ufw"
            super(VSGTenant, self).save_instance(instance)

            if instance.isolation in ["container", "container_vm"]:
                lan_network = self.get_lan_network(instance)
                port = self.find_or_make_port(instance, lan_network, ip="192.168.0.1", port_id="unmanaged")
                port.set_parameter("c_tag", self.volt.c_tag)
                port.set_parameter("s_tag", self.volt.s_tag)
                port.set_parameter("device", "eth1")
                port.set_parameter("bridge", "br-lan")

                wan_networks = [x for x in instance.slice.networks.all() if "wan" in x.name]
                if not wan_networks:
                    raise XOSProgrammingError("No wan_network")
                port = self.find_or_make_port(instance, wan_networks[0])
                port.set_parameter("next_hop", value="10.0.1.253")   # FIX ME
                port.set_parameter("device", "eth0")

            if instance.isolation in ["vm"]:
                lan_network = self.get_lan_network(instance)
                port = self.find_or_make_port(instance, lan_network)
                port.set_parameter("c_tag", self.volt.c_tag)
                port.set_parameter("s_tag", self.volt.s_tag)
                port.set_parameter("neutron_port_name", "stag-%s" % self.volt.s_tag)
                port.save()

            # tag the instance with the s-tag, so we can easily find the
            # instance later
            if self.volt and self.volt.s_tag:
                tags = Tag.objects.filter(name="s_tag", value=self.volt.s_tag)
                if not tags:
                    tag = Tag(service=self.provider_service, content_object=instance, name="s_tag", value=self.volt.s_tag)
                    tag.save()

            # VTN-CORD needs a WAN address for the VM, so that the VM can
            # be configured.
            if CORD_USE_VTN:
                tags = Tag.select_by_content_object(instance).filter(name="vm_vrouter_tenant")
                if not tags:
                    vrouter = self.get_vrouter_service().get_tenant(address_pool_name="addresses_vsg", subscriber_service = self.provider_service)
                    vrouter.set_attribute("tenant_for_instance_id", instance.id)
                    vrouter.save()
                    tag = Tag(service=self.provider_service, content_object=instance, name="vm_vrouter_tenant", value="%d" % vrouter.id)
                    tag.save()
Exemplo n.º 13
0
    def test_can_add_tags_to_post(self):
        tag1 = Tag(name='my first tag', slug='my-first-tag')
        tag1.save()
        tag2 = Tag(name='my second tag', slug='my-second-tag')
        tag2.save()

        post = Post()
        post.title = "should be title"
        post.subtitle = 'should be subtitle'
        post.created = datetime.now()
        post.body =  "should be body"
        post.save()

        post.tags = [tag1, tag2]

        post_found = Post.objects.get(title=post.title)
        self.assertIn(tag1, post_found.tags.all())
        self.assertIn(tag2, post_found.tags.all())
        self.assertEquals(len(post_found.tags.all()), 2)
def addTag(name, objtype, objid):
    tag = Tag(name=name, objtype=objtype, objid=objid)
    tag.save()
    return tag
Exemplo n.º 15
0
 def save_tags(self, tags, post):
     for tag in tags:
         t = Tag(tag=tag)
         t.save()
         t.post.add(post)
Exemplo n.º 16
0
    def handle(self, *args, **options):
        if not Tag.objects.filter(name=STARRED_TAGNAME).exists():
            t = Tag(name=STARRED_TAGNAME)
            t.save()

        arg_album_name = options['album_name'][0] if options[
            'album_name'] else None

        if arg_album_name is not None:
            album_list = [arg_album_name]
        else:
            album_list = img_utils.get_album_list(settings.PHOTOS_BASEDIR)

        for album_name in album_list:
            _logger.debug("Generating db items for %s: ", album_name)
            try:
                album = Album.objects.get(name=album_name)
            except Album.DoesNotExist:
                album = Album(name=album_name)
                album.save()

            for photo in img_utils.get_photo_list(settings.PHOTOS_BASEDIR,
                                                  album_name):
                photo_relpath = img_utils.get_photo_filesystem_relpath(
                    album_name, photo)
                photo_abspath = img_utils.get_photo_filesystem_path(
                    settings.PHOTOS_BASEDIR, album_name, photo)
                photo_f = None
                try:
                    photo_f = open(photo_abspath, 'rb')
                    hashsum = img_utils.calc_mediafile_hash(photo_f)
                    photo_f.seek(0)
                    try:
                        mf = MediaFile.objects.get(file_hash=hashsum)
                        if mf.file_location != photo_relpath:
                            mf.file_location = photo_relpath
                            mf.save()
                    except MediaFile.DoesNotExist:
                        im = None
                        try:
                            im = Image.open(photo_f)
                            width, height = im.size
                            img_datetime = None
                            if hasattr(im, '_getexif'):
                                # noinspection PyProtectedMember
                                img_exif = im._getexif()
                                if img_exif:
                                    img_datetimedata = img_exif.get(
                                        EXIF_DATETIMEORIGINAL_TAG, None)
                                    try:
                                        img_datetime = img_utils.parse_exif_date(
                                            img_datetimedata
                                        ) if img_datetimedata else None
                                        if img_datetime:
                                            img_datetime = img_datetime.replace(
                                                tzinfo=pytz.UTC)
                                    except ValueError as v:
                                        _logger.warning(
                                            "Could not process date for %s, err: %s",
                                            photo_abspath, str(v))

                            mf = MediaFile(file_hash=hashsum,
                                           mediatype=models.MEDIATYPE_PHOTO,
                                           file_location=photo_relpath,
                                           width=width,
                                           height=height,
                                           date_taken=img_datetime)
                            try:
                                mf.save()
                            except django.db.utils.IntegrityError:
                                # Most probably file was modified, just update old record to preserve
                                # tags and comments
                                mf_old = MediaFile.objects.get(
                                    file_location=photo_relpath)
                                if MediaFile.objects.filter(
                                        file_location="DEL").exists():
                                    # This shouldn't exist but if we don't do this check a
                                    # uncleanly stopped previous job would break the makedb
                                    # command permanently
                                    MediaFile.objects.get(
                                        file_location="DEL").delete()
                                # Do this since file_location needs to be unique
                                mf_old.file_location = str("DEL")
                                mf_old.save()
                                mf.save()
                                mf_old.transfer_relations_to_other(mf)
                                mf_old.delete()

                        except OSError:
                            # this is not an image file, check for video
                            # TODO: work in progress
                            if os.path.splitext(photo_relpath)[-1] == ".MP4":
                                _logger.info("FOUND VIDEO")
                                mf = MediaFile(
                                    file_hash=hashsum,
                                    mediatype=models.MEDIATYPE_VIDEO,
                                    file_location=photo_relpath,
                                    width=0,
                                    height=0)
                                mf.save()
                            else:
                                raise IOError("")
                        finally:
                            if im is not None:
                                im.close()

                    try:
                        album_item = AlbumItem.objects.get(
                            file_location=photo_relpath)
                        album_item.media_file = mf
                        album_item.album = album
                    except AlbumItem.DoesNotExist:
                        album_item = AlbumItem(file_location=photo_relpath,
                                               album=album,
                                               media_file=mf)
                    album_item.save()

                except IOError:
                    _logger.warning("Could not process file: %s",
                                    photo_abspath)
                finally:
                    if photo_f is not None:
                        photo_f.close()
            album.gen_album_dates()
            album.save()

        if arg_album_name is None:
            # Delete albums where underlying folder is missing
            # Nothing should be linked to Album or AlbumItem so we should just be deleting
            # generated data
            for album in Album.objects.all():
                if album.name not in album_list:
                    print("Deleting album %s" % (album.name, ))
                    album.delete()

            all_files = set()
            for album_name in album_list:
                photo_dir = os.path.join(settings.PHOTOS_BASEDIR, album_name)
                all_files.update([
                    os.path.join(album_name, file_name)
                    for file_name in os.listdir(photo_dir)
                ])

            # Delete albums where underlying folder is missing. Note that comments, tags
            # and AlbumItems are linked to mediafiles and will be removed but since the
            # file does not exist anymore it should be ok
            for mf in MediaFile.objects.all():
                if mf.file_location not in all_files:
                    print("Removing file %s from database" %
                          (mf.file_location, ))
                    mf.delete()
Exemplo n.º 17
0
def create_fake_tags(number=10):
    Tag.objects.all().delete()
    for i in range(number):
        instance = Tag(name=fake.name())
        instance.save()
Exemplo n.º 18
0
def profile_view(request, profile_id):

    profile = Profile.objects.get(pk=profile_id)
    now = datetime.datetime.now()

    if request.POST:
        comment = request.POST.get('comment')
        pro_tag = request.POST.get('pro-tag')
        con_tag = request.POST.get('con-tag')
        file = request.FILES.get('file')
        star_rating = request.POST.get('stars')
        if comment:
            title = request.POST.get('comment-title')
            review = Review(title=title, comment=comment, date=now)
            review.save()
            profile.reviews.add(review)
        elif pro_tag:
            try:
                tag = Tag.objects.get(title=pro_tag, isPro=1)
            except ObjectDoesNotExist:
                tag = Tag(title=pro_tag, isPro=1)
                tag.save()

            user_tag = UserTag(tag=tag)
            user_tag.save()
            profile.pro_tags.add(user_tag)
        elif con_tag:
            try:
                tag = Tag.objects.get(title=pro_tag, isPro=0)
            except ObjectDoesNotExist:
                tag = Tag(title=con_tag, isPro=0)
                tag.save()

            user_tag = UserTag(tag=tag)
            user_tag.save()
            profile.con_tags.add(user_tag)
        elif file:
            photo_form = PhotoForm(request.POST, request.FILES)
            if photo_form.is_valid():
                image = photo_form.save()
                profile.images.add(image)
        elif star_rating:
            rating = StarRating(value=star_rating, date=now)
            rating.save()
            profile.star_ratings.add(rating)

    # profile_id = request.POST.get('profile_id')

    total = 0
    count = 0
    for rating in profile.star_ratings.all():
        count += 1
        total += rating.value

    overall_rating = round(total / count, 0) if count else 0

    history = getHistory(profile)
    photo_form = PhotoForm()

    context = {
        'profile': profile,
        'rating': overall_rating,
        'history': history,
        'photo_form': photo_form
    }

    return render(request, 'core/profile.html', context)
Exemplo n.º 19
0
 def save_tags(self, tags, post):
     for tag in tags:
         t = Tag(tag=tag)
         t.save()
         t.post.add(post)