Beispiel #1
0
def entity_load(request):
    key = get_user_load_key(request.user)
    # debouncing using cache timeout
    loading = cache.get(key)
    if loading:
        return JSONResponse(data={'error': 'too many request'}, status=403)
    else:
        # after captcha , block user in 2 seconds
        cache.set(key, True, timeout=2)
        pass
    # debouncing end

    if request.method == "POST":
        _forms = EntityURLFrom(request=request, data=request.POST)
        if _forms.is_valid():
            _item_info = _forms.load()
            if 'entity_hash' in _item_info:
                _res = {
                    'status': 'EXIST',
                    'data': _item_info,
                }
            else:
                _res = {
                    'status': 'SUCCESS',
                    'data': _item_info,
                }
            return JSONResponse(data=_res)

    return JSONResponse(data={'error': 'request method not right'}, status=403)
Beispiel #2
0
 def post_ajax(self, request, *args, **kwargs):
     _forms = SKUForm(request.POST)
     if _forms.is_valid():
         _forms.save()
         return JSONResponse(data={'result': 1}, status=200)
     elif _forms.repeatstatus:
         return JSONResponse(data={'result': -1}, status=406)
     else:
         return JSONResponse(data={'result': 0}, status=400)
Beispiel #3
0
 def post_ajax(self, request, *args, **kwargs):
     instance = SKU.objects.get(pk=kwargs['pk'])
     _forms = SKUForm(request.POST, instance=instance)
     if _forms.is_valid():
         _forms.save()
         return JSONResponse(data={'result': 1}, status=200)
     elif _forms.repeatstatus:
         return JSONResponse(data={'result': -1}, status=406)
     else:
         return JSONResponse(data={'result': 0}, status=400)
Beispiel #4
0
def entity_note_comment(request,
                        nid,
                        template='web/entity/note/comment_list.html'):
    if request.method == "POST":
        if request.user.is_authenticated():
            _user = request.user
        else:
            return HttpResponseRedirect(reverse('web_login'))

        try:
            note = Note.objects.get(pk=nid)
        except Note.DoesNotExist:
            raise Http404
        _forms = CommentForm(note=note, user=_user, data=request.POST)
        if _forms.is_valid():

            comment = _forms.save()
            template = 'web/entity/note/comment.html'

            _t = loader.get_template(template)
            _c = RequestContext(request, {
                'comment': comment,
            })

            _data = _t.render(_c)

            return JSONResponse(
                data={
                    'data': _data,
                    'status': '1',
                },
                content_type='text/html; charset=utf-8',
            )
    else:
        _forms = CommentForm()

    _comment_list = Note_Comment.objects.filter(note_id=nid).normal()
    log.info(_comment_list.query)
    _t = loader.get_template(template)
    _c = RequestContext(request, {
        'comment_list': _comment_list,
        'note_id': nid,
        'forms': _forms
    })
    _data = _t.render(_c)

    return JSONResponse(
        data={
            'data': _data,
            'note_id': nid
        },
        content_type='text/html; charset=utf-8',
    )
Beispiel #5
0
def messages(request, template='notifications/messages/message.html'):
    _user = request.user
    _page = request.GET.get('page', 1)
    _timestamp = request.GET.get('timestamp',None)
    if _timestamp != None:
        _timestamp = datetime.fromtimestamp(float(_timestamp))
    else:
        _timestamp = datetime.now()

    el = Entity_Like.objects.popular()
    cids = Entity.objects.filter(pk__in=list(el)).annotate(dcount=Count('category')).values_list('category_id', flat=True)

    _categories = Sub_Category.objects.filter(id__in=list(cids), status=True)
    # too expensive ???

    # remove_user_list = GKUser.objects.deactive_user_list()
    # remove_user_list.append(_user.id)
    # remove_user_list = list(remove_user_list)
    remove_user_list = []
    remove_user_list.append(_user.id)
    message_list = _user.notifications.filter(timestamp__lt=_timestamp).exclude(actor_object_id__in=remove_user_list)

    paginator = ExtentPaginator(message_list, 5)

    try:
        _messages = paginator.page(_page)
    except PageNotAnInteger:
        _messages = paginator.page(1)
    except EmptyPage:
        raise Http404

    _user.notifications.mark_all_as_read()
    if request.is_ajax():
        if not _messages.object_list:
            res = {
                'status': 0,
                'msg': 'no data'
            }
        else:
            _t = loader.get_template('notifications/messages/partial/ajax_notification.html')
            _c = RequestContext(request, {
                'messages': _messages,
            })
            _data = _t.render(_c)
            res = {
                'status': 1,
                'data': _data,
            }
        return JSONResponse(data=res, content_type='text/html; charset=utf-8',)

    return render_to_response(
        template,
        {
            'messages': _messages,
            'categories': random.sample(_categories, 6),
            # 'category': category,
        },
        context_instance = RequestContext(request),
    )
Beispiel #6
0
def entity_update_note(request, nid):
    if request.method == "POST":
        _user = request.user
        _forms = NoteForm(request.POST, user=_user, nid=nid)
        if _forms.is_valid():
            note = _forms.update()
            return JSONResponse(data={'result': '1', 'note': note.note})
    return HttpResponseNotAllowed
Beispiel #7
0
def poke(request, note_id):
    if request.is_ajax():
        _user = request.user

        try:
            np = Note_Poke.objects.get(user=_user, note_id=note_id)
            np.delete()
            return JSONResponse(data={'result': '0', "note_id": note_id})
        except Note_Poke.DoesNotExist:
            np = Note_Poke(
                user=_user,
                note_id=note_id,
            )
            np.save()
        return JSONResponse(data={'result': '1', 'note_id': note_id})
    else:
        return HttpResponseNotAllowed
Beispiel #8
0
    def get_ajax(self, request, *args, **kwargs):
        template = loader.get_template('web/main/partial/new_entity_ajax.html')
        req_context = RequestContext(request, self.get_context_data())

        return JSONResponse(data={
            'data': template.render(req_context),
            'status': 1
        },
                            content_type='text/html; charset=utf-8')
Beispiel #9
0
def upload_avatar(request):
    _user = request.user
    if request.method == 'POST':
        _forms = AvatarForm(_user, request.POST, request.FILES)
        if _forms.is_valid():
            _forms.save()
            return JSONResponse(status=200,
                                data={'avatar_url': _user.profile.avatar_url})
        log.info(_forms.errors)
    return HttpResponseNotAllowed
Beispiel #10
0
def entity_note_comment_delete(request, comment_id):
    if request.is_ajax():
        _user = request.user
        try:
            comment = Note_Comment.objects.get(user=_user, pk=comment_id)
            comment.delete()
            return JSONResponse(data={'status': 1})
        except:
            raise Http404

    return HttpResponseNotAllowed
Beispiel #11
0
    def get_ajax(self, request, *args, **kwargs):
        self.tag_id = request.GET.get('dataValue')
        self.object_list = getattr(self, 'object_list', self.get_queryset())

        template = loader.get_template(
            'web/tags/partial/new_tag_article_item_ajax.html')
        req_context = RequestContext(request, self.get_context_data())

        return JSONResponse(data={
            'data': template.render(req_context),
            'status': 1
        },
                            content_type='text/html; charset=utf-8')
Beispiel #12
0
 def get_ajax(self, request, *args, **kwargs):
     self.object_list = getattr(self, 'object_list', self.get_queryset())
     context = self.get_context_data()
     template = 'web/main/partial/selection_ajax.html'
     _t = loader.get_template(template)
     _c = RequestContext(request, context)
     _data = _t.render(_c)
     return JSONResponse(
         data={
             'data': _data,
             'status': 1
         },
         content_type='text/html; charset=utf-8',
     )
Beispiel #13
0
def entity_unlike(request, eid):
    if request.is_ajax():
        _user = request.user
    else:
        return HttpResponseNotAllowed
    try:
        if settings.DEBUG:
            el = Entity_Like.objects.get(entity_id=eid, user=_user)

            el.delete()
        else:
            unlike_task.delay(uid=_user.id, eid=eid)
        return JSONResponse(data={'status': 0})
    except Entity_Like.DoesNotExist:
        raise Http404
Beispiel #14
0
def entity_like(request, eid):
    if request.is_ajax():
        _user = request.user
        try:
            if settings.DEBUG:
                el, created = Entity_Like.objects.get_or_create(
                    user=_user,
                    entity_id=eid,
                )

            else:
                like_task.delay(uid=_user.id, eid=eid)

            return JSONResponse(data={'status': 1})
        except Exception, e:
            log.error("ERROR: %s", e.message)
Beispiel #15
0
def entity_post_note(request,
                     eid,
                     template='web/entity/partial/ajax_detail_note.html'):
    if request.method == 'POST':
        _user = request.user
        _eid = eid

        _forms = NoteForm(request.POST, user=_user, eid=_eid)
        if _forms.is_valid():
            note = _forms.save()
            _t = loader.get_template(template)
            _c = RequestContext(request, {'note': note, 'note_forms': _forms})
            _data = _t.render(_c)
            return JSONResponse(
                data={
                    'status': 1,
                    'data': _data,
                },
                content_type='application/json; charset=utf-8',
            )
    raise HttpResponseNotAllowed
Beispiel #16
0
def list(request, template='management/category/list.html'):
    #
    # c = request.GET.get('c', '1')
    if request.is_ajax():

        res = {}
        # res[''] = {}
        categories = Category.objects.all()

        for c in categories:
            res[c.id] = []
            for s in c.sub_categories.all().order_by('alias'):
                res[c.id].append({
                    'category_id': s.id,
                    'category_title': s.title,
                })
                # log.info(s)
        return JSONResponse(res)
        # return HttpResponse(json.dumps(res))

    page = request.GET.get('page', 1)

    categories = Category.objects.all().order_by('-status')

    paginator = ExtentPaginator(categories, 30)
    try:
        category_list = paginator.page(page)
    except PageNotAnInteger:
        category_list = paginator.page(1)
    except EmptyPage:
        raise Http404

    return render_to_response(
        template,
        {
            # 'current_category_id': int(category_id),
            'category_list': category_list,
            # 'sub_categories': sub_categories,
        },
        context_instance=RequestContext(request))
Beispiel #17
0
 def render_to_json_response(self, context, **response_kwargs):
     if context:
         return JSONResponse(self.get_data(context), **response_kwargs)
     return ErrorJsonResponse(status=404)
Beispiel #18
0
def event(request, slug, template='web/events/home'):
    _page_num = request.GET.get('p', 1)
    _slug = slug
    try:
        event = Event.objects.get(slug=_slug)
        template = template + '_%s.html' % _slug
    except Event.DoesNotExist:
        raise Http404

    try:
        loader.get_template(template)
    except TemplateDoesNotExist:
        template = "web/events/home.html"

    hash_str = md5(event.tag.encode('utf-8')).hexdigest()
    tag = Tags.objects.get(hash=hash_str)
    inner_qs = Content_Tags.objects.filter(tag=tag, target_content_type=24) \
        .values_list('target_object_id', flat=True).using('slave')
    log.info(inner_qs.query)
    _eid_list = Note.objects.filter(pk__in=list(inner_qs)).values_list(
        'entity_id', flat=True).using('slave')

    _entity_list = Entity.objects.filter(id__in=list(set(_eid_list)), status=Entity.selection) \
        .filter(selection_entity__is_published=True, selection_entity__pub_time__lte=datetime.now()) \
        .using('slave')

    # here is some dirty code for 1111 event
    top_entities_list = None
    top_entities_list_like = list()
    if event.toptag:
        top_tag_name = event.toptag
        # TODO: 此部分逻辑太复杂,查询太多,影响性能
        try:
            top_tag = Tags.objects.get(name=top_tag_name)

            note_id_list = Content_Tags.objects \
                .filter(tag=top_tag, target_content_type_id=24) \
                .values_list("target_object_id", flat=True) \
                .using('slave')

            top_entities_id_list = Note.objects \
                .filter(pk__in=list(note_id_list)) \
                .values_list('entity_id', flat=True) \
                .using('slave')

            top_entities_filter = Q(pk__in=list(top_entities_id_list))
            top_entities_filter &= Q(selection_entity__is_published=True)
            top_entities_filter &= Q(
                selection_entity__pub_time__lte=datetime.now())
            top_entities_list = Entity.objects.filter(
                top_entities_filter).using('slave')

            if request.user.is_authenticated():
                top_entities_list_like = Entity_Like.objects \
                    .filter(entity_id__in=top_entities_list, user=request.user) \
                    .values_list('entity_id', flat=True).using('slave')

        except Tags.DoesNotExist as e:
            pass

    _paginator = ExtentPaginator(_entity_list, 12)

    try:
        _entities = _paginator.page(_page_num)
    except PageNotAnInteger:
        _entities = _paginator.page(1)
    except EmptyPage:
        raise Http404

    el = list()
    if request.user.is_authenticated():
        e = _entities.object_list
        el = Entity_Like.objects.filter(entity_id__in=list(e),
                                        user=request.user).values_list(
                                            'entity_id', flat=True)
        el = list(el) + list(top_entities_list_like)

    _show_event_banners = Show_Event_Banner.objects.filter(event=event,
                                                           position__gt=0)
    _show_editor_recommendations = Show_Editor_Recommendation.objects.filter(
        event=event, position__gt=0)

    _show_editor_recommendations_entity = Show_Editor_Recommendation.objects \
        .filter(event=event, section='entity', position__gt=0).order_by('position')

    _show_editor_recommendations_fair = Show_Editor_Recommendation.objects \
        .filter(event=event, section='fair', position__gt=0).order_by('position')

    _show_editor_recommendations_shop = Show_Editor_Recommendation.objects \
        .filter(event=event, section='shop', position__gt=0).order_by('position')

    if request.is_ajax():
        _ret = {'status': 0, 'msg': '没有更多数据'}

        if _entity_list:
            log.info(_entities)
            _t = loader.get_template(
                'web/events/partial/event_entity_list.html')
            try:
                _c = RequestContext(request, {
                    'user_entity_likes': el,
                    'entities': _entities,
                })

                _data = _t.render(_c)
            except Exception, e:
                log.error('render error', e.message)
                _data = list()

            _ret = {'status': '1', 'data': _data}
        return JSONResponse(
            data=_ret,
            content_type='text/html; charset=utf-8',
        )
Beispiel #19
0
            follower=_fans,
            followee_id=user_id,
        )
        raise Http404
    except User_Follow.DoesNotExist, e:
        uf = User_Follow(
            follower=_fans,
            followee_id=user_id,
        )
        uf.save()

    try:
        reverse_uf = User_Follow.objects.get(follower_id=user_id,
                                             followee=_fans)
        # mutual following
        return JSONResponse(data={'status': 2})

    except User_Follow.DoesNotExist:
        return JSONResponse(data={'status': 1})


@login_required
@csrf_exempt
def unfollow_action(request, user_id):
    _fans = request.user

    try:
        uf = User_Follow.objects.get(
            follower=_fans,
            followee_id=user_id,
        )