예제 #1
0
 def get(self, request, photo_pk):
     photo = get_object_or_404(Photo, pk=photo_pk)
     action = Action()
     action.action_type = Action.KUDU
     action.user = request.user
     action.content_object = photoaction.save()
     return Response(action)
예제 #2
0
 def post(self, request, **kwargs):
     try:
         photo = Photo.objects.get(pk=self.kwargs.get("pk"))
     except:
         return JsonResponse({'message': 'Photo not found'})
     kudu_count = photo.kudu_count
     if kudu_count == 1:
         person_text = "Person"
     else:
         person_text = "People"
     text = "%s gave this<br />a kudu" % person_text
     if request.user.id is None:
         return JsonResponse({'message': 'You will need to sign in', 'kudus': kudu_count, 'text': text})
     else:
         if Action.objects.filter(action_type="K", user=request.user, content_type__model='photo', photo=photo).count():
             return JsonResponse(
                 {'message': 'Thanks, but you already gave a kudu', 'kudus': kudu_count, 'text': text})
         else:
             action = Action()
             action.content_type = ContentType.objects.get(model='photo')
             action.object_id = photo.id
             action.content_object = photo
             action.user = request.user
             action.action_type = 'K'
             action.save()
             photo.update_kudu_count()
             photo.check_and_send_kudu_email()
             if photo.kudu_count == 1:
                 person_text = "Person"
             else:
                 person_text = "People"
             text = "%s gave this<br />a kudu" % person_text
             message = "Thank you for giving a kudu"
             return JsonResponse({'message': message, 'kudus': photo.kudu_count, 'text': text})
예제 #3
0
    def post(self, request, **kwargs):

        try:
            obj = TourOperatorReview.objects.filter(
                pk=self.kwargs.get("pk")).first()
        except:
            return JsonResponse({'message': 'Review not found'})
        kudu_count = obj.kudu_count
        if kudu_count == 1:
            person_text = "Person"
        else:
            person_text = "People"
        text = "%s gave this<br />a kudu" % person_text

        if request.user.id is None:
            return JsonResponse({
                'message': 'You will need to sign in',
                'kudus': kudu_count,
                'text': text
            })
        else:
            if Action.objects.filter(action_type="K",
                                     user=request.user,
                                     tour_operator_review=obj).count():
                return JsonResponse({
                    'message': 'Thanks, but you already gave a kudu',
                    'kudus': kudu_count,
                    'text': text
                })
            else:
                action = Action()
                action.content_type = ContentType.objects.get(
                    model='touroperatorreview')
                action.object_id = obj.id
                action.content_object = obj
                action.user = request.user
                action.action_type = 'K'
                action.save()

                obj.update_kudu_count()
                if obj.kudu_count == 1:
                    person_text = "Person"
                else:
                    person_text = "People"
                text = "%s gave this<br /> a kudu" % person_text
                message = "Thank you for giving a kudu"
                return JsonResponse({
                    'message': message,
                    'kudus': obj.kudu_count,
                    'text': text
                })
    def handle(self, *args, **options):
        # not allowed in production
        if not settings.DEBUG:
            self.stdout.write(self.style.ERROR("DEBUG is off"))
        db = MySQLdb.connect(host=options['db_host'],
                             db=options['db_name'],
                             user=options['db_user'],
                             password=options['db_pass'])
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        created, updated = 0, 0
        photos = Photo.objects.filter(tour_operator_review__isnull=False)
        for photo in photos:
            photo.park_review = None
            photo.save()
        TourOperatorReview.objects.all().delete()
        #touroperatorreview
        cursor.execute("""
        SELECT
            touroperator.name,
            user.email_address,
            user.id as user_id,
            touroperatorreview.*
        FROM
            touroperatorreview,
            touroperator,
            user
        WHERE
            touroperator.id = touroperatorreview.touroperator_id AND
            user.id = touroperatorreview.user_id
        """)
        result = cursor.fetchall()
        for c in result:
            newdict = {}
            newdict['title'] = c.pop('review_title')
            newdict['slug'] = c.pop('review_title_slugged')
            newdict['content'] = c.pop('review_copy')
            newdict['pearls_of_wisdom'] = c.pop('pearls_of_wisdom')
            newdict['email_sent'] = c.pop('email_sent') == '1'
            newdict['rejection_text'] = c.pop('rejection_text')
            newdict['friend_recommend'] = c.pop('friend_recommend') == 'Yes'
            newdict['overall_rating'] = c.pop('overall_rating')

            newdict['safari_type'], dymmy = SafariType.objects.get_or_create(
                name=c.pop('safari_type'))
            days_booked = c.pop('days_booked')
            if days_booked == '30+':
                days_booked = 30
            newdict['days_booked'] = days_booked
            newdict['did_not_go'] = c.pop('did_not_go_flag') != None
            newdict['vehicle_rating'] = c.pop('vehicle_rating')
            newdict['meet_and_greet_rating'] = c.pop('meet_and_greet_rating')
            newdict['responsiveness_rating'] = c.pop('responsiveness_rating')
            newdict['safari_quality_rating'] = c.pop('safari_quality_rating')
            newdict['itinerary_quality_rating'] = c.pop(
                'itinerary_quality_rating')
            newdict['start_date'] = c.pop('start_date')

            newdict['response'] = c.pop('response')
            newdict['response_date'] = c.pop('response_date')
            newdict['response_email_sent'] = c.pop('response_email_sent')

            date_created = c.pop('date_created')
            if date_created:
                date_created = make_aware(date_created)
            newdict['date_created'] = date_created
            newdict['find_out'] = c.pop('find_out_about')

            date_modified = c.pop('date_modified')
            if date_modified:
                date_modified = make_aware(date_modified)
            newdict['date_modified'] = date_modified

            date_deleted = c.pop('date_deleted')
            if date_deleted:
                date_deleted = make_aware(date_deleted)
            newdict['date_deleted'] = date_deleted
            newdict['user'] = User.objects.get(username=c.pop('email_address'))
            try:
                newdict['tour_operator'] = TourOperator.objects.get(
                    name=c['name'])
            except ObjectDoesNotExist:
                print('Tour ' + str(c['name']) + 'doesnotexists')
                continue
            exists_slug = TourOperatorReview.objects.filter(
                slug=newdict['slug'])
            if exists_slug:
                newdict['slug'] = newdict['slug'] + '-' + str(c.pop('user_id'))

            status = c.pop('status')
            if status == "active":
                newdict['status'] = TourOperatorReview.ACTIVE
            if status == "pending":
                newdict['status'] = TourOperatorReview.PENDING
            if status == "rejected":
                newdict['status'] = TourOperatorReview.REJECTED

            obj = TourOperatorReview(**newdict)

            obj.save()
            created += 1
            #touroperatorreview_activity
            SQL = """
            select activity.activity_name
            FROM
            touroperatorreview_activity, activity
            WHERE
            touroperatorreview_activity.activity_id = activity.id AND
            touroperatorreview_activity.touroperatorreview_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                animal = Activity.objects.get(name_old=c_['activity_name'])
                obj.activities.add(animal)

            SQL = "SELECT uuid FROM photo where album_id = %i"
            cursor.execute(SQL % c['album_id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                try:
                    photo = Photo.objects.get(uuid_value=c_['uuid'])
                    photo.tour_operator_review = obj
                    photo.save()
                except Photo.DoesNotExist:
                    pass

            # touroperatorreview_animal
            SQL = """
            select animal.animal_name
            FROM
            touroperatorreview_animal, animal
            WHERE
            touroperatorreview_animal.animal_id = animal.id AND
            touroperatorreview_animal.touroperatorreview_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                animal = Animal.objects.get(name=c_['animal_name'])
                obj.animals.add(animal)

            # touroperatorreview_park
            SQL = """
            select park.park_name
            FROM
            touroperatorreview_park, park
            WHERE
            touroperatorreview_park.park_id = park.id AND
            touroperatorreview_park.touroperatorreview_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                park = Park.objects.get(name=c_['park_name'])
                obj.parks.add(park)

            # touroperatorreview_countryindex
            SQL = """
            select countryindex.country_name
            FROM
            touroperatorreview_countryindex, countryindex
            WHERE
            touroperatorreview_countryindex.countryindex_id = countryindex.id AND
            touroperatorreview_countryindex.touroperatorreview_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                countri_index = CountryIndex.objects.get(
                    name=c_['country_name'])
                obj.country_indexes.add(countri_index)

            #touroperatorreviewvisit
            #cursor.execute("""
            #SELECT
            #    touroperatorreviewvisit.*,
            #    user.email_address as email_address
            #FROM
            #    touroperatorreviewvisit
            #    LEFT JOIN user ON user.id = touroperatorreviewvisit.user_id
            #WHERE
            #    touroperatorreviewvisit.touroperatorreview_id = %s
            #""" % c['id'])
            #result = cursor.fetchall()
            #for c_ in result:
            #    newdict = {}
            #    newdict['date_created'] = make_aware(c_.pop('timestamp'))
            #    newdict['ip_address'] = c_.pop('ip_address')
            #    newdict['referer'] = c_.pop('referer')
            #    newdict['country_short'] = c_.pop('country_code')
            #    newdict['content_object'] = obj
            #    newdict['activity_type'] = 'CLICK'
            #    email_add = c_.pop('email_address')
            #    if email_add != None:
            #        newdict['user'] = User.objects.get(username=email_add)
            #    obj_analitics = Analytic(**newdict)
            #    obj_analitics.save()

            #touroperatorreviewhelpful
            cursor.execute("""
            SELECT 
                touroperatorreviewhelpful.timestamp,
                user.email_address as email_address
            FROM
                touroperatorreviewhelpful
                LEFT JOIN user ON user.id = touroperatorreviewhelpful.user_id
            WHERE
                touroperatorreviewhelpful.touroperatorreview_id = %s
            """ % c['id'])
            result = cursor.fetchall()
            for c_ in result:
                newdict = {}
                newdict['content_object'] = obj
                newdict['date_created'] = make_aware(c_.pop('timestamp'))
                newdict['action_type'] = Action.KUDU
                email_add = c_.pop('email_address')
                if email_add != None:
                    newdict['user'] = User.objects.get(username=email_add)
                obj_act = Action(**newdict)
                obj_act.save()
            obj.save()

        #touroperatorreviewlead TODO what is it?

        message = 'Imported %i updated %i touroperatorreviews' % (created,
                                                                  updated)

        self.stdout.write(self.style.SUCCESS(message))
예제 #5
0
    def handle(self, *args, **options):
        # not allowed in production
        users = {}
        if not settings.DEBUG:
            self.stdout.write(self.style.ERROR("DEBUG is off"))
        db = MySQLdb.connect(host=options['db_host'],
                             db=options['db_name'],
                             user=options['db_user'],
                             password=options['db_pass'])
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        created, updated = 0, 0
        cursor.execute("select COUNT(*) as count FROM photo")
        r = cursor.fetchone()
        count = r['count']
        Photo.objects.all().delete()
        cursor.execute("""select 
        photo.*,
        touroperator.name as tour_operator,
        countryindex.country_name as countryindex,
        park.park_name as park,
        activity.activity_name as activity,
        email_address
        from 
        photo 
        LEFT JOIN touroperator ON photo.touroperator_id = touroperator.id
        LEFT JOIN user ON user.id = photo.user_id
        LEFT JOIN countryindex ON photo.countryindex_id = countryindex.id
        LEFT JOIN park ON photo.park_id = park.id
        LEFT JOIN activity ON photo.activity_id = activity.id
        """)
        result = cursor.fetchall()
        skipped = 0
        smaller = 0
        hashes = {}
        for c in result:
            tour_operator_name = c['tour_operator']
            tour_operator_obj = False
            if tour_operator_name:
                try:
                    tour_operator_obj = TourOperator.objects.get(
                        name=tour_operator_name)
                except ObjectDoesNotExist:
                    print('Tour ' + str(c['tour_operator']) + 'doesnotexists')
                    continue
            username = c.pop('email_address')
            try:
                user = User.objects.get(username=username)
            except ObjectDoesNotExist:
                user = None
                pass
            newdict = {}
            newdict['uuid_value'] = c.pop('uuid')
            if not newdict['uuid_value']:
                print("UUID is null", c.pop("id"))
                continue
            newdict['caption'] = c.pop('caption')
            newdict['date_created'] = make_aware(c.pop('date_created'))
            newdict['user'] = user
            date_modified = c.pop('date_modified')
            if date_modified:
                date_modified = make_aware(date_modified)
            newdict['date_modified'] = date_modified
            if tour_operator_obj:
                newdict['tour_operator'] = tour_operator_obj
            if c['countryindex']:
                newdict['country_index'] = CountryIndex.objects.get(
                    name=c.pop('countryindex'))
            if c['park']:
                newdict['park'] = Park.objects.get(name=c.pop('park'))
            if c['activity']:
                newdict['activity'] = Activity.objects.get(
                    name_old=c.pop('activity'))
            uuid = newdict.pop('uuid_value')
            print(uuid)
            obj, is_created = Photo.objects.update_or_create(uuid_value=uuid,
                                                             defaults=newdict)
            if is_created:
                created += 1
            else:
                # obj.image.delete(save=True)
                print('updated')
                updated += 1
            #idk why uuid is changed
            obj.uuid_value = uuid
            tags = c['tags']
            if tags != None and tags != '':
                tags = tags.split(',')
                for tag in tags:
                    if tag != '':
                        o_tag, _ = Tag.objects.update_or_create(name=tag[:999])
                        obj.tags.add(o_tag)

            if c['gallery_path']:
                cur_image_path = '%sroot%s' % (
                    options['base_location'],
                    c['gallery_path'],
                )

                if os.path.exists(cur_image_path):
                    filename, file_extension = os.path.splitext(cur_image_path)
                    openedFile = open(cur_image_path, 'rb')
                    readFile = openedFile.read()
                    md5Hash = hashlib.md5(readFile)
                    md5Hashed = md5Hash.hexdigest()
                    if md5Hashed in hashes:
                        skipped += 1
                        print('uuid duplicated file ' + str(obj.uuid_value))
                        obj.date_deleted = timezone.now()
                    hashes[md5Hashed] = 1

                    month = newdict['date_created'].month
                    year = newdict['date_created'].year
                    image_path = "/images/photos/%s/%s/" % (year, month)
                    os.makedirs(settings.MEDIA_ROOT + image_path,
                                exist_ok=True)
                    image_path += ("image_%d%s" %
                                   (obj.id, file_extension.lower()))
                    dst_image_path = settings.MEDIA_ROOT + image_path
                    copyfile(cur_image_path, dst_image_path)
                    obj.image = image_path[1:]
            if obj.image.width < 300 and obj.image.height < 300:
                smaller += 1
                print("image %s is skipped by its size %d ,%d" %
                      (obj.image, obj.image.width, obj.image.height))
                continue
            SQL = """
            select animal.animal_name
            FROM
            photo_animal, animal
            WHERE
            photo_animal.animal_id = animal.id AND
            photo_animal.photo_id = '%i'
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                animal = Animal.objects.get(name=c_['animal_name'])
                obj.animals.add(animal)

            # comments
            cursor.execute("""
            SELECT
                photocomment.*, user.email_address as email_address
            FROM
                photocomment
                LEFT JOIN user ON user.id = photocomment.user_id
            WHERE
                photocomment.photo_id = '%i'
            """ % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                Comment.objects.filter(content_type__model='Photo').delete()
                comment = Comment()
                comment.comment = c_.pop('photo_comment')
                email_add = c_.pop('email_address')
                try:
                    user = User.objects.get(username=email_add)
                except ObjectDoesNotExist:
                    print("User" + email_add + "dont exists")
                    continue
                comment.user = user
                comment.date_created = make_aware(c_.pop('timestamp'))
                comment.content_object = obj
                comment.save()

            # photo kudus
            cursor.execute("""
            SELECT 
                photolike.timestamp,
                user.email_address as email_address
            FROM
                photolike
                LEFT JOIN user ON user.id = photolike.user_id
            WHERE
                photolike.photo_id = %s
            """ % c['id'])
            result = cursor.fetchall()
            for c_ in result:
                newdict_ = {}
                newdict_['content_object'] = obj
                newdict_['date_created'] = make_aware(c_.pop('timestamp'))
                newdict_['action_type'] = Action.KUDU
                email_add = c_.pop('email_address')
                if email_add != None:
                    newdict_['user'] = User.objects.get(username=email_add)
                obj_act = Action(**newdict_)
                obj_act.save()
            obj.save()

            # photovisit
            SQL = """
            SELECT 
                photovisit.*, photo.uuid, user.email_address as email_address,
                photovisit.user_id
            FROM
                photo, photovisit
                LEFT JOIN user ON user.id = photovisit.user_id
            WHERE
                photovisit.photo_id = photo.id
                AND photo.uuid = '%s'
            """
            cursor.execute(SQL % uuid)
            result_ = cursor.fetchall()
            for c_ in result_:
                analytic = Analytic()
                analytic.content_object = obj
                analytic.date_created = make_aware(c_.pop('timestamp'))
                analytic.ip_address = c_.pop('ip_address')
                analytic.referer = c_.pop('referer')
                #analytic.country_code = c_.pop('country_code')
                analytic.activity_type = 'VISIT'
                email_add = c_.pop('email_address')
                if email_add != None:
                    if not email_add in users:
                        try:
                            users[email_add] = User.objects.get(
                                username=email_add)
                            analytic.user = users[email_add]
                        except ObjectDoesNotExist:
                            print("User" + email_add + "dont exists")
                    else:
                        analytic.user = users[email_add]
                    analytic.save()
            obj.save()
        message = 'Imported %i updated %i skipped %i (%i by size) photos' % (
            created, updated, skipped, smaller)

        self.stdout.write(self.style.SUCCESS(message))
    def handle(self, *args, **options):
        # not allowed in production
        if not settings.DEBUG:
            self.stdout.write(self.style.ERROR("DEBUG is off"))
        db = MySQLdb.connect(
            host=options['db_host'],
            db=options['db_name'],
            user=options['db_user'],
            password=options['db_pass'],
            charset='utf8',
            use_unicode=True,
        )
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        created, updated = 0, 0
        comments = 0
        cursor.execute("""
        select article.*, user.email_address as user_email, articlecategory.name as category_name from
        article, user, articlecategory
        WHERE
        article.user_id = user.id AND
        article.category_id = articlecategory.id
        """)
        Comment.objects.filter(content_type__model='article').delete()
        result = cursor.fetchall()
        for c in result:
            newdict = {}
            newdict['title'] = c.pop('title')
            newdict['title_short'] = c.pop('title_short')
            newdict['highlights'] = c.pop('highlights')
            newdict['content'] = c.pop('article_copy')
            newdict['source'] = c.pop('source')
            newdict['image_caption'] = c.pop('image_caption')
            newdict['slug'] = c.pop('title_slugged')[:499]
            if c['status'] == 'active':
                newdict['article_status'] = 'PUBLISHED'
            if c['status'] == 'pending':
                newdict['article_status'] = 'DRAFT'
            newdict['date_created'] = make_aware(c.pop('date_created'))
            newdict['meta_title'] = c.pop('meta_title')
            newdict['meta_keywords'] = c.pop('meta_keywords')
            newdict['meta_description'] = c.pop('meta_description')

            newdict['user'] = User.objects.get(email=c['user_email'])
            category_name = c.pop('category_name')
            obj, is_created = Article.objects.update_or_create(
                title=newdict.pop('title'), defaults=newdict)

            #search all images
            soup = BeautifulSoup(obj.content)
            imgs = soup.findAll("img", {"alt": True, "src": True})
            for img in imgs:
                img_url = img["src"]
                print(img_url)
                filename = img_url.split("/")[-1]
                r = requests.get(img_url, stream=True)
                if r.status_code == 200:
                    # Set decode_content value to True, otherwise the downloaded image file's size will be zero.
                    r.raw.decode_content = True
                    #save the image in the django media dir
                    filename = 'uploads/imported_articles/%s' % filename
                    fs = FileSystemStorage()
                    filename = fs.save(filename, r.raw)
                    uploaded_file_url = fs.url(filename)
                    obj.content = obj.content.replace(img_url,
                                                      uploaded_file_url)
                    print(uploaded_file_url)
                    print('*')
            obj.save()

            obj.date_created = newdict['date_created']
            if is_created:
                created += 1
            else:
                obj.image.delete(save=True)
                updated += 1
            obj.categories.set([Category.objects.get(name=category_name)])
            if c['image_path']:
                image_path = '%sroot/%s' % (
                    options['base_location'],
                    c['image_path'],
                )
                if os.path.exists(image_path):
                    image_file = open(image_path, "rb")
                    obj.image.save("image_%s" % obj.pk,
                                   File(image_file),
                                   save=True)

            if c['image_raw']:
                image_raw_path = '%sroot/%s' % (
                    options['base_location'],
                    c['image_raw'],
                )
                if os.path.exists(image_raw_path):
                    image_raw_file = open(image_raw_path, "rb")
                    obj.image_raw.save("image_%s" % obj.pk,
                                       File(image_raw_file),
                                       save=True)

            SQL = """
            select activity.activity_name
            FROM
            article_activity, activity
            WHERE
            article_activity.activity_id = activity.id AND
            article_activity.article_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                park = Activity.objects.get(name_old=c_['activity_name'])
                obj.activities.add(park)
            SQL = """
            select animal.animal_name
            FROM
            article_animal, animal
            WHERE
            article_animal.animal_id = animal.id AND
            article_animal.article_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                park = Animal.objects.get(name=c_['animal_name'])
                obj.animals.add(park)
            SQL = """
            select countryindex.country_name
            FROM
            article_countryindex, countryindex
            WHERE
            article_countryindex.countryindex_id = countryindex.id AND
            article_countryindex.article_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                country_index = CountryIndex.objects.get(
                    name=c_['country_name'])
                obj.country_indexes.add(country_index)
            SQL = """
            select park.park_name
            FROM
            article_park, park
            WHERE
            article_park.park_id = park.id AND
            article_park.article_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                country_index = Park.objects.get(name=c_['park_name'])
                obj.parks.add(country_index)
            SQL = """
            select articlecomment.*, user.email_address
            FROM
            articlecomment, user
            WHERE
            user.id = articlecomment.user_id AND
            articlecomment.article_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                comment = Comment()
                user = User.objects.get(email=c_['email_address'])
                if not user:
                    print('in articles, ' + c_['email_address'] +
                          ' user does not exists')
                    continue
                comment.user = user
                comment.content_object = obj
                comment.comment = c_['comment']
                comment.date_created = make_aware(c_.pop('timestamp'))
                comment.save()
                comments += 1

            #article kudus
            cursor.execute("""
            SELECT 
                articlekudu.timestamp,
                user.email_address as email_address
            FROM
                articlekudu
                LEFT JOIN user ON user.id = articlekudu.user_id
            WHERE
                articlekudu.article_id = %s
            """ % c['id'])
            result = cursor.fetchall()
            for c_ in result:
                newdict = {}
                newdict['content_object'] = obj
                newdict['date_created'] = make_aware(c_.pop('timestamp'))
                newdict['action_type'] = Action.KUDU
                email_add = c_.pop('email_address')
                if email_add != None:
                    newdict['user'] = User.objects.get(username=email_add)
                obj_act = Action(**newdict)
                obj_act.save()
            obj.save()
        message = 'Imported %i updated %i articles and %i comments' % (
            created, updated, comments)
        self.stdout.write(self.style.SUCCESS(message))
예제 #7
0
    def handle(self, *args, **options):
        # not allowed in production
        if not settings.DEBUG:
            self.stdout.write(self.style.ERROR("DEBUG is off"))
        db = MySQLdb.connect(host=options['db_host'],
                             db=options['db_name'],
                             user=options['db_user'],
                             password=options['db_pass'])
        cursor = db.cursor(MySQLdb.cursors.DictCursor)
        created, updated = 0, 0
        photos = Photo.objects.filter(park_review__isnull=False)
        for photo in photos:
            photo.park_review = None
            photo.save()
        ParkReview.objects.all().delete()
        #parkreview
        cursor.execute("""
        SELECT
            park.park_name,
            user.email_address,
            parkreview.*,
            user.id as user_id
        FROM
            parkreview,
            park,
            user
        WHERE
            park.id = parkreview.park_id AND
            user.id = parkreview.user_id
        """)
        result = cursor.fetchall()
        for c in result:
            newdict = {}
            newdict['title'] = c.pop('review_title')
            newdict['slug'] = c.pop('review_title_slugged')[:255]
            newdict['content'] = c.pop('review_copy')
            newdict['pearls_of_wisdom'] = c.pop('pearls_of_wisdom')
            newdict['rejection_text'] = c.pop('rejection_text')
            newdict['friend_recommend'] = c.pop('friend_recommend') == 'Yes'
            newdict['days_booked'] = c.pop('days_booked')
            newdict['email_sent'] = c.pop('email_sent') == '1'
            newdict['overall_rating'] = c.pop('overall_rating')
            newdict['quality_wildlife_rating'] = c.pop(
                'quality_wildlife_rating')
            newdict['quality_lodging_rating'] = c.pop('quality_lodging_rating')
            newdict['crowdedness_rating'] = c.pop('crowdedness_rating')
            newdict['book_lodging'] = c.pop('book_lodging') == 'Yes'

            date_created = c.pop('date_created')
            if date_created:
                date_created = make_aware(date_created)
            newdict['date_created'] = date_created

            date_modified = c.pop('date_modified')
            if date_modified:
                date_modified = make_aware(date_modified)
            newdict['date_modified'] = date_modified

            date_deleted = c.pop('date_deleted')
            if date_deleted:
                date_deleted = make_aware(date_deleted)
            newdict['date_deleted'] = date_deleted

            visit_date = c.pop('visit_date')
            newdict['visit_date'] = visit_date
            newdict['user'] = User.objects.get(username=c.pop('email_address'))
            newdict['park'] = Park.objects.get(name=c.pop('park_name'))
            exists_slug = ParkReview.objects.filter(slug=newdict['slug'])
            if exists_slug:
                newdict['slug'] = newdict['slug'] + '-' + str(c.pop('user_id'))

            status = c.pop('status')
            if status == "active":
                newdict['status'] = ParkReview.ACTIVE
            if status == "pending":
                newdict['status'] = ParkReview.PENDING
            if status == "rejected":
                newdict['status'] = ParkReview.REJECTED

            obj = ParkReview(**newdict)
            obj.save()
            created += 1

            SQL = "SELECT uuid FROM photo where album_id = %i"
            cursor.execute(SQL % c['album_id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                try:
                    photo = Photo.objects.get(uuid_value=c_['uuid'])
                    photo.park_review = obj
                    photo.save()
                except Photo.DoesNotExist:
                    pass
            #parkreview_activity
            SQL = """
            select activity.activity_name
            FROM
            parkreview_activity, activity
            WHERE
            parkreview_activity.activity_id = activity.id AND
            parkreview_activity.parkreview_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                animal = Activity.objects.get(name_old=c_['activity_name'])
                obj.activities.add(animal)

            # parkreview_animal
            SQL = """
            select animal.animal_name
            FROM
            parkreview_animal, animal
            WHERE
            parkreview_animal.animal_id = animal.id AND
            parkreview_animal.parkreview_id = %i
             """
            cursor.execute(SQL % c['id'])
            result_ = cursor.fetchall()
            for c_ in result_:
                animal = Animal.objects.get(name=c_['animal_name'])
                obj.animals.add(animal)

            #parkreviewvisit
            #cursor.execute("""
            #SELECT
            #    parkreviewvisit.*,
            #    user.email_address as email_address
            #FROM
            #    parkreviewvisit
            #    LEFT JOIN user ON user.id = parkreviewvisit.user_id
            #WHERE
            #    parkreviewvisit.parkreview_id = %s
            #""" % c['id'])
            #result = cursor.fetchall()
            #for c_ in result:
            #    newdict = {}
            #    newdict['date_created'] = make_aware(c_.pop('timestamp'))
            #    newdict['ip_address'] = c_.pop('ip_address')
            #    newdict['referer'] = c_.pop('referer')
            #    newdict['country_short'] = c_.pop('country_code')
            #    newdict['content_object'] = obj
            #    newdict['activity_type'] = 'CLICK'
            #    email_add = c_.pop('email_address')
            #    if email_add != None:
            #        newdict['user'] = User.objects.get(username=email_add)
            #    obj_analitics = Analytic(**newdict)
            #    obj_analitics.save()

            #parkreviewhelpful
            cursor.execute("""
            SELECT 
                parkreviewhelpful.timestamp,
                user.email_address as email_address
            FROM
                parkreviewhelpful
                LEFT JOIN user ON user.id = parkreviewhelpful.user_id
            WHERE
                parkreviewhelpful.parkreview_id = %s
            """ % c['id'])
            result = cursor.fetchall()
            for c_ in result:
                newdict = {}
                newdict['content_object'] = obj
                newdict['date_created'] = make_aware(c_.pop('timestamp'))
                newdict['action_type'] = Action.KUDU
                email_add = c_.pop('email_address')
                if email_add != None:
                    newdict['user'] = User.objects.get(username=email_add)
                obj_act = Action(**newdict)
                obj_act.save()
            obj.save()

        message = 'Imported %i updated %i parkreviews' % (created, updated)

        self.stdout.write(self.style.SUCCESS(message))