Exemplo n.º 1
0
    def get(self, request):
        '''
        添加商品评论
        :param request:
        :return:
        '''
        ret = {}

        commodity_id = request.GET['id']

        auth_cookie = WechatUtils.checkMemberLogin(request)
        score = request.GET['score']

        content = request.GET['content']

        member_id = auth_cookie.id
        Comment.objects.create(content=content,
                               joined_date=datetime.datetime.now(),
                               commodity_id=commodity_id,
                               member_id=auth_cookie.id)
        Transaction.objects.filter(
            Q(member_id=member_id)
            & Q(commodity_id=commodity_id)).update(rating=score)
        ret['msg'] = "评论成功"
        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 2
0
    def post(self, request):
        '''
        :param request: 小程序的请求
        :return:  返回成功信息
        '''
        ret = {}
        auth_cookie = WechatUtils.checkMemberLogin(request)
        member_id = auth_cookie.id
        now = datetime.datetime.now()  # 现在的时间
        last_behave = Credit.objects.filter(Q(userid_id=member_id) & Q(behave=2))
        if last_behave:
            last_share_date = last_behave.last().createtime  # 上次分享的时间

            if now.strftime('%Y-%m-%d') != last_share_date.strftime('%Y-%m-%d'):
                ret['first_time_share'] = '恭喜你,今天首次分享获得3积分'
                Credit.objects.create(
                    behave=2,
                    creditpoints=3,
                    credittype=0,
                    createtime=datetime.datetime.now(),
                    userid_id=member_id
                )
        else:
            Credit.objects.create(
                behave=2,
                creditpoints=3,
                credittype=0,
                createtime=datetime.datetime.now(),
                userid_id=member_id
            )
        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 3
0
 def post(self, request):
     ret = {}
     commodity_ids = request.POST['goods'].split(',')
     print("goods", request.POST['goods'])
     print("goods", type(commodity_ids))
     auth_cookie = WechatUtils.checkMemberLogin(request)
     member_id = auth_cookie.id
     for commodity_id in commodity_ids:
         Cart.objects.filter(
             Q(commodity_id=commodity_id)
             & Q(member_id=member_id)).delete()
     return HttpResponse(ret, content_type='application/json')
Exemplo n.º 4
0
 def get(self, request):
     ret = {}
     fields = ['id', 'imUrl', 'title', 'present_price']
     auth_cookie = WechatUtils.checkMemberLogin(request)
     member_id = auth_cookie.id
     cart_list = Cart.objects.filter(member_id=member_id)
     commodity_list = []
     for cart in cart_list:
         commodity = Commodity.objects.filter(id=cart.commodity_id).values(
             *fields).first()
         commodity_list.append(commodity)
     ret = json.dumps(dict(data=commodity_list), cls=DjangoJSONEncoder)
     return HttpResponse(ret, content_type='application/json')
Exemplo n.º 5
0
    def get(self, request):
        ret = {}
        commodity_id = request.GET['id']
        auth_cookie = WechatUtils.checkMemberLogin(request)
        member_id = auth_cookie.id

        cart_list = Cart.objects.filter(
            Q(member_id=member_id) & Q(commodity_id=commodity_id))
        if cart_list:
            ret['msg'] = "已经加入收藏"
        else:
            Cart.objects.create(member_id=member_id, commodity_id=commodity_id)
            ret['msg'] = "加入收藏成功"
        return HttpResponse(json.dumps(ret), content_type='application/json')
    def get(self, request):
        p = int(request.GET['p'])
        user = WechatUtils.checkMemberLogin(request)
        user_id = user.id
        recommendations = Users_AllRecommendations.objects.filter(
            user_id=user_id)
        '''
        ※※※这里有个关键问题,由于后端算法和数据库的链接原因,这边得到的Commodityidlist实际上是String类型(只是看起来像list),不能直接转
        成List使用,所以需要使用split方法把它切分成list。
        '''
        commodityidlist = recommendations[0].products_id
        commodityidlist = commodityidlist.split(',')

        commoditylist = []

        page_size = 10  #每页显示的商品数量
        '''
        前端会返回一个值,p:当前页数,以下代码判断该次Get行为是否会超出列表长度。
        每次只查找page_size个值,性能优秀Perfect。
        '''
        have_been_showed_commodityid = p * page_size
        if (have_been_showed_commodityid + page_size > len(commodityidlist)):
            has_more = False
            for i in range(have_been_showed_commodityid,
                           len(commodityidlist) -
                           have_been_showed_commodityid):

                item_id = commodityidlist[i]
                commodity = Commodity.objects.filter(
                    id=item_id.lstrip()).values().first()
                commoditylist.append(commodity)
        else:
            has_more = True
            for i in range(have_been_showed_commodityid,
                           have_been_showed_commodityid + page_size):
                item_id = commodityidlist[i]
                commodity = Commodity.objects.filter(
                    id=item_id.lstrip()).values().first()
                commoditylist.append(commodity)

        ret = dict(data=commoditylist)
        ret["has_more"] = has_more
        ret = json.dumps(ret, cls=DjangoJSONEncoder)
        return HttpResponse(ret, content_type='application/json')
    def get(self, request):
        user = WechatUtils.checkMemberLogin(request)
        user_id = user.id
        recommendations = Users_Recommendations.objects.filter(user_id=user_id)
        commodityidlist = []

        for i in recommendations:
            commodityidlist.append([
                i.product_id_1, i.product_id_2, i.product_id_3, i.product_id_4,
                i.product_id_5
            ])

        commoditylist = []
        for item_id in commodityidlist[0]:
            commodity = Commodity.objects.filter(id=item_id).values().first()
            commoditylist.append(commodity)

        ret = dict(data=commoditylist)

        ret = json.dumps(ret, cls=DjangoJSONEncoder)
        return HttpResponse(ret, content_type='application/json')
Exemplo n.º 8
0
    def get(self, request):
        ret = {}
        ua = request.META.get("HTTP_AUTHORIZATION")
        print("ua:", ua)

        auth_cookie = WechatUtils.checkMemberLogin(request)
        print('auth_cookie:', auth_cookie)

        ret['id'] = auth_cookie.id
        ret['openid'] = auth_cookie.openid
        ret['pic_name'] = auth_cookie.pic_name
        ret['nickname'] = auth_cookie.nickname
        ret['gender'] = auth_cookie.gender
        ret['city'] = auth_cookie.city
        ret['province'] = auth_cookie.province
        # ret['last_login_date'] = auth_cookie.last_login_date 不能json化
        ret['avatarUrl'] = auth_cookie.avatarUrl
        ret['codeVerify'] = auth_cookie.codeVerify
        ret['type'] = auth_cookie.type

        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 9
0
    def get(self, request):
        print("进入方法")
        user = WechatUtils.checkMemberLogin(request)
        user_id = user.id
        boughtitems = Transaction.objects.filter(member_id=user_id)
        boughtitemkindlist = []

        boughtitemdict = {
            'Baby': 0,
            'Beauty': 0,
            'Grocery_and_Gourmet_Food': 0,
            'Electronics': 0,
            'Office_Products': 0,
            'Pet_Supplies': 0,
            'Sports_and_Outdoors': 0,
            'Home_and_Kitchen': 0,
        }
        commoditylist = []
        sum_of_boughtitem = len(boughtitems)
        for boughtitem in boughtitems:
            boughtitemkindlist.append(
                boughtitem.commodity.categories.type_name)
            boughtitemdict[boughtitem.commodity.categories.type_name] += 1
            '''
            该用户若是购买了两件以上或者25%以上某种类商品,则给他推送该种类下随机五件商品,注意,Order_by方法损耗较大
            但还是最优随机选择方法。
            '''
        for type in boughtitemdict:
            if (boughtitemdict[type] >= 2
                    or boughtitemdict[type] / sum_of_boughtitem >= 0.25):
                recommendations = Commodity.objects.filter(
                    categories__type_name=type).order_by('?')[:5].values()
                commoditylist += recommendations

        random.shuffle(commoditylist)
        ret = dict(data=commoditylist)
        ret = json.dumps(ret, cls=DjangoJSONEncoder)
        return HttpResponse(ret, content_type='application/json')
Exemplo n.º 10
0
    def get(self, request):
        """
        获取会员基本信息,并返回小程序端
        :param request:
        :return:
        """
        ret = {}

        auth_cookie = WechatUtils.checkMemberLogin(request)

        ret['id'] = auth_cookie.id
        ret['openid'] = auth_cookie.openid
        ret['pic_name'] = auth_cookie.pic_name
        ret['nickname'] = auth_cookie.nickname
        ret['gender'] = auth_cookie.gender
        ret['city'] = auth_cookie.city
        ret['province'] = auth_cookie.province
        # ret['last_login_date'] = auth_cookie.last_login_date 不能json化
        ret['avatarUrl'] = auth_cookie.avatarUrl
        ret['codeVerify'] = auth_cookie.codeVerify
        ret['type'] = auth_cookie.type

        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 11
0
    def post(self, request):
        """
        小程序登陆业务逻辑实现-post方法
        :param request:
        :return:
        """
        ret = {'code': 200, 'msg': '操作成功', 'data': {}}
        code = request.POST['code']
        code_verify = request.POST['codeVerify'] if request.POST[
            'codeVerify'] else ''

        if not code:
            ret['code'] = 500
            ret['msg'] = '无效的code请求'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        openid = WechatUtils.getOpenid(code)

        if openid is None:
            ret['code'] = 500
            ret['msg'] = 'openid出错'
            ret = {'result': 'false', 'msg': 'openid出错'}
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        if code_verify == '-1':
            ret['code'] = 500
            ret['msg'] = '无效的code请求'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        nickname = request.POST['nickName'] if request.POST['nickName'] else ''
        gender = request.POST['gender'] if request.POST['gender'] else ''
        city = request.POST['city'] if request.POST['city'] else ''
        province = request.POST['province'] if request.POST['province'] else ''
        avatar_url = request.POST['avatarUrl'] if request.POST[
            'avatarUrl'] else ''

        # 判断是否已经注册过
        bind_info = Member.objects.filter(codeVerify=code_verify, openid=0)

        print('bind_info')
        print(bind_info)

        # 正常注册的情况,通过code bind_info 不为空
        if bind_info:
            Member.objects.filter(id=bind_info[0].id).update(
                openid=openid,
                nickname=nickname,
                gender=gender,
                city=city,
                province=province,
                avatarUrl=avatar_url,
                state=0,
                type=1,
                joined_date2=datetime.datetime.now(),
                last_login_date=datetime.datetime.now())

        print(bind_info.values_list())

        print(bind_info.first())

        if bind_info.first() is not None:
            now = datetime.datetime.now()  # 现在的时间
            last_login_date = Member.objects.get(
                id=bind_info[0].id).last_login_date  # 上次登录的时间

            if now.strftime('%Y-%m-%d') != last_login_date.strftime(
                    '%Y-%m-%d'):
                # 今天第一次登陆
                print("今天第一次登录")
                ret['first_time_login'] = '******'
                print("credit insert:")
                Credit.objects.create(behave=0,
                                      creditpoints=2,
                                      credittype=0,
                                      createtime=datetime.datetime.now(),
                                      userid_id=bind_info[0].id)

            Member.objects.filter(id=bind_info[0].id).update(
                last_login_date=datetime.datetime.now()
            )  # 每次登陆更新last_login_date

        token = ""
        if bind_info.first():
            token = "%s#%s" % (WechatUtils.geneAuthCode(
                id=bind_info.first().id,
                codeVerify=bind_info.first().codeVerify,
                state=bind_info.first().state,
                type=bind_info.first().type,
            ), bind_info.first().id)
            ret['user_id'] = bind_info.first().id
        else:
            token = "%s#%s" % (WechatUtils.geneAuthCode(
                id='-1',
                codeVerify='-1',
                state='0',
                type='0',
            ), -1)
            ret['user_id'] = '-1'

        ret['data'] = {'token': token}

        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 12
0
        def post(self, request):
            """
            接受base64编码的人脸数据,并把商品数据生成订单
            :param request:
            :return:
            """
            ret = dict(status="fail")

            # 接受前端传递过来的uuid -- 判别始于哪一个商家
            img = request.POST['img']

            img1 = img.replace('data:image/png;base64,', '')
            newdata = base64.b64decode(img1)

            memberid = str(uuid.uuid1()).replace('-', '')

            image_path1 = BASE_DIR + os.sep + "media" + os.sep + "face" + os.sep + datetime.datetime.now(
            ).strftime('%Y-%m-%d')

            if not os.path.exists(image_path1):
                os.mkdir(image_path1)

            image_path = image_path1 + os.sep + memberid + '.png'

            try:
                with open(image_path, 'wb') as file:
                    file.write(newdata)
            except FileNotFoundError as fnfe:
                print(fnfe)

            # opencv读取图片,开始进行人脸识别
            img = misc.imread(os.path.expanduser(image_path), mode='RGB')
            # 设置默认插入时 detect_multiple_faces =False只检测图中的一张人脸,True则检测人脸中的多张
            # 一般入库时只检测一张人脸,查询时检测多张人脸
            images = image_array_align_data(img,
                                            image_path,
                                            pnet,
                                            rnet,
                                            onet,
                                            detect_multiple_faces=False)

            # 设置返回结果

            ret = {}

            # 判断如果如图没有检测到人脸则直接返回
            if len(images.shape) < 4:
                ret['info'] = '没有人脸信息,请重新输入,以确保有人脸信息'

                print(ret)
                return HttpResponse(json.dumps(ret),
                                    content_type="application/json")

            feed_dict = {
                images_placeholder: images,
                phase_train_placeholder: False
            }
            # emb_array保存的是经过facenet转换的128维的向量
            emb_array = sess.run(embeddings, feed_dict=feed_dict)

            face_query = Matrix()

            code_verify = WechatUtils.genCode()

            # 不让生成已经存在的验证码
            while Member.objects.filter(codeVerify=code_verify):
                code_verify = WechatUtils.genCode()

            if code_verify == '-1':
                ret['info'] = '验证码非法操作'
                return HttpResponse(json.dumps(ret),
                                    content_type="application/json")

            # 分别获取距离该图片中人脸最相近的人脸信息
            # pic_min_scores 是数据库中人脸距离(facenet计算人脸相似度根据人脸距离进行的)
            # pic_min_names 是当时入库时保存的文件名
            # pic_min_uid  是对应的用户id
            # if face_query.get_socres(emb_array) is not None:
            pic_min_scores, pic_min_names, pic_min_uid = face_query.get_socres(
                emb_array)
            for i in range(0, len(pic_min_scores)):
                if pic_min_scores[i] < MAX_DISTINCT:
                    ret['faceid'] = pic_min_uid[i]
                    ret['distance'] = pic_min_scores[i]
                    ret['picname'] = pic_min_names[i]

            print(ret)

            if not ret:
                # 新建一个用户
                is_video = Member.objects.filter(codeVerify=code_verify)
                print('isVideo')
                print(is_video.exists())
                if not is_video.exists():
                    print('进来了')
                    for j in range(0, len(emb_array)):
                        Member.objects.create(
                            faceid=memberid,
                            pic_name=memberid + "_" + str(j) + ".png",
                            face_json=",".join(
                                str(li) for li in emb_array[j].tolist()),
                            joined_date1=datetime.datetime.now(),
                            codeVerify=code_verify.lower())

                    ret['type'] = 1  # 表示新用户
                    ret['codeVerify'] = code_verify
                    ret['info'] = 'success, add a face new'
            else:
                # 更新操作  已知用户

                ret['type'] = 0  # 表示老用户
                ret['codeVerify'] = Member.objects.filter(
                    faceid=ret['faceid']).first().codeVerify
                ret['info'] = 'update'

            # 作为一个多次购物的用户,
            # 作为一个第一次注册的用户,
            member_foreign = Member.objects.filter(
                codeVerify=ret['codeVerify'].lower()).first()

            # 不能用于检验验证码

            print('member_foreign')
            print(member_foreign)

            if member_foreign is None:
                ret['state'] = '当前用户未识别'

                return HttpResponse(json.dumps(ret),
                                    content_type="application/json")

            # 生成一条订单
            if request.POST['param'] is None or request.POST['param'] == {}:
                ret['state'] = '订单错误'

                return HttpResponse(json.dumps(ret),
                                    content_type="application/json")

            orderid = str(int(time.time() * 1000)) + str(uuid.uuid1()).replace(
                '-', '')[0:10]

            param = eval(request.POST['param'])
            total = 0
            for key_value in param.items():
                comm = Commodity.objects.filter(id=key_value[0])
                total += float(comm[0].present_price) * int(key_value[1])
                Transaction.objects.create(rating=3,
                                           num=key_value[1],
                                           member=member_foreign,
                                           commodity=comm[0],
                                           joined_date=datetime.datetime.now(),
                                           orderid=orderid)

            Credit.objects.create(behave=4,
                                  creditpoints=int(total),
                                  credittype=0,
                                  createtime=datetime.datetime.now(),
                                  userid=member_foreign)

            print('结果展示')
            print(ret)
            return HttpResponse(json.dumps(ret),
                                content_type="application/json")
Exemplo n.º 13
0
    def post(self, request):
        """
        会员状态验证-post方法
        :param request:
        :return:
        """
        ret = {'code': 200, 'msg': '操作成功', 'data': {}}

        code = request.POST['code']
        code_verify = request.POST['codeVerify'] if request.POST[
            'codeVerify'] else ''

        if not code:
            ret['code'] = 500
            ret['msg'] = '无效的请求code'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        openid = WechatUtils.getOpenid(code)

        if openid is None:
            ret['code'] = 500
            ret['msg'] = 'openid出错'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        if code_verify == '-1':
            ret['code'] = 500
            ret['msg'] = '无效的code请求'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        bind_info = Member.objects.filter(openid=openid)

        if not bind_info:
            ret['code'] = 500
            ret['msg'] = '未绑定'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        now = datetime.datetime.now()  # 现在的时间
        last_login_date = Member.objects.get(
            id=bind_info[0].id).last_login_date  # 上次登录的时间

        if now.strftime('%Y-%m-%d') != last_login_date.strftime('%Y-%m-%d'):
            # 今天第一次登陆
            print("今天第一次登录")
            ret['first_time_login'] = '******'
            print("credit insert:")
            Credit.objects.create(behave=0,
                                  creditpoints=2,
                                  credittype=0,
                                  createtime=datetime.datetime.now(),
                                  userid_id=bind_info[0].id)

        Member.objects.filter(id=bind_info[0].id).update(
            last_login_date=datetime.datetime.now())  # 每次登陆更新last_login_date

        token = "%s#%s" % (WechatUtils.geneAuthCode(
            id=bind_info.values_list()[0][0],
            codeVerify=bind_info.values_list()[0][13],
            state=bind_info.values_list()[0][12],
            type=bind_info.values_list()[0][14],
        ), bind_info.values_list()[0][0])
        ret['data'] = {'token': token}
        ret['user_id'] = bind_info.values_list()[0][0]
        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 14
0
    def post(self, request):

        ret = {'code': 200, 'msg': '操作成功', 'data': {}}
        code = request.POST['code']
        codeVerify = request.POST['codeVerify'] if request.POST[
            'codeVerify'] else ''

        if not code or len(code) < 1:
            ret['code'] = 500
            ret['msg'] = '无效的code请求'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        openid = WechatUtils.getOpenid(code)

        if openid is None:
            ret['code'] = 500
            ret['msg'] = 'openid出错'
            ret = {'result': 'false', 'msg': 'openid出错'}
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        if codeVerify == '-1':
            ret['code'] = 500
            ret['msg'] = '无效的code请求'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        nickname = request.POST['nickName'] if request.POST['nickName'] else ''
        gender = request.POST['gender'] if request.POST['gender'] else ''
        city = request.POST['city'] if request.POST['city'] else ''
        province = request.POST['province'] if request.POST['province'] else ''
        avatarUrl = request.POST['avatarUrl'] if request.POST[
            'avatarUrl'] else ''

        # 判断是否已经注册过
        bind_info = Member.objects.filter(codeVerify=codeVerify)
        # 正常注册的情况,通过code
        if bind_info:
            Member.objects.filter(id=bind_info[0].id).update(
                openid=openid,
                nickname=nickname,
                gender=gender,
                city=city,
                province=province,
                avatarUrl=avatarUrl,
                state=0,  # 0 表示正常 1 表示异常
                type=1,  # 0普通用户 1 高级用户
                joined_date2=datetime.datetime.now(),  # 用户注册时间
                last_login_date=datetime.datetime.now()  # 最后一次登录时间
            )

        print(bind_info.values_list())
        token = ""
        if bind_info:
            token = "%s#%s" % (WechatUtils.geneAuthCode(
                id=bind_info.values_list()[0][0],
                codeVerify=bind_info.values_list()[0][13],
                state=bind_info.values_list()[0][12],
                type=bind_info.values_list()[0][14],
            ), bind_info.values_list()[0][0])
        else:
            token = "%s#%s" % (WechatUtils.geneAuthCode(
                id='-1',
                codeVerify='-1',
                state='0',
                type='0',
            ), -1)

        ret['data'] = {'token': token}
        return HttpResponse(json.dumps(ret), content_type='application/json')
Exemplo n.º 15
0
    def post(self, request):

        ret = {'code': 200, 'msg': '操作成功', 'data': {}}

        code = request.POST['code']
        codeVerify = request.POST['codeVerify'] if request.POST[
            'codeVerify'] else ''

        print('code:', code)
        print('codeVerify:', codeVerify)

        if not code or len(code) < 1:
            ret['code'] = 500
            ret['msg'] = '无效的请求code'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        openid = WechatUtils.getOpenid(code)

        if openid is None:
            ret['code'] = 500
            ret['msg'] = 'openid出错'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        if codeVerify == '-1':
            ret['code'] = 500
            ret['msg'] = '无效的code请求'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        bind_info = Member.objects.filter(openid=openid)

        if not bind_info:
            ret['code'] = 500
            ret['msg'] = '未绑定'
            return HttpResponse(json.dumps(ret),
                                content_type='application/json')

        now = datetime.datetime.now()
        # Member.objects.filter(id=bind_info[0].id)

        Member.objects.filter(id=bind_info[0].id).update(
            last_login_date=datetime.datetime.now())  # 每次登陆更新last_login_date

        # print("credit insert:")
        # Credit.objects.create(
        #     behave=0,
        #     points=2,
        #     type=0,
        #     createtime=datetime.datetime.now(),
        #     userid_id=43
        # )

        token = "%s#%s" % (WechatUtils.geneAuthCode(
            id=bind_info.values_list()[0][0],
            codeVerify=bind_info.values_list()[0][13],
            state=bind_info.values_list()[0][12],
            type=bind_info.values_list()[0][14],
        ), bind_info.values_list()[0][0])
        ret['data'] = {'token': token}
        ret['user_id'] = bind_info.values_list()[0][0]
        return HttpResponse(json.dumps(ret), content_type='application/json')