def CreateShop(): body = request.get_json() body['slug'] = slug.slug(body['name']) items = Shop(**body).save() path = '%s/public/%s' % (os.getcwd(), items.id) os.mkdir(path, 755) return Response(items.to_json(), mimetype="application/json", status=200)
def create_new(self): rv = Form.validate(self) if rv: shop = Shop() shop.init(self.name.data, self.address.data) db.session.add(shop) db.session.commit() self.shop = shop return True return False
def add_order_list(): ''' 批量或逐个加入采购单 ''' redis = RedisClient() user_login_dict = redis.get_login_info_by_img(session['QR']) cookie = user_login_dict.get('cookie') # 获取登录cookie # 查询参数 ids_json = request.args.get( 'ids' ) or '{"ids": ["5b7a6a093f3e1cceb46c84da", "5b7a6a023f3e1cceb46c84c1", "5b7a6c943f3e1cceb46c9f0e"]}' ids_dict = json.loads(ids_json) ids = ids_dict['ids'] order_list = [] if len(OrderCart.objects) < 50: for id in ids: if not OrderCart.objects(_id=ObjectId(id)): # 排除重复加入的订单 order_dict = Shop.objects( _id=ObjectId(id)).first().to_mongo().to_dict() order_list.append(order_dict) if order_list: final_order_list = taobao_query(order_list, cookie) for order_dict in final_order_list: OrderCart(**order_dict).save() result = {'status': 0, 'msg': '加入成功'} else: result = {'status': 1, 'msg': '商品已经在采购单里面了,无需重复添加'} else: result = {'status': 1, 'msg': '加入失败,最多只能加入50个商品'} return Response(json.dumps(result), mimetype='application/json')
def add_shop(): name = request.form.get('shop_name') city = request.form.get('shop_city') new_shop = Shop(name=name, city=city) db.session.add(new_shop) db.session.commit() return redirect('/shops')
def test_assign_disassign_worker(sel_log_admin): driver = sel_log_admin workplace_name = "test workplace" new_workplace = Shop(shopname=workplace_name) db.session.add(new_workplace) db.session.commit() test_user = "******" get_users.add_user(test_user, "test password", "3") driver.get("http://127.0.0.1:5000/workplace-worker-connect") workplace_elem = Select(driver.find_element_by_id("workplace")) worker_elem = Select(driver.find_element_by_id("worker")) workplace_elem.select_by_value(workplace_name) worker_elem.select_by_value(test_user) driver.find_element_by_id("submit").click() workplace = Shop.query.filter_by(shopname=workplace_name).first() user = User.query.filter_by(username=test_user).first() assert user in workplace.works.all() driver.get("http://127.0.0.1:5000/workplace-worker-connect") driver.find_element_by_id(workplace_name).click() driver.find_element_by_id("remove-%s" % test_user).click() assert user not in workplace.works.all() db.session.delete(new_workplace) db.session.delete(User.query.filter_by(username=test_user).first()) db.session.commit()
def register(): name = request.json.get('name') email = request.json.get('email') password = request.json.get('password') #if email exists shop = Shop.query.filter_by(email=email).first() if not shop is None: return jsonify({'message': 'User already exists!'}), 400 #add user to DB shoop = Shop(name=name, email=email) shop.set_password(password) db.session.add(shop) db.session.commit() token = jwt.encode( { 'id': shop.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta( seconds=current_app.config['SESSION_TOKEN_EXPIRY']) }, current_app.config['SECRET_KEY']) return jsonify({'token': token.decode('UTF-8')}), 200
def upload_sku(): ''' excel导入卖家sku ''' if request.method == 'POST': upload_data = request.get_records(field_name='file') # 检查卖家sku是否重复 sku_list = [item['SKU'] for item in upload_data if item['SKU'] != ''] for i in sku_list: if sku_list.count(i) > 1: result = {'status': 1, 'msg': '导入失败,卖家SKU:{}重复了'.format(i)} return Response(json.dumps(result), mimetype='application/json') # sku导入处理 match_sum, not_match_sum, forty_more_sum = 0, 0, 0 for item in upload_data: ob = Shop.objects(goods_url=item['商品链接']) if not ob: not_match_sum += 1 elif len(str(item['SKU'])) > 40: forty_more_sum += 1 else: ob.update_one(set__sku_id=str(item['SKU'])) match_sum += 1 result = { 'status': 0, 'msg': '导入成功!{0}个商品匹配成功,{1}个商品链接无法匹配,{2}个商品的SKU超过40个字符,插入失败'\ .format(match_sum, not_match_sum, forty_more_sum) } return Response(json.dumps(result), mimetype='application/json') return '''
def test_accept_request(self): a = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Administrator').first()) m = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Moderator').first()) user = User(name='sorvihead', password='******', role=Role.query.filter_by(name='User').first()) u = User(name='test', password='******') db.session.add_all([a, u, m, user]) db.session.commit() s = Shop(name='afi', shop_code='9066') d = Department(name='kids') r = Request(description='test', user=u, shop=s, department=d) r2 = Request(description='test2', user=u, shop=s, department=d) r3 = Request(description='test3', user=u, shop=s, department=d) db.session.add_all([s, d, r, r2, r3]) db.session.commit() a.accept_request(r) m.accept_request(r2) db.session.add(r) db.session.commit() self.assertTrue(r.approved) self.assertTrue(r2.approved) self.assertRaises(PermissionError, user.accept_request, r3)
def test_remove_from_department(self): a = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Administrator').first()) m = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Moderator').first()) user = User(name='sorvihead', password='******', role=Role.query.filter_by(name='User').first()) u = User(name='test', password='******') db.session.add_all([a, u, m, user]) db.session.commit() s = Shop(name='afi', shop_code='9066') d = Department(name='kids') a.add_to_shop(user, s) a.add_to_department(user, d) a.remove_from_department(user, d) self.assertFalse(user.department == d) a.add_to_department(user, d) a.remove_from_shop(user, s) self.assertFalse(user.department == d) a.add_to_shop(user, s) a.add_to_department(user, d) self.assertRaises(PermissionError, u.remove_from_department, user, d)
def create_default_shop(): shop_email = config['DEFAULT_SHOP_EMAIL'] shop = Shop(name='shop', email=shop_email, telephone='0499316385', address='rue machin 4311 liege') db.session.add(shop) db.session.commit()
def open_shop(): form = ShopForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): new_shop = Shop( name=form.name.data, owner_id=form.owner_id.data, description=form.description.data, city=form.description.data, state=form.state.data, country=form.country.data, ) db.session.add(new_shop) db.session.commit() return new_shop.to_dict() else: return {"errors": "invalid submission"}
def save_sku(): ''' 保存sku至shop商品库 ''' id = request.args.get('id') sku_id = request.args.get('skuId') shop_order = request.args.get('shopOrder') try: o_id = ObjectId(id) Shop.objects(_id=o_id).update_one(set__sku_id=sku_id) result = {'status': 0, 'msg': '请求成功'} except Exception: current_app.logger.error("sku can't be saved!", exc_info=True) result = {'status': 1, 'msg': '保存失败,网络有点问题,请稍后重试'} return Response(json.dumps(result), mimetype='application/json')
def search_view(): ''' 采购单关键词联想搜索 ''' # 查询字符串 goods_title = request.args.get('goodsTitle') sku_id = request.args.get('skuId') shop_list = [] if goods_title: queryset = Shop.objects( __raw__={'goods_title': { '$regex': goods_title }}) # 查询商品名称 for ob in queryset: ob_dict = ob.to_mongo().to_dict() shop_dict = { 'id': str(ob_dict['_id']), 'goodsTitle': ob_dict['goods_title'], 'skuId': ob_dict['sku_id'] } shop_list.append(shop_dict) if len(shop_list) == 10: # 取前10条记录 break if sku_id: queryset = Shop.objects(__raw__={'sku_id': { '$regex': sku_id }}) # 查询商家sku for ob in queryset: ob_dict = ob.to_mongo().to_dict() shop_dict = { 'id': str(ob_dict['_id']), 'goodsTitle': ob_dict['goods_title'], 'skuId': ob_dict['sku_id'] } shop_list.append(shop_dict) if len(shop_list) == 10: break if shop_list: result = {'status': 0, 'data': {'list': shop_list}, 'msg': '请求成功'} else: result = {'status': 1, 'msg': '没有找到相关商品'} return Response(json.dumps(result), mimetype='application/json')
def shop(): form = EditShopForm() if form.validate_on_submit(): shop = Shop(owner=form.owner.data, city=form.city.data, segment=form.segment.data, address=form.address.data, lat=form.lat.data, long=form.long.data) db.session.add(shop) db.session.commit() return redirect(url_for('main.index')) return render_template('shop.html', title='Shop', form=form)
def import_products(request): ProductInfo.objects.all().delete() Product.objects.all().delete() Category.objects.all().delete() Shop.objects.all().delete() dir = os.path.dirname(practice.__file__) file_path = os.path.join(dir, 'shop1.yaml') print(file_path) with open(file_path) as file: shop_dict = yaml.load(file, Loader=yaml.FullLoader) print(shop_dict) shop = shop_dict['shop'] shop_model = Shop(name=shop) shop_model.save() for category in shop_dict['categories']: category_model = Category(id=category['id'], name=category['name']) category_model.save() category_model.shops.add(shop_model) category_model.save() for good in shop_dict['goods']: product = Product( id=good['id'], category_id=good['category'], name=good['name'], ) product.save() product_info = ProductInfo(product=product, price=good['price'], price_rrc=good['price_rrc'], shop=shop_model, quantity=good['quantity']) product_info.save() return HttpResponse("You're looking at question OK")
def setUp(self) -> None: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() Role.insert_roles() a = User(name='admin', email='*****@*****.**', password='******') u1 = User(name='1', email='1', password='******') u2 = User(name='2', email='2', password='******') u3 = User(name='3', email='3', password='******') s = Shop(name='afi', shop_code='9066') u1.shop = s db.session.add_all([a, u1, u2, u3, s]) db.session.commit()
def post(self, args, **_kwargs): position = from_shape(Point(args['lng'], args['lat']), srid=4326) new_shop = Shop(name=args['name'], address=args['address'], position=position, withdrawn=False) new_shop.tags = [ ShopTag(name=tag, shop=new_shop) for tag in unique_stripped(args['tags']) ] db.session.add(new_shop) try: db.session.commit() except IntegrityError as e: db.session.rollback() if "shop_pna_c" in e.orig: return custom_error('Address/Position/Name', ['Same address, position and name with existing shop']), \ ErrorCode.BAD_REQUEST else: return custom_error( 'tags', ['Duplicate tags' ]), ErrorCode.BAD_REQUEST # we should never get here return shop_schema.dump(new_shop).data
def ShopCollection(id): categories = InternCategoriesShop(id) shop = Shop.objects().filter(id=id) for t in shop: items = { "id": str(t['id']), "name": t['name'], "email": t['email'], "nit": t['nit'], "phone": t['phone'], "address": t['address'], "shipping": t['shipping'], "_categories": json.loads(categories) } return items, 200
def create_shops(count=5): for _ in range(count): name = fk.company() email = fk.email() telephone = fk.phone_number() address = fk.street_address() shop = Shop(name=name, email=email, telephone=telephone, address=address) db.session.add(shop) try: db.session.commit() except IntegrityError: db.session.rollback()
def test_add_to_shop(self): a = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Administrator').first()) m = User(name='sorvihead', password='******', role=Role.query.filter_by(name='Moderator').first()) user = User(name='sorvihead', password='******', role=Role.query.filter_by(name='User').first()) u = User(name='test', password='******') db.session.add_all([a, u, m, user]) db.session.commit() s = Shop(name='afi', shop_code='9066') a.add_to_shop(user, s) self.assertTrue(user.shop == s) self.assertRaises(PermissionError, u.add_to_shop, user, s)
def new_workplace(): """ Adds new workplace to database. """ if acc_test.check_access(0) is False: return redirect(url_for("main.index")) form = NewWorkplaceForm() if form.validate_on_submit(): workplace = Shop(shopname=form.workplace_name.data) db.session.add(workplace) db.session.commit() flash("Stworzono nowy sklep") return redirect(url_for("main.index")) return render_template("acc_man/new_workplace.html", title="Grafiki - nowy sklep", form=form)
def fill_db_by_test_data(): shop = Shop(name="Test Shop").save() images = [ "https://vdxl.im/8718475964735_a_en_hd_1.jpg", "https://vdxl.im/8718475964735_g_en_hd_1.jpg", "https://vdxl.im/8718475964735_g_en_hd_2.jpg", "https://vdxl.im/8718475964735_g_en_hd_3.jpg", "https://vdxl.im/8718475964735_g_en_hd_4.jpg", ] categories = [ "Toys & Games/Toys/Kids Riding Vehicles/Push & Pedal Riding Vehicles", "Animals & Pet Supplies/Pet Supplies/Cat Supplies/Cat Beds", "Animals & Pet Supplies/Pet Supplies/Dog Supplies/Dog Apparel", "Animals & Pet Supplies/Pet Supplies/Dog Supplies/Dog Beds", ] description = "<p>This memory foam neck pillow will surely bring you" description += "a soft velvety feel and a comfortable sleeping experience at home." description += "</p><ul><li>Colour: White<br/></li><li>Dimensions: 50 x 30 x (7-10) cm (L x W x H)<br/></li>" description += "<li>Delivery includes 2 pcs of pillow</li><li>Fabric: Polyester: 100%</li></ul>(product_id: 2899)" for i in range(10): Product(sku=f"{100089 + i}", title=f"Test Product({i + 1})", category_path=categories[i % len(categories)], price=((i + 1) * 1.01), qty=i + 1, vidaxl_id=35084 + i, description=description).save(commit=False) Image(product_id=i + 1, url=randint(0, len(images))).save(commit=False) Category(shop_id=shop.id, path=categories[1]).save(commit=False) Category(shop_id=shop.id, path=categories[2]).save(commit=False) Configuration.set_value(shop_id=shop.id, name='MARGIN_PERCENT', value='20', path=categories[0]) Configuration.set_value(shop_id=shop.id, name='ROUND_TO', value='95', path=categories[1]) Configuration.set_value(shop_id=shop.id, name='LEAVE_VIDAXL_PREFIX', value=True, path=categories[2]) db.session.commit()
def add_shop(): #add shop if current_user.role < 3 or current_user.is_anonymous: #none return abort(404) #add_shop.html form = AddShopForm( ) #Takes the data in the database and adds the new item to the shop if form.validate_on_submit(): new_item = Shop(item_name=form.item_name.data, brand=form.brand.data, age=form.age.data, price=form.price.data, image=form.image.data) db.session.add(new_item) db.session.commit() flash("Item has been added") return render_template("add_shop.html", quest_answ=quest_answ, title="Add shop", form=form)
def index(): form = PurchaseForm() form.purchaser.choices = [(current_user.id, current_user.username)] + [ (u.id, u.username) for u in User.get_user_list().filter(User.id != current_user.id).all() ] if form.validate_on_submit(): language = guess_language(form.subject.data) if language == 'UNKNOWN' or len(language) > 5: language = '' shopname = form.shopname.data shop = Shop.query.filter_by(shopname=shopname).first() if shop is None: shop = Shop(shopname=shopname) db.session.add(shop) purchaser = User.query.get(form.purchaser.data) if purchaser is None: purchaser = current_user purchase = Purchase(purchase_date=form.purchase_date.data, value=form.value.data, seller=shop, subject=form.subject.data, author=current_user, language=language) purchaser.add_purchase(purchase) db.session.add(purchase) db.session.commit() flash(_l("Your purchase is traced now!")) return redirect(url_for('main.index')) else: page = request.args.get('page', 1, type=int) purchases = current_user.followed_purchases().paginate( page, current_app.config['ELEMENTS_PER_PAGE'], False) next_url = url_for('main.index', page=purchases.next_num) \ if purchases.has_next else None prev_url = url_for('main.index', page=purchases.prev_num) \ if purchases.has_prev else None return render_template('index.html', title=_l("Home Page"), form=form, purchases=purchases.items, next_url=next_url, prev_url=prev_url)
def home(request): wheels = Wheel.objects.all() navs = Nav.get_all() mustbuys = MustBuy.get_all() shops = Shop.get_all() shop1 = shops[0:1][0] shop2_3 = shops[1:3] # print(shops) # print(shop1) mainshows = MainShow.get_all() data = { 'wheels': wheels, 'navs': navs, 'mustbuys': mustbuys, 'shop1': shop1, 'shop2_3': shop2_3, 'shop3_7': shops[3:7], 'shop7_11': shops[7:11], 'mainshows': mainshows } return render(request, 'home.html', context=data)
def seed_shops(): shop1 = Shop( name="EucalyptusBlooms", shop_logo= "https://i.etsystatic.com/isla/4c301d/38481952/isla_500x500.38481952_saohan4m.jpg?version=0", owner_id=1, description="Eucalyptus & Lavender Shower, Bath and Boutquets", city="Charlotte", state="North Carolina", country="United States", num_sales=20836, store_link="https://www.etsy.com/shop/EucalyptusBlooms") shop2 = Shop( name="thenewplantco", shop_logo= "https://i.etsystatic.com/isla/067ac7/40353823/isla_500x500.40353823_7uavibj0.jpg?version=0", owner_id=2, description="We specialize in affordable and hard to find plants.", city="", state="", country="United States", num_sales=36416, store_link="https://www.etsy.com/shop/thenewplantco") shop3 = Shop( name="TropicalTouchPlants", shop_logo= "https://i.etsystatic.com/isla/049b31/41986207/isla_500x500.41986207_kt8arxu2.jpg?version=0", owner_id=3, description="Specializing in quality Tillandsias for over 30 years.", city="Clermont", state="Florida", country="United States", num_sales=3520, store_link="https://www.etsy.com/shop/TropicalTouchPlants") shop4 = Shop( name="ElementalBonsaiGardn", shop_logo= "https://i.etsystatic.com/isla/6f11dc/32315682/isla_500x500.32315682_92u3kapf.jpg?version=0", owner_id=4, description="Live bonsai, bamboo, small foliage, pottery, and more!", city="Kissimmee", state="Florida", country="United States", num_sales=13500, store_link="https://www.etsy.com/shop/ElementalBonsaiGardn") shop5 = Shop( name="IntoThePot", shop_logo= "https://i.etsystatic.com/isla/ef7190/41467576/isla_500x500.41467576_5md37oju.jpg?version=0", owner_id=5, description="Houseplants and accessories", city="Tampa", state="Florida", country="United States", num_sales=2012, store_link="https://www.etsy.com/shop/IntoThePot") shop6 = Shop( name="TwistedAcres", shop_logo= "https://i.etsystatic.com/isla/2253a0/35944568/isla_500x500.35944568_kx9kenk3.jpg?version=0", owner_id=6, description="AIR PLANTS TILLANDSIA TOP QUALITY", city="Fort Myers", state="Florida", country="United States", num_sales=107815, store_link="https://www.etsy.com/shop/TwistedAcres") shop7 = Shop( name="9Tree7", shop_logo= "https://i.etsystatic.com/isla/5db9d4/45647748/isla_500x500.45647748_kymzgfe0.jpg?version=0", owner_id=7, description="We sell cool plants", city="Columbus", state="Ohio", country="United States", num_sales=83, store_link="https://www.etsy.com/shop/9Tree7") shop8 = Shop( name="SnakeRiverGarden", shop_logo= "https://i.etsystatic.com/isla/3a907a/45128805/isla_500x500.45128805_i8tbmm3m.jpg?version=0", owner_id=8, description="Snake River Gardens", city="Filer", state="Idaho", country="United States", num_sales=7340, store_link="https://www.etsy.com/shop/SnakeRiverGarden") shop9 = Shop( name="Dorology", shop_logo= "https://i.etsystatic.com/isla/79f542/48490113/isla_500x500.48490113_k8ce3887.jpg?version=0", owner_id=9, description="House Plants, Succulents and Cactus", city="Hickory", state="North Carolina", country="United States", num_sales=1928, store_link="https://www.etsy.com/shop/Dorology") shop10 = Shop( name="GreenGardenFinds", shop_logo= "https://i.etsystatic.com/isla/e61f0e/47781475/isla_500x500.47781475_6wt65k2l.jpg?version=0", owner_id=10, description="Plant Seeds and Live Plants", city="", state="", country="", num_sales=267, store_link="https://www.etsy.com/shop/GreenGardenFinds") db.session.add(shop1) db.session.add(shop2) db.session.add(shop3) db.session.add(shop4) db.session.add(shop5) db.session.add(shop6) db.session.add(shop7) db.session.add(shop8) db.session.add(shop9) db.session.add(shop10) db.session.commit()
def participate(request): if request.user.is_authenticated(): return HttpResponseRedirect(reverse('my_account')) if request.method == "POST": shop_form = ParticipateForm(request.POST) login_form = CustomLoginForm() if shop_form.is_valid(): shop_first_name = shop_form.cleaned_data.get('contact_first_name') shop_last_name = shop_form.cleaned_data.get('contact_last_name') shop_contact_email = shop_form.cleaned_data.get('contact_email') shop_password = shop_form.cleaned_data.get('password') shop_retype_password = shop_form.cleaned_data.get('retype_password') user = User.objects.create_user(shop_contact_email, shop_contact_email, shop_password) user.first_name = shop_first_name user.last_name = shop_last_name user.save() shop = Shop(user = user) shop.name = shop_form.cleaned_data.get('name') shop.public_phone = shop_form.cleaned_data.get('public_phone') shop.address_line_1 = shop_form.cleaned_data.get('address_line_1') shop.address_line_2 = shop_form.cleaned_data.get('address_line_2') shop.city = shop_form.cleaned_data.get('city') shop.state = shop_form.cleaned_data.get('state') shop.zip_code = shop_form.cleaned_data.get('zipcode') shop.URL = shop_form.cleaned_data.get('website') coordinates = gmaps.geocode(shop.address_line_1+", "+shop.address_line_2+", "+shop.city+", "+shop.state+", "+shop.zipcode) shop.latitude = coordinates[0]['geometry']['location']['lat'] shop.latitude = coordinates[0]['geometry']['location']['lng'] shop.save() return HttpResponseRedirect(reverse('index')) else: shop_form = ParticipateForm() login_form = CustomLoginForm() return render(request, "participate.html", {'store_form': shop_form, 'form':login_form})
def Shops(): items = Shop.objects().to_json() return jsonify(items), 200
def ShopNit(id): items = Shop.objects().filter(nit=id).to_json() return Response(items, mimetype="application/json", status=200)
def ShopId(id): items = Shop.objects().get(id=id).to_json() return Response(items, mimetype="application/json", status=200)
def get_shop_list(): ''' 商品库信息组合去重及商品库模糊搜索功能 ''' # 查询参数 ww_id = request.args.get('wwId') or '' store_name = request.args.get('storeName') or '' goods_title = request.args.get('goodsTitle') or '' sku_id = request.args.get('skuId') or '' # 分页参数 page_num = int(request.args.get('pageNum') or 1) page_size = int(request.args.get('pageSize') or 20) # 从历史订单数据库更新数据到商品库,不覆盖原有数据,保证卖家sku的完整保留 one_record = Shop.objects.order_by('-_id').first() # 筛选shop中_id最大值的记录 max_id = one_record['_id'] if one_record else None if max_id: # 取出历史订单orders中大于此_id的记录 query_set = Orders.objects(_id__gt=max_id) else: # 商品库为空,取出历史订单所有记录 query_set = Orders.objects() if query_set: # 将查询结果去重并保存至shop中 only_records = query_set.aggregate( # 组合去重 { '$group': { '_id': {'goods_url': "$goods_url", 'goods_sku1': "$goods_sku1", 'goods_sku2': "$goods_sku2"}, 'id': {'$max': "$_id"}, # 取_id最大值 'goods_url': {'$first': "$goods_url"}, 'goods_title': {'$first': "$goods_title"}, 'goods_img': {'$first': "$goods_img"}, 'store_name': {'$first': "$store_name"}, 'ww_name': {'$first': "$ww_name"}, 'real_per_price': {'$first': "$real_per_price"}, 'goods_sku1': {'$first': "$goods_sku1"}, 'goods_sku2': {'$first': "$goods_sku2"} } } ) for item in only_records: item.pop('_id') item['_id'] = item.pop('id') item['sku_id'] = '' if not max_id: # 商品库为空,直接保存 Shop(**item).save() else: # 商品库不为空,查询无重复再保存 if not Shop.objects(goods_url=item['goods_url'], goods_sku1=item['goods_sku1'], goods_sku2=item['goods_sku2']): Shop(**item).save() # 商品库展示 if ww_id or store_name or goods_title or sku_id: # 条件查询(模糊查询) page_data = Shop.objects( Q(__raw__={'ww_name': { '$regex': ww_id }}) & Q(__raw__={'store_name': { '$regex': store_name }}) & Q(__raw__={'goods_title': { '$regex': goods_title }}) & Q(__raw__={'sku_id': { '$regex': sku_id }})).paginate(page=page_num, per_page=page_size) else: # 一般情况(无查询) page_data = Shop.objects().paginate(page=page_num, per_page=page_size) list_all_query = [] for item in page_data.items: new_each_result = OrderedDict() for k, v in MAPPING.items(): new_each_result[k] = str(item[v]) if item[v] else '' list_all_query.append(new_each_result) result = { 'status': 0, 'total': page_data.total, 'pageSize': page_size, 'pageNum': page_data.page, 'data': { 'list': list_all_query }, 'msg': '请求成功' } return Response(json.dumps(result), mimetype='application/json')