예제 #1
0
    def test_basic(self):
        stream = StringIO.StringIO()

        stream_out = StreamDataStorage(stream)

        doc1 = Product(id="432", kids="1", price="1,0")
        doc2 = Product(id="231", kids="0", price="2")
        doc3 = Product(id="313", kids="1", price="3,0")

        docs = [doc1, doc2, doc3]

        stream_out.save_data(docs)

        stream.seek(0)
        stream_in = StreamDataSource(stream)

        doc2.price = "99,9"

        update_product(stream_in.get_data(), stream_out, doc2)

        stream.seek(0)
        new_docs = list(stream_in.get_data())

        self.assertEqual(len(new_docs), 3)
        self.assertTrue(
            (new_docs[0].price == "99,9") or
            (new_docs[1].price == "99,9") or
            (new_docs[2].price == "99,9")
        )
예제 #2
0
    def test_delete(self):
        u1 = User(login='******', password='******')
        u2 = User(login='******', password='******')
        p = Product(type=1234567890, serial=123456, week=45, year=15)
        c = Comment(body='comment body', author_id=u1.id, product_id=p.get_product_id())
        db.session.add_all([u1, u2, p, c])
        db.session.commit()

        # wrong user --> 403
        token = u2.get_api_token()
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='DELETE',
                data=json.dumps({'token': token}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 403)

        token = u1.get_api_token()
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='DELETE',
                data=json.dumps({'token': token}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 200)
            c = Comment.query.get(c.id)
            self.assertIsNone(c)
예제 #3
0
def storageWorkingDSM(is_opertaion):
    pp = Product.query.filter_by(name='WORKING_DSM_V1.0.0').first()
    if pp == None:
        pp = Product()
        pp.id = '3'
        pp.name = 'WORKING_DSM_V1.0.0'
    pp.is_operation = is_opertaion
    pp.updateTime = datetime.now()
    db.session.add(pp)
    db.session.commit()
예제 #4
0
def storageKnowledge(is_opertaion):
    pp = Product.query.filter_by(name='KNOWLEDGE_V1.1.0').first()
    if pp == None:
        pp = Product()
        pp.id = '4'
        pp.name = 'KNOWLEDGE_V1.1.0'
    pp.is_operation = is_opertaion
    pp.updateTime = datetime.now()
    db.session.add(pp)
    db.session.commit()
예제 #5
0
 def test_moderation(self):
     db.create_all()
     u1 = User(login='******', password='******')
     u2 = User(login='******', password='******', is_admin=True)
     p = Product(type=1234567890, serial=123456, week=45, year=15)
     c1 = Comment(body='comment body 1', author_id=u1.id, product_id=p.get_product_id())
     c2 = Comment(body='comment body 2', author_id=u2.id, product_id=p.get_product_id())
     db.session.add_all([u1, u2, p, c1, c2])
     db.session.commit()
     """
예제 #6
0
def add():
    form = AddForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            product = Product()
            product.createdate = datetime.datetime.now()
            form.populate_obj(product)
            db.session.add(product)
            db.session.commit()
            return redirect(url_for('product.index'))
    return render_template('product/add.html', form=form)
예제 #7
0
 def test_approved(self):
     db.create_all()
     u = User(login='******', password='******')
     p = Product(type=1234567890, serial=123456, week=45, year=15)
     c1 = Comment(body='comment body 1', author_id=u.id, product_id=p.get_product_id())
     c2 = Comment(body='comment body 2', author_id=u.id, product_id=p.get_product_id())
     db.session.add_all([u, p, c1, c2])
     db.session.commit()
     comments = p.comments.all()
     self.assertTrue(len(comments) == 2)
     self.assertTrue(comments[0] == c1)
    def _populate_db(self):
        BASE_IMAGE_URL = "http://azurefresh.blob.core.windows.net/image-store/"

        import os

        with open(os.path.join("app", "management", "commands", "grocery.csv"), "r") as csvfile:
            reader = csv.reader(csvfile)
            for row in reader:
                p = Product(name=row[0], price=row[1], image_link=BASE_IMAGE_URL + row[2], description=row[3])
                p.save()

        print("Added Grocery Items to the Database")
예제 #9
0
def product_get(id):
	if id:
		product = Product.query.filter_by(site_id=g.sid, branch_id=g.bid, is_active='Y', id=id).first()
	else:
		no = db.session.query(db.func.max(Product.no)).filter_by(site_id=g.sid, branch_id=g.bid).scalar() or 0
		no = no + 1
		product = Product(site_id=g.sid, branch_id=g.bid)
		product.no = no
		product.code = 'P' + str(no).zfill(4)
	schema = ProductSchema()
	return jsonify({
		'product': schema.dump(product).data
	})
예제 #10
0
 def test_notification_list(self):
     db.create_all()
     u1 = User(login='******', password='******')
     u2 = User(login='******', password='******')
     p = Product(type=1234567890, serial=123456, week=45, year=15)
     c1 = Comment(body='comment body 1', author_id=u1.id, product_id=p.get_product_id())
     c2 = Comment(body='comment body 2', author_id=u1.id, product_id=p.get_product_id())
     c3 = Comment(body='comment body 3', author_id=u1.id, product_id=p.get_product_id())
     c4 = Comment(body='comment body 4', author_id=u1.id, product_id=p.get_product_id())
     c5 = Comment(body='comment body 5', author_id=u1.id, product_id=p.get_product_id())
     c6 = Comment(body='comment body 6', author_id=u1.id, product_id=p.get_product_id())
     
     db.session.add_all([u1, u2, p, c1, c2, c3, c4, c5])
     db.session.commit()
     """
예제 #11
0
def add_product(request, fridge_id):
    """
    Ajoute un produit à un frigo
    :param request:
    :param fridge_id: l'identifiant du frigo voulu
    :return: detail.html
    :raise Http404: si le frigo n'a été trouvé
    """
    # Vérification de l'existence du frigo
    fridge = get_object_or_404(Fridge, pk=fridge_id)

    if request.method == 'POST':
        # Récupération des informations du formulaire
        form = AddProductForm(request.POST)
        if form.is_valid():
            try:
                # Récupération des données envoyées en POST
                product_name = request.POST['name']
                product_exp_date = request.POST['expdate']
                product_quantity = request.POST['quantity']
                product_unit = request.POST['unit']
            except KeyError:
                # Si un index n'a pas été trouvé : renvoi l'utilisateur vers detail.html
                return render(request, 'app/detail.html', {
                    'fridge': Fridge.objects.with_products(fridge_id),
                    'form': form
                })

            else:
                # Création du nouveau produit avec les informations reçues
                new_product = Product(name=product_name,
                                      exp_date=datetime.datetime.strptime(product_exp_date, "%d/%m/%Y"))
                new_product.save()
                # Création de la ligne de liaison avec le produit, le frigo et les informaitons reçues
                new_productfridge = ProductFridge(fridge=fridge, product=new_product,
                                                  quantity=product_quantity, unit=product_unit)
                new_productfridge.save()
                # Redirect vers la même page : detail.html
                return HttpResponseRedirect(reverse('app:detail', args=(fridge_id,)))
        else:
            # En cas de non validation du formulaire : renvoi vers detail.html
            return render(request, 'app/detail.html', {
                'fridge': Fridge.objects.with_products(fridge_id),
                'form': form
            })
예제 #12
0
    def test_token_errors(self):
        u1 = User(login='******', password='******')
        u2 = User(login='******', password='******')
        p = Product(type=1234567890, serial=123456, week=45, year=15)
        c = Comment(body='comment body', author_id=u1.id, product_id=p.get_product_id())
        db.session.add_all([u1, u2, p, c])
        db.session.commit()

        # missing JSON --> 400
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='PUT'):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 400)

        # missing token --> 401
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='PUT',
                data=json.dumps({'bad': 123}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 401)

        # bad token --> 401
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='PUT',
                data=json.dumps({'token': 'a bad token'}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 401)

        # malformed token --> 401
        u3 = User(login='******', password='******')
        with self.app.test_request_context(
                '/webapi/1.0/comments/' + str(c.id),
                method='PUT',
                data=json.dumps({'token': u3.get_api_token()}),
                headers={'Content-Type': 'application/json'}):
            res = self.app.full_dispatch_request()
            self.assertTrue(res.status_code == 401)
예제 #13
0
 def test_news_json(self):
     brand = Brand(name='fake-name',
                   slug='fake-slug',
                   tagline='fake-tagline',
                   text='fake-text',)
     brand.save()
     response = self.client.get('/ajax/brands/')
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, 'fake-name')
     self.assertContains(response, 'fake-slug')
     self.assertContains(response, 'fake-tagline')
     self.assertContains(response, 'fake-text')
     product = Product(name='fake-product-name',
                       slug='fake-product-slug',
                       text='fake-product-text',)
     product.save()
     brand.products.add(product)
     brand.save()
     response = self.client.get('/ajax/brands/')
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, 'fake-product-name')
예제 #14
0
	def get(self):
		self.response.headers['Content-Type'] = 'application/json'
		
		filtered_products = [extend_dict(product_data, {'id': product_id}) 
								for product_id, product_data in Product.cache().items()]
		
		store = self.request.get('store', '').lower().strip()
		if store:
			filtered_products = [product for product in filtered_products
									if store in product['sale']['stores']]
		
		size = self.request.get('size', '').strip()
		if size:
			filtered_products = [product for product in filtered_products if size in product['sizes']]

		brand_id = int(self.request.get('brand_id', 0))
		if brand_id:
			filtered_products = [product for product in filtered_products
									if product['brand']['id'] == brand_id]
									
		max_price = int(self.request.get('max_price', 0))
		if max_price > 0:
			filtered_products = [product for product in filtered_products
									if len(product['prices']) and
										(max(product['prices']) <= max_price)]				

		min_price = int(self.request.get('min_price', 0))
		if min_price > 0:
			filtered_products = [product for product in filtered_products
									if len(product['prices']) and
										(min(product['prices']) >= min_price)]
										
		origin = self.request.get('origin')
		if origin:
			filtered_products = [product for product in filtered_products
									if product['origin'] == origin]
		
		status = self.request.get('status')
		if status:
			filtered_products = [product for product in filtered_products
									if product['status'] == status]
							
		available = self.request.get('available')
		if available:
			filtered_products = [product for product in filtered_products
									if product['status'] == (bool(available) and 'F' or 'X')]
			
		limit = int(self.request.get('limit', 0))
		if limit:
			filtered_products = filtered_products[:limit]
		
		self.response.out.write(json.dumps({'products': filtered_products}))
예제 #15
0
 def create_new(self):
     r1 = self.name.validate(self)
     r2 = self.memo.validate(self)
     r3 = self.img.validate(self)
     r4 = self.price.validate(self)
     if r1 and r2 and r3 and r4:
         category = Category.query.get(self.category.data)
         if category is None:
             self.category.errors.append(_(u'Category not found'))
             return False
         if not check_img(self.img.data):
             self.img.errors.append(_(u'Image not found'))
             return False
         product = Product()
         product.init(self.name.data, self.memo.data, self.img.data, self.price.data)
         product.category = category
         i = Upload.query.filter_by(url=self.img.data).first()
         db.session.delete(i)
         db.session.add(product)
         db.session.commit()
         self.product = product
         return True
     return False
예제 #16
0
def addProduct(request):
    args = {}
    args = getBasicInfo(args, "Productos")
    args['providers'] = Provider.objects.all()

    if request.POST:
        provider = Provider.objects.get(name=request.POST['provider'])
        name = request.POST['name']
        short_description = request.POST['short-description']
        large_description = request.POST['large-description']
        image = request.FILES['image']
        product = Product()
        product.provider = provider
        product.name = name
        product.short_description = short_description
        product.large_description = large_description
        if image:
            product.image = image
        product.save()
        args['msg'] = "Producto agregado correctamente"
        return render_to_response('aeadmin/products/add_product.html', args, context_instance=RequestContext(request))
    return render_to_response('aeadmin/products/add_product.html', args, context_instance=RequestContext(request))
예제 #17
0
def product(product_id):
    product = Product(product_id)
    product.import_from_json()
    return render_template("product.html.jinja", product=str(product))
예제 #18
0
 def copy(self, request, queryset):
     l = queryset.count()
     if l == 0:
         self.message_user(request, "Debe seleccionar al menos un producto.", level=messages.ERROR)
     else:
         for q in queryset:
             n = Product()
             n.name = 'Copia de '+ q.name
             p = Product.objects.filter(name = n.name).first()
             if p:
                 n.name = n.name + ' ' + datetime.now().__str__()
             n.slug = 'copia-' + q.slug
             n.shortdescription = q.shortdescription
             n.longdescription = q.longdescription
             n.keywords = q.keywords
             n.price = q.price
             n.discount_price = q.discount_price
             n.stock = q.stock
             n.active = False
             n.show_in_home = False
             n.order = self.get_max_order() + 1
             n.save()
             category = q.category
             for c in category.all():
                 c.product_set.add(n)
         self.message_user(request, "Los productos se han copiado.")
예제 #19
0
 def test_need_to_eat_with_expired_date(self):
     """
     need_to_eat() doit retourner True pour les produits dont la date_exp est < maintenant
     """
     exp_date_product = Product(exp_date=timezone.now() - datetime.timedelta(days=5))
     self.assertEqual(exp_date_product.need_to_eat(), True)
예제 #20
0
    db.create_all()
except Exception as e:
    print(e)
    
cust = Customer(username = "******",
                    email = "*****@*****.**",
                    first_name = "first_test",
                    last_name = "last_test",
                    middle_name = "middle_test",
                    phone_number = "123456789",
                    gender = "M",
                    marital_status = "Married")
cust.set_password('test_pass')

prod1 = Product(
                    name = "test_window_wide",
                    type = "window"
                )
prod2 = Product(
                    name = "test_window_square",
                    type = "window"
                )
prod3 = Product(
                    name = "test_window_tall",
                    type = "window"
                )

wind1 = Window(
                    window_type = "singlehung",
                    width = 25,
                    height = 10,
                    color = "white",
예제 #21
0
 def test_in_stock_false(self):
     for product in [
         Product(quantity=0),
     ]:
         self.assertFalse(product.in_stock)
예제 #22
0
 def test_need_to_eat_with_long_date(self):
     """
     need_to_eat() doit retourner False pour les produits dont la date est > à aujourd'hui + 3 jours
     """
     long_date_product = Product(exp_date=timezone.now() + datetime.timedelta(days=30))
     self.assertEqual(long_date_product.need_to_eat(), False)
예제 #23
0
파일: routes.py 프로젝트: sbaker9/icSavings
def reset_db():
    flash(
        "Resetting database: deleting old data and repopulating with dummy data"
    )
    # clear all data from all tables
    meta = db.metadata
    for table in reversed(meta.sorted_tables):
        print('Clear table {}'.format(table))
        db.session.execute(table.delete())
    db.session.commit()

    # adding dummy data--

    c1 = Category(name="Toys")
    c2 = Category(name="Electronics")

    db.session.add(c1)
    db.session.add(c2)
    db.session.commit()

    a1 = Product(
        name="Nintendo Switch with Neon Blue and Neon Red Joy‑Con",
        description=
        "Play your way with the Nintendo Switch gaming system. Whether you’re at home or on the "
        "go, solo or with friends, the Nintendo Switch system is designed to fit your life. Dock "
        "your Nintendo Switch to enjoy HD gaming on your TV. Heading out? Just undock your console and "
        "keep playing in handheld mode.",
        url=
        "https://www.amazon.com/dp/B07VGRJDFY/ref=cm_gf_atz_iaaa_d_p0_c0_qd0coEtwouCW5V9Zr4M2HQ8",
        favorite=False,
        category=c1,
        image=
        "https://images-na.ssl-images-amazon.com/images/I/71Qk2M1CIgL._AC_SL1500_.jpg"
    )
    a2 = Product(
        name="Echo Dot Kids Edition",
        description=
        "Designed with kids in mind - They can ask Alexa to play music, hear stories, call "
        "approved friends and family, and explore a world of kid-friendly skills.",
        url=
        "https://www.amazon.com/dp/B07Q2MXPH6/ref=cm_gf_atz_iaaa_d_p0_c0_qd0O2FWT6ajLcfkyxyUA27t",
        favorite=True,
        category=c2,
        image=
        "https://images-na.ssl-images-amazon.com/images/I/619hTFl4%2BIL._AC_SL1000_.jpg"
    )
    a3 = Product(
        name="Really RAD Robots - Turbo Bot",
        description=
        "Turbo Bot is built for speed! With a full function remote control including a turbo "
        "Boost switch!",
        url=
        "https://www.amazon.com/dp/B07NSTW6FT/ref=cm_gf_atz_iaaa_d_p0_c0_qd01g4cV1qjOSc2nnti4MzZ",
        favorite=False,
        category=c1,
        image=
        "https://images-na.ssl-images-amazon.com/images/I/61QEo-fe1JL._AC_SL1418_.jpg"
    )
    a4 = Product(
        name="Hot Wheels Toy Story 4 Bundle Vehicles, 6 Pack",
        description=
        "The beloved cast becomes a 5-pack of unique and highly coveted Character Cars.",
        url=
        "https://www.amazon.com/gp/product/B07L8YMFH8/ref=cg_htl-lcat_3a2_w?pf_rd_m=ATVPDKIKX0DER&pf_rd_"
        "s=desktop-top-slot-6&pf_rd_r=YDW1WMNXF1Y3FFJY0KH5&pf_rd_t=0&pf_rd_p=b4c22792-984a-4880-8b60-"
        "44dfcac63ee9&pf_rd_i=gf-events--holiday-toy-list",
        favorite=True,
        category=c1,
        image=
        "https://images-na.ssl-images-amazon.com/images/I/81ytG6lfGTL._AC_SL1500_.jpg"
    )
    a5 = Product(
        name="Beats Solo3 Wireless On-Ear Headphones - Matte Black",
        description=
        "With up to 40 hours of battery life, Beats Solo3 wireless is your perfect everyday "
        "headphone.",
        url=
        "https://www.amazon.com/dp/B01LWWY3E2/ref=cm_gf_aaam_iaaa_d_p0_c0_qd0PoZ3uEKKhZA1d0qZjrgk",
        favorite=False,
        category=c2,
        image=
        "https://images-na.ssl-images-amazon.com/images/I/71sBjbHYbKL._AC_SL1500_.jpg"
    )

    db.session.add(a1)
    db.session.add(a2)
    db.session.add(a3)
    db.session.add(a4)
    db.session.add(a5)

    v1 = Price(price=299.00, datetime=datetime(2019, 10, 14), productID=1)
    v2 = Price(price=289.00, datetime=datetime(2019, 10, 16), productID=1)
    v3 = Price(price=249.00, datetime=datetime(2019, 10, 18), productID=1)
    v4 = Price(price=299.00, datetime=datetime(2019, 10, 20), productID=1)
    v5 = Price(price=309.00, datetime=datetime(2019, 10, 22), productID=1)
    v6 = Price(price=34.99, datetime=datetime(2019, 10, 14), productID=2)
    v7 = Price(price=39.99, datetime=datetime(2019, 10, 16), productID=2)
    v8 = Price(price=44.99, datetime=datetime(2019, 10, 18), productID=2)
    v9 = Price(price=34.99, datetime=datetime(2019, 10, 20), productID=2)
    v10 = Price(price=39.99, datetime=datetime(2019, 10, 22), productID=2)
    v11 = Price(price=39.99, datetime=datetime(2019, 10, 14), productID=3)
    v12 = Price(price=37.99, datetime=datetime(2019, 10, 16), productID=3)
    v13 = Price(price=41.99, datetime=datetime(2019, 10, 18), productID=3)
    v14 = Price(price=38.99, datetime=datetime(2019, 10, 20), productID=3)
    v15 = Price(price=43.99, datetime=datetime(2019, 10, 22), productID=3)
    v16 = Price(price=24.99, datetime=datetime(2019, 10, 14), productID=4)
    v17 = Price(price=26.99, datetime=datetime(2019, 10, 16), productID=4)
    v18 = Price(price=28.99, datetime=datetime(2019, 10, 18), productID=4)
    v19 = Price(price=23.99, datetime=datetime(2019, 10, 20), productID=4)
    v20 = Price(price=24.99, datetime=datetime(2019, 10, 22), productID=4)
    v21 = Price(price=249.00, datetime=datetime(2019, 10, 14), productID=5)
    v22 = Price(price=199.00, datetime=datetime(2019, 10, 16), productID=5)
    v23 = Price(price=179.00, datetime=datetime(2019, 10, 18), productID=5)
    v24 = Price(price=239.00, datetime=datetime(2019, 10, 20), productID=5)
    v25 = Price(price=219.00, datetime=datetime(2019, 10, 22), productID=5)

    db.session.add(v1)
    db.session.add(v2)
    db.session.add(v3)
    db.session.add(v4)
    db.session.add(v5)
    db.session.add(v6)
    db.session.add(v7)
    db.session.add(v8)
    db.session.add(v9)
    db.session.add(v10)
    db.session.add(v11)
    db.session.add(v12)
    db.session.add(v13)
    db.session.add(v14)
    db.session.add(v15)
    db.session.add(v16)
    db.session.add(v17)
    db.session.add(v18)
    db.session.add(v19)
    db.session.add(v20)
    db.session.add(v21)
    db.session.add(v22)
    db.session.add(v23)
    db.session.add(v24)
    db.session.add(v25)

    pu1 = ProductToUser(userID=1, productID=1)
    pu2 = ProductToUser(userID=1, productID=2)
    pu3 = ProductToUser(userID=1, productID=4)
    pu4 = ProductToUser(userID=2, productID=1)
    pu5 = ProductToUser(userID=2, productID=3)
    pu6 = ProductToUser(userID=2, productID=4)
    pu7 = ProductToUser(userID=2, productID=5)

    db.session.add(pu1)
    db.session.add(pu2)
    db.session.add(pu3)
    db.session.add(pu4)
    db.session.add(pu5)
    db.session.add(pu6)
    db.session.add(pu7)

    u1 = User(username="******", email="*****@*****.**")
    u2 = User(username="******", email="*****@*****.**")

    db.session.add(u1)
    db.session.add(u2)

    db.session.commit()

    u1.set_password("firewater")
    u2.set_password("earthair")

    db.session.commit()

    return redirect(url_for('index'))
예제 #24
0
def delete(request, pk):
    if pk is None:
        raise BadRequest("Product id is required")
    product = Product.delete().where(Product.id == pk).execute()

    return 200, json.dumps({"Product Deleted": True})
예제 #25
0
from app import db
from app.models import Product, Category, Customer, Order, OrderItem

category1 = Category('Cleaning')
category2 = Category('Chemicals')
category3 = Category('Household Supplies')

product0 = Product('Bleach')
product1 = Product('toilet paper')
product2 = Product('mop')
product3 = Product('small bucket')
product5 = Product('hand soap')
product0.categories.extend([category1, category2])
product1.categories.extend([category2, category3])
product2.categories.append(category3)
product3.categories.append(category3)
product5.categories.append(category1)

order0 = Order(1, 'Waiting')
order1 = Order(1, 'Waiting')
order2 = Order(2, 'In Transit')
order3 = Order(3, 'Delivered')

customer1 = Customer('James T. Kirk')
customer2 = Customer('Jean Luc Picard')
customer3 = Customer('Jonathan Archer')

db.session.add_all([
    order0, order1, order2, order3, customer1, customer2, customer3, product0,
    product1, product2, product3, product5, category1, category2, category3
])
예제 #26
0
def test_name_validation(client, init_database):
    with pytest.raises(ValueError):
        Product(name=" ", description="invalid book")
예제 #27
0
from app import db
from datetime import datetime
from app.models import Product, Product_Release, Client

#this file cretes the database schema and pre populates the table
db.create_all()
product = Product(product_name="UNKNOWN")
client = Client(client_name="UNKNOWN")
product_release = Product_Release(product_id=1, release_number="UNKNOWN",inserted_at=datetime.utcnow())
db.session.add(product)
db.session.add(client)
db.session.add(product_release)
db.session.commit()
print("DB Created")
예제 #28
0
def seed_products():
    """SWORDS"""
    short_sword = Product(
        title="Short Sword",
        image=
        "https://1.bp.blogspot.com/-iV-ILYgMtsg/WqgeQbw-efI/AAAAAAAADOI/eXxSIeSTWgwibevUdl1OtgapAZ5w3thogCLcBGAs/s1600/Polished%2BAncient%2BSteel%2BSword.png",
        price=200,
        description="A sword for only \
                               the very bravest of heros. It is for the Hero \
                               who is not afraid to get up close and personal \
                               with the maw of the beast. Light versital and \
                               ready for any close combat you can throw at it",
        lore="It was written by a master swordsman once that\
                               a warriors true mettle could only be found when\
                               wielding a short sword.",
        quantity=2000,
        category_id=1)
    long_sword = Product(
        title="Long Sword",
        image=
        "https://3.bp.blogspot.com/-ZnGkRBCP3h0/Ws-EiDXXKxI/AAAAAAAADbY/Ba6RnoNCjMsogGggwL9jp-35xYBo70bsQCLcBGAs/s1600/Balanced%2BGreatsword%2Bof%2BExtermination%2B53%2B%2528of%2Bthe%2BMountains%2B56%2529%2B%2528Dwarf-craft%2BGreat%2BSword%2529.png",
        price=300,
        description="A sword perfect for\
                         your assault class hero. It can stand up to heavy \
                         blows from mid-level weapons and yet still be\
                         versitile enough to leap into the fold. This blade is\
                         deadly in a fight against lightly armoured foes and\
                         multiple enemy engagements.",
        lore="Empires have been won and lost depending on\
                               which end of the long sword you found yourself\
                               on.",
        quantity=1467,
        category_id=1)
    broad_sword = Product(
        title="Broad Sword",
        image=
        "https://4.bp.blogspot.com/-k_jT3_NY9uk/Ws-EnpU4foI/AAAAAAAADcU/jKAJNf2nkngui4AKvzSG23JkP7Y-L7E-QCLcBGAs/s1600/Heavy%2BBright%2BSteel%2BGreat%2BSword%2Bof%2BMight.png",
        price=500,
        description="This weapon is\
                                designed to counter heavily armoured enemies.\
                                It is also helpful in cutting a path through\
                                an enemy hoard. It is slow, heavy and will\
                                decimate anything in its path.",
        lore="It is\
                                said that when the realm of man was told they\
                                would face the armored hoards of Sauron, they \
                                responded with the broad sword.",
        quantity=1298,
        category_id=1)
    dagger = Product(
        title="Dagger",
        image=
        "https://3.bp.blogspot.com/-e_rp2d7fFsg/W0z9LZU0oHI/AAAAAAAADxs/g5FTqR-x98UVVPe6E7YKtUMsAjy88ZMmgCLcBGAs/s1600/Anglas%2B%2528Auger%252C%2BDagger%2Bof%2Bthe%2BNight%2529.png",
        price=150,
        description="If you are looking for\
                     fast look no farther than the dagger. This weapon will\
                     slice dice and cut POTATOES faster than you can say\
                     Bererland.",
        lore="Strike fast and move quickly is the\
                     code of the dagger.",
        quantity=5000,
        category_id=1)
    elven_dagger = Product(
        title="Elven Dagger",
        image=
        "https://2.bp.blogspot.com/-gkan2PNlDI8/W00fVWx565I/AAAAAAAAD08/1-vsfzw4y48U3Oo8zFJ__vwRaYFGMCxcACLcBGAs/s1600/Dagger%2Bof%2Bthe%2BFirst%2BAge%2B59%2B%2528Reshaped%2BFA%2B65%2529.png",
        price=150,
        description="The back up\
                           weapon of the elvish Army. Used Broadly as a\
                           secondary to their bows. More nimble than the\
                           traditional dagger but only has one edge.",
        lore="The elvish dagger is considered a short\
                           weapon. Not because of its size but because its\
                           target only sees it for a short time before they\
                           expire.",
        quantity=419,
        category_id=1)
    hook_sword = Product(
        title="Hook Sword",
        image=
        "https://2.bp.blogspot.com/-cJ9EySvp5hs/WqgeVEwtaGI/AAAAAAAADOg/DQO6ST0y73Q9EWKXgt0uoViAX1A_WuRvACLcBGAs/s1600/Scimitar.png",
        price=325,
        description="A sword with\
                         surprising multiplicity. It is between the long sword\
                         and short sword in length. It has a sharpened point\
                         on the end of the backside of the blade that is used\
                         to puncture hard targets and pull them.",
        lore="Its\
                         not much to look at but you can use it anywhere.",
        quantity=10000,
        category_id=1)
    falchion = Product(
        title="Falchion",
        image=
        "https://4.bp.blogspot.com/-ImRhXaEjZkI/WqgeXKSiEnI/AAAAAAAADOs/yRzYvSGOW48t-Dyp7eudtr2WOPj2T6UNQCLcBGAs/s1600/Sword%2Bof%2BKnowledge%2B%2528LM%2Bexclusive%2529.png",
        price=500,
        description="Similar to the broad\
                       sword in speed but heavier and more special",
        lore="",
        quantity=1298,
        category_id=1)
    """AXES"""
    dull_axe = Product(
        title="Dull Axe",
        image=
        "https://2.bp.blogspot.com/-yJ-qHbtkjPQ/WtOlh3AV9RI/AAAAAAAADi4/46Xf9q7l6eUyGXmTEuvjxUtYoH5VgZ9QwCLcBGAs/s1600/Iron%2BAxe%2B%2528Galadhrim%2BAxe%2Bof%2BCombat%2Band%2BTactics%2529.png",
        price=50,
        description="I wouldn't say it will split skulls,\
                        but it might cut a melon",
        lore="This axe, at one time, was sharp.",
        quantity=1,
        category_id=1)
    huntsmans_axe = Product(
        title="Huntsman's Axe",
        image=
        "https://1.bp.blogspot.com/-tPH6WeUgW3M/WtO52z4JaYI/AAAAAAAADls/w3OSTE2WOqsAw_F6ZTyXjpdC724CINRHgCLcBGAs/s1600/Potent%2BAxe%2Bof%2Bthe%2BDeep%2B%2528Polished%2BFangorn%2BAxe%2Bof%2BStrength%2529.png",
        price=100,
        description="This axe is great for a man hunting.\
                            Need to feed your family? Look no further. We've\
                            got what you're looking for! The Huntsman's Axe!",
        lore="",
        quantity=500,
        category_id=1)
    obsidian_axe = Product(
        title="Obsidian Axe",
        image=
        "https://2.bp.blogspot.com/-W3i-bZwWeHg/WtOsikhznaI/AAAAAAAADko/oe0molH3mmQTgtbLQ975EI2ocS1NKkJfwCLcBGAs/s1600/Champion%2527s%2BAxe%2Bof%2Bthe%2BThird%2BAge%2B75.png",
        price=150,
        description="This axe cuts through like a cold,\
                           dark night. Silent and terrifying.",
        lore="",
        quantity=600,
        category_id=1)
    dwarven_axe = Product(
        title="Dwarven Axe",
        image=
        "https://1.bp.blogspot.com/-0ffwfYTYoyg/WtS4CzyM1VI/AAAAAAAADok/4DPKzb85Ql88773dUcrj76V9I_ychTONwCLcBGAs/s1600/Champion%2527s%2BGreat%2BAxe%2Bof%2Bthe%2BFIrst%2BAge%2B59.png",
        price=600,
        description="Forged within the depths of Moria.\
                          Smelted through ages of experience, sweat, blood,\
                          and dragon tears.",
        lore="",
        quantity=100,
        category_id=1)
    """BOWS"""
    long_bow = Product(
        title="Longbow",
        image=
        "https://wow.zamimg.com/uploads/screenshots/normal/211381-farstriders-longbow.jpg",
        price=75,
        description="Great\
                       for launching a volley or defending from a siege. A\
                       longbow is classic and dependable. Made from a single\
                       piece of wood.",
        lore="",
        quantity=5000,
        category_id=1)
    short_bow = Product(
        title="Shortbow",
        image=
        "https://wow.zamimg.com/uploads/screenshots/normal/1013267-composite-bow.jpg",
        price=50,
        description="\
                        Great for firing from horseback. The shortbow\
                        considered to be the cavalry's first resort.",
        lore="A\
                        favorite of the men of Rohan",
        quantity=3000,
        category_id=1)
    elven_bow = Product(
        title="Elven Bow",
        image=
        "https://wow.zamimg.com/uploads/screenshots/normal/433155-thoridal-the-stars-fury.jpg",
        price=400,
        description="\
                        Features delicate carvings painted gold. Known for\
                        accuracy from great distances. Elegant and effective.",
        lore="Hewn from the trees of Lothlorien",
        quantity=100,
        category_id=1)
    """MACES"""
    wooden_club = Product(
        title="Wooden Club",
        image=
        "https://3.bp.blogspot.com/-fJRu2TjIgZU/W1JWsyZRRCI/AAAAAAAAEF0/hHlvtvAnwGghukg0ESi_H253WT68VBVQgCLcBGAs/s1600/Ash%2BClub%2B%2528Heavy%2BAsh%2BClub%2Bof%2BVitality%2529.png",
        price=15,
        description="Nine out of ten cavemen agree: this\
                          wooden club will at least get you home from work.",
        lore="Definitely didn't find it on the side of the\
                          road.",
        quantity=1,
        category_id=1)
    flanged_mace = Product(
        title="Flanged Mace",
        image=
        "https://1.bp.blogspot.com/-JIqZCZEwLBU/W06Kz5EFyvI/AAAAAAAAD6s/zk11VBxgn4IWyAzmhvgaqflr1G15eroGACLcBGAs/s1600/Forged%2BElven-steel%2BMace%2Bof%2BCombat.png",
        price=600,
        description="A highly-specialized mace designed for\
                           punching through armor. Heavy and indestructable.",
        lore="Has ruined more than one game of whack-a-mole\
                           ",
        quantity=1900,
        category_id=1)
    stone_club = Product(
        title="Stone Club",
        image=
        "https://3.bp.blogspot.com/-Wf7AIzgCaNQ/W1JYhGeZKqI/AAAAAAAAEHQ/KsUtA6DCNz8hJtZcVFDhjV6gQvvTKuyaQCLcBGAs/s1600/Old%2BReliable.png",
        price=20,
        description="Avid stone club users know how hard it\
                         is to find the perfect stone for a club. This, my\
                         friends, is it.",
        lore="Definitely also not found on\
                         the side of the road.",
        quantity=2,
        category_id=1)
    night_club = Product(
        title="Night Club",
        image=
        "https://1.bp.blogspot.com/-x1aMsB7F06U/W1j677uh6-I/AAAAAAAAENc/8SRg83q0K88cSwMAVV1lOCoF3DPRZW_8QCLcBGAs/s1600/Polished%2BScout%2527s%2BGreat%2BClub.png",
        price=500,
        description="A good time, until it's not.",
        lore="",
        quantity=7,
        category_id=1)
    """SHIELDS"""
    wooden_shield = Product(
        title="Wooden Shield",
        image=
        "https://1.bp.blogspot.com/-FQLI0UrZjDc/XWgIjamlnrI/AAAAAAAAFIc/96ny6TkIoac6Yp8IEQ84RYs0onYt0uutQCLcBGAs/s1600/Crafted%2BBuckler.png",
        price=50,
        description="Effective against weak enemies and\
                            dull weapons. If you want to live go for the\
                            upgrade.",
        lore="Also definitely not found on the\
                            side of the road.",
        quantity=2800,
        category_id=2)
    aspi = Product(
        title="Aspi",
        image=
        "https://1.bp.blogspot.com/-R8vQKwyX9d8/XWf0nlUQ8JI/AAAAAAAAFFg/JB6BrLkArTMslNNyvm0Kosew-JQgZ6ABwCLcBGAs/s1600/Shield%2Bof%2BAnfalas.png",
        price=600,
        description="Heavy-duty,\
                   metal-studded, but unfortunately not waterproof. Please\
                   stop asking.",
        lore="Used by a civilization where the\
                   warrior was held to the highest esteem. Truly unmatched for\
                   its potential, especially in group combat.",
        quantity=300,
        category_id=2)
    gondorian_shield = Product(
        title="Gondorian Shield",
        image=
        "https://1.bp.blogspot.com/-2t4JSZ5UtGE/XWf0nfhQCiI/AAAAAAAAFFc/6ex4hO02laIyDGvh4u9QSmc1zIJxGuyOgCLcBGAs/s1600/Pack%2Bof%2Bthe%2BAnorien%2BAutumn.png",
        price=1000,
        description="This defensive weapon is more of a\
                               structure than a piece of equipment. Built to\
                               carry its user all the way across No Man's Land\
                               Intimidating and beautiful.",
        lore="Engraved with the Tree of Gondor.",
        quantity=10,
        category_id=2)
    """ARMOR"""
    leather_armor = Product(
        title="Leather Armor",
        image=
        "http://4.bp.blogspot.com/-BHt4NyluE7g/U_JGVd00e4I/AAAAAAAACVw/zAWll-olyK0/s1600/Aerthain_Swan.png",
        price=150,
        description="Light,\
                            durable, and slightly\
                            flame-retardant.",
        lore="Made from cow.\
                            Depending on the company you keep, can be \
                                multifunctional.",
        quantity=829,
        category_id=3)
    orc_armor = Product(
        title="Orc Armor",
        image=
        "https://wow.zamimg.com/uploads/screenshots/normal/761325-savage-warrior.jpg",
        price=200,
        description="A\
                        patchwork of trophies woven into something somewhat \
                        like armor.",
        lore="Don't look too close.",
        quantity=317,
        category_id=3)
    full_plate_armor = Product(
        title="Full Plate Armor",
        image=
        "https://1.bp.blogspot.com/-ZLAkWVbFLo8/XneqlU_E98I/AAAAAAAAFlg/ZNiD7740PVQJY_gN-JmmRS6SRyyCAl7JQCLcBGAsYHQ/s1600/Nathrien_Anniversary%2528s%2529.png",
        price=2000,
        description="You won't go anywhere\
                               fast in this, and you won't sneak up on anyone.\
                               Also, takes a while to get off but it'll keep\
                               your head on.",
        lore="Imbued with mithril\
                               filigree.",
        quantity=10,
        category_id=3)
    """FOOD AND DRINK"""
    lembas_bread = Product(
        title="Lembas Bread",
        image=
        "https://cdn.mos.cms.futurecdn.net/rX8mEDef3UR4WNKdg3kTFW-1200-80.jpg",
        price=15,
        description="A bite will satisfy a man a day.",
        lore="",
        quantity=42,
        category_id=4)
    legolas_lager = Product(
        title="Legolas Lager",
        image=
        "https://wow.zamimg.com/uploads/screenshots/normal/58201-brewfest-pony-keg.jpg",
        price=5,
        description="It won't give you the eyes of an elf,\
                            but it'll make you feel like you shoot like one.",
        lore="It's been said Legolas drank a cask and felt\
                            a tingle.",
        quantity=6,
        category_id=4)
    gollum_grog = Product(
        title="Gollum Grog",
        image="https://wow.zamimg.com/uploads/screenshots/small/64740.jpg",
        price=2000,
        description="Everyone looks good after ten, my\
                          precious. A real loincloth-dropper.",
        lore="Strong\
                          enough to bring Deagol back.",
        quantity=10,
        category_id=4)
    potatoes = Product(
        title="Potatoes",
        image=
        "https://images.unsplash.com/photo-1518977676601-b53f82aba655?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1500&q=80",
        price=2000,
        description="Boil 'em, mash 'em, stick 'em in stew.",
        lore="Boil 'em, mash 'em, stick 'em in stew.",
        quantity=100,
        category_id=4)
    apple = Product(
        title="Apples",
        image=
        "https://images.unsplash.com/photo-1611574474484-ced6cb70a2cf?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1500&q=80",
        price=10,
        description="uh apple",
        lore="This apple is menacing",
        quantity=1,
        category_id=4)
    ring = Product(
        title='A gold ring',
        image=
        'https://cdn.pixabay.com/photo/2016/09/15/07/05/ring-1671094_1280.jpg',
        price=1000,
        description=
        'This is a rather ordinary gold ring. Some might call it boring. Every once in awhile some pretty letters appear on it which is cool.',
        lore='Just a regular old ring',
        category_id=5)
    anduril = Product(
        title='Andúril',
        image=
        'https://1.bp.blogspot.com/-iP36mifbTyk/WqgSM9ZMdJI/AAAAAAAADNU/mmbN0K5TxPAmO8SP0K43_I95yAIH3HgRACLcBGAs/s1600/Minstrel%2527s%2BSword%2Bof%2Bthe%2BFirst%2BAge%2B60.png',
        price=10000,
        description=
        'Forged from the shards of Narsil... This blade was wielded by eventual King of Gondor, Aragorn, to purge Middle Earth of the Dark Lord.',
        lore='Also works well to cut potatoes.',
        category_id=5)
    glamdring = Product(
        title='Glamdring',
        image=
        'https://2.bp.blogspot.com/-SDBuOAkJHlo/WqgSJHFifXI/AAAAAAAADM8/VvVEHVtXgZAz91VbqqtH0YfHVgunlJiQACLcBGAs/s1600/Free-cutter.png',
        price=3000,
        description=
        'The sword of the wizard Gandalf. Better known for his fireworks and sweet hat he, apparently, also had a sword.',
        lore=
        'This blade was used to fell a demon of the ancient world in the depths of Moria.',
        category_id=5)
    sting = Product(
        title='Sting',
        image=
        'https://4.bp.blogspot.com/-ozBYwENBlL8/W00qw94JKsI/AAAAAAAAD2c/s7LxdMoqq3gHaZaBsBBnXMCItN5aRfHZACLcBGAs/s1600/Dagger%2Bof%2Bthe%2BThird%2BAge%2B95%2B%2528Relic-master%2529.png',
        price=6969,
        description=
        'This blade was used by Bilbo the Great on his adventures to the Lonely Mountain and later by Frodo the Mighty in his quest to save Middle Earth.',
        lore='Rumor has it that the blade glows when orcs are near...',
        category_id=5)
    mithril_shirt = Product(
        title='Mithril Shirt',
        image=
        'https://images.metmuseum.org/CRDImages/aa/mobile-large/DP147287.jpg',
        price=10000,
        description=
        'Forged in forgotten ways by dwarves of old... Mithril was common then but the dwarves delved deeper into the earth to find even more.  This did not turn out well for the dwarves.',
        lore='This armor protected Frodo.',
        category_id=5)
    palantir = Product(
        title='Palantir',
        image=
        'https://images.unsplash.com/photo-1506808940319-a472563bebee?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1510&q=80',
        price=7000,
        description=
        'Used as an ancient form of communication across vast distances.  The Dark Lord used these to corrupt the weak-minded.',
        lore='A bad time in the wrong hands',
        category_id=5)
    """HORSES"""
    """MAGIC"""
    """UNIQUE ITEMS"""

    db.session.add(short_sword)
    db.session.add(long_sword)
    db.session.add(broad_sword)
    db.session.add(dagger)
    db.session.add(elven_dagger)
    db.session.add(hook_sword)
    db.session.add(falchion)
    db.session.add(dull_axe)
    db.session.add(huntsmans_axe)
    db.session.add(obsidian_axe)
    db.session.add(dwarven_axe)
    db.session.add(long_bow)
    db.session.add(short_bow)
    db.session.add(elven_bow)
    db.session.add(wooden_club)
    db.session.add(flanged_mace)
    db.session.add(stone_club)
    db.session.add(night_club)
    db.session.add(wooden_shield)
    db.session.add(aspi)
    db.session.add(gondorian_shield)
    db.session.add(leather_armor)
    db.session.add(orc_armor)
    db.session.add(full_plate_armor)
    db.session.add(lembas_bread)
    db.session.add(legolas_lager)
    db.session.add(gollum_grog)
    db.session.add(potatoes)
    db.session.add(apple)
    db.session.add(ring)
    db.session.add(anduril)
    db.session.add(glamdring)
    db.session.add(sting)
    db.session.add(mithril_shirt)
    db.session.add(palantir)

    db.session.commit()
예제 #29
0
 def test_in_stock_true(self):
     for product in [
         Product(quantity=1),
         Product(quantity=5),
     ]:
         self.assertTrue(product.in_stock)
예제 #30
0
파일: tasks.py 프로젝트: mshafrir/hautely
	def get(self, sale_id):
		self.response.headers['Content-Type'] = 'text/plain'
		
		sale_id = int(sale_id)
		sale = Sale.lookup(sale_id)
		if not sale:
			self.response.out.write('Sale id %d not found.\n' % (sale_id))
			
		else:
			url = "%s/sale/mobile_sale_listing?sale_id=%d" % (API_SVC, sale_id)
			content = helper.fetch(url)
			products_data = json.loads(content)['data']['products']
			
			if products_data and len(products_data):
				brand_entities = [Brand.get_by_key_name(str(product['brand_id']))
									for product in products_data.values()]
				brands = dict([(int(brand.id), brand) for brand in brand_entities if brand])
							
				for product_id, product_data in products_data.items():
					brand_id = product_data['brand_id']
					brand = Brand.lookup(brand_id)
					
					product_id = int(product_id)
					product_data['name'] = mod_product_string(product_data['name'])
					product_data['description'] = mod_product_string(product_data['description'], '\n')
					product_data['categories'] = list(itertools.chain(*([k.split('_')
															for k in product_data['category_keys']])))
					product = Product.create(product_id, product_data, sale,
											brands.get(brand_id) or Brand.create(brand_id))
				
					if not product:
						self.response.out.write("Did not create product %d - %s.\n" %
							(product_id, product_data['name']))
					else:
						self.response.out.write("Created product %d - %s.\n" %
							(product_id, product_data['name']))
						prices = []
						sizes = []
						looks = product_data['looks']
						if looks:
							for look_data in looks:
								look_id = look_data['look_id']
								look = Look.create(look_id, look_data, product)
							
								if not look:
									self.response.out.write('\tDid not create Look for look id %d.\n' % look_id)
								
								else:
									self.response.out.write('\tCreated look id %d for product %d %s.\n' %
															(look_id, product_id, product.name))
														
									prices.extend([look_data.get(price_key) for price_key in PRICE_KEYS])
	
									skus = look_data.get('skus') or []
									for sku_data in skus:
										size = sku_data.get('size')
										if size:
											if size[0].isdigit():
												sizes.extend(size.split('/'))
											else:
												sizes.append(size)
										sku_id = sku_data['sku_id']
										sku = SKU.create(sku_id, sku_data, look or Look.get_by_key_name("%s" % look_id))
									
										if sku:
											self.response.out.write('\t\t- Created SKU %d.\n' % sku_id)
											prices.extend([sku_data.get(price_key) for price_key in PRICE_KEYS])
										else:
											self.response.out.write('\t\t- Did not create SKU %d.\n' % sku_id)
							
							prices = list(frozenset(filter(lambda price: price and price > 0, prices)))
							if prices:
								product.lowest_price = min(prices)
								product.highest_price = max(prices)
							if sizes:
								product.sizes = list(frozenset(sizes))
							product.put()
							
					self.response.out.write("\n\n")
예제 #31
0
def add_proc():
    # 数据格式
    # dict_items([('name', '神鼎飞丹砂'), ('yuan', 11), ('cent', 11), ('type', '健康食品'), ('category', '五谷杂粮'),
    #             ('specification', [{'value': '胜多负少的', 'canDelete': False}]), ('swiperImages', [
    #         {'order': 1, 'pic_id': '5daec15918e7c1e59a26128c', 'name': 'timg.jpg'},
    #         {'order': 2, 'pic_id': '5daec15918e7c1e59a261288', 'name': 'u=1975038247,3581492848&fm=26&gp=0.jpg'}]), (
    #             'descImages', [{'order': 1, 'pic_id': '5daec15d18e7c1e59a261291',
    #                             'name': 'u=1975038247,3581492848&fm=26&gp=0.jpg'}])])
    json_data = request.get_json()  # 返回的 json_data 是一个 dict
    print(json_data.items())
    print(json_data.keys())
    proc = Product()
    proc.name = json_data["name"]
    proc.description = json_data["description"]
    proc.price = int(json_data["yuan"]) * 100 + int(json_data["cent"])
    proc.type = json_data["type"]
    proc.category = json_data["category"]
    proc.specification = [spec["value"] for spec in json_data["specification"]]
    proc.list_swipers = [
        OnePicture(order=swiper["order"], pic_id=swiper["pic_id"])
        for swiper in json_data["swiperImages"]
    ]
    proc.list_desc = [
        OnePicture(order=desc["order"], pic_id=desc["pic_id"])
        for desc in json_data["descImages"]
    ]
    print(json_data.get("name"))
    print(json_data.get("swiperImages", "haha"))
    print(proc.to_mongo())
    rs = proc.save()
    # proc = Product(name=json_data["name"])
    return jsonify(rs)
예제 #32
0
def create_order(request):
    """
    input
    {
        "order_id": "1",
        "main_phone": "+375445814266",
        "additional_phone": "+375298757099",
        "index": 220096,
        "area": "Минская",
        "city": "Minsk",
        "street_type": "ул",
        "street_name": "Голодеда",
        "house": 2,
        "building": "a",
        "flat": 12,
        "floor": 3,
        "entrance": 5,
        "order_datetime": 1549832400000,
        "delivery_date": 1549832400000,
        "delivery_time": "today, at night",
        "products": [
            {
                "name": "Комплект постельного белья 2,0 бязь",
                "type_id": 1,
                "number": 2,
                "price": 44.5,
                "purchase_price": 20.1,
                "option_ids": [
                    2,6
                ],
                "comment": "супер товар"
            }
        ],
        "comment": "super cool order"
    }

    returns
    {
        "ok":"ok"
    }
    or
    {
        "error": {
            "code": "error id",
            "text": "error string"
        }
    }
    """
    json_input = json.loads(request.body)
    order_datetime_timestamp = json_input['order_datetime']
    delivery_date_timestamp_in_seconds = json_input['delivery_date'] / 1000
    order_datetime = get_datetime_from_timestamp(order_datetime_timestamp)
    delivery_date = date.fromtimestamp(delivery_date_timestamp_in_seconds)
    additional_phone = json_input['additional_phone']
    optional_customer_data = {
        'additional_phone': additional_phone
    }
    customer = Customer.objects.get_or_create(main_phone=json_input['main_phone'],
                                              defaults=optional_customer_data)[0]
    update_if_truthy(customer, optional_customer_data)
    order = Order(pk=json_input['order_id'], comment=json_input['comment'],
                  order_datetime=order_datetime, delivery_date=delivery_date,
                  delivery_time=json_input['delivery_time'],
                  customer=customer)
    order.save()
    for json_product in json_input['products']:
        product = Product(name=json_product['name'],
                          type_id=json_product['type_id'],
                          number=int(json_product['number'] or 1),
                          price=float(json_product['price']),
                          purchase_price=float(json_product['purchase_price']),
                          order=order,
                          comment=json_product['comment'])
        product.save()
        for option_id in json_product['option_ids']:
            product.options.add(Option.objects.get(pk=option_id))
        order.product_set.add(product)
    optional_address_data = {
        'index': int(json_input['index'] or 0),
        'area': json_input['area'],
        'city': json_input['city'],
        'street_type': json_input['street_type'],
        'street_name': json_input['street_name'],
        'house': json_input['house'],
        'building': json_input['building'],
        'flat': int(json_input['flat'] or 0),
        'floor': int(json_input['floor'] or 0),
        'entrance': int(json_input['entrance'] or 0)
    }
    address = Address.objects.get_or_create(customer=customer, defaults=optional_address_data)[0]
    update_if_truthy(address, optional_address_data)
    address.save()
    return russian_json_response({"ok": "ok"})
예제 #33
0
    def process_item(self, item, spider):
        name_and_price = detect_name_and_suggested_price(item['full_name'])
        item['product_name'] = name_and_price['name']
        item['suggested_price'] = name_and_price['suggested_price']
        item['percentage_decrease'] = count_percentage_decrease(
            item['suggested_price'], item['price'])
        item['price_too_low'] = item['price'] < item['suggested_price']

        source = item['source']

        product = Product.query.filter_by(source=source).filter_by(
            dealer_id=item['dealer_id']).filter_by(
                full_name=item['full_name']).first()

        if product is None:
            add_dealer(item['dealer_id'], source)
            product = Product(
                dealer_id=item['dealer_id'],
                source=source,
                full_name=item['full_name'],
                url=item['url'],
                price=item['price'],
                free_shipping=item['free_shipping'],
                product_name=item['product_name'],
                price_too_low=item['price_too_low'],
                percentage_decrease=item['percentage_decrease'],
                suggested_price=item['suggested_price'],
                timestamp_full=datetime.utcnow(),
                timestamp_short=datetime.utcnow().strftime('%Y-%m-%d'),
                archive=False)
            db.session.add(product)
        else:
            product.url = item['url']
            product.price = item['price']
            product.free_shipping = item['free_shipping']
            product.price_too_low = item['price_too_low']
            product.suggested_price = item['suggested_price']
            product.percentage_decrease = item['percentage_decrease']
            product.timestamp_full = datetime.utcnow()
            product.timestamp_short = datetime.utcnow().strftime('%Y-%m-%d')
            product.archive = False
            db.session.add(product)
        db.session.commit()

        return item
예제 #34
0
 def handle(self, *args, **options):
     archivo = args[0]
     f = open(archivo, 'r')
     l = f.readlines()
     count = 0
     for c in l:
         name, longdescription, shortdescription, price, category = c.split('#')
         
         name = name[1:-1]
         name = name.decode('utf-8')
         
         slug = name.replace(' ', '-')
         slug = slug.replace(',', '')
         slug = slug.replace(':', '')
         slug = unicodedata.normalize('NFKD', slug).encode('ASCII', 'ignore') 
         slug = slug.lower()
         
         shortdescription = shortdescription[1:-1]
         shortdescription = shortdescription.decode('utf-8')
         
         longdescription = longdescription[1:-1]
         longdescription = longdescription.decode('utf-8')
         
         keywords = slug.replace('-', ',')
         
         price = price[1:-1]
         price = int(price)
         
         discount_price = 0
         
         stock = 1000
         
         order = 0
         
         active = True
         
         category = category[1:-2]
         category = Category.objects.get(name = category)
         
         show_in_home = False
         
         product = Product()
         product.name = name
         product.slug = slug
         product.shortdescription = shortdescription
         product.longdescription = longdescription
         product.keywords = keywords
         product.price = price
         product.discount_price = discount_price
         product.stock = stock
         product.order = order
         product.active = active
         product.show_in_home = show_in_home
          
         try:
             product.save()
             category.product_set.add(product)
             count += 1
             self.stdout.write('Producto %s almacenado' %  product.name)
         except Exception:
             self.stdout.write('Producto %s NO almacenado' %  product.name)
         
     self.stdout.write('Se almacenaron %d productos' % count)
예제 #35
0
def houqin():
    if current_user.is_authenticated:
        if current_user.section != '后勤部':
            flash('您不属于后勤部')
            return redirect(url_for('main.index'))
        elif current_user.part == '部长':
            u = User.query.filter(User.section == '开发部')
            # 增加新项目
            if request.method == "POST":
                add_b = request.form.get('add')
                add_product = Product(
                    name=add_b,
                    progress='未完成',
                    sections='开发部',
                )
                if Product.query.filter(Product.name == add_b).first():
                    flash('此项目已经存在,请增加新项目')
                    return render_template('bumen/kaifa_b.html')
                db.session.add(add_product)
                db.session.commit()
            p = Product.query.filter(Product.user == None)
            u_pro = []
            for i in u:
                p_b = i.u_project.all()
            return render_template('bumen/kaifa_b.html', u=u, p_b=p_b, p=p)
        u = User.query.filter(User.username == current_user.username).first()
        # pro_u = u.u_project.all()
        p = u.u_project.all()
        print('**************************')
        print(type(u))
        # 获取未完成项目
        pro = Product.query.filter(Product.progress == '未完成')
        pro_unend = []
        for i in pro:
            a = i.user.all()
            b = []
            if a != []:
                for j in a:
                    b.append(j.username)
                    if current_user.username not in b:
                        pro_unend.append(i)
            pro_unend.append(i)
        # 获取个人未完成项目
        pro_end = []
        for i in p:
            if i.progress == '未完成':
                pro_end.append(i)
        # return pro_end
        # 查询个人所有项目

        # 获取数据
        if request.method == 'POST':
            # 增加项目
            add_pro_id = request.form.get('add_pro')
            u = User.query.get(current_user.id)
            add_pro = Product.query.get(int(add_pro_id))
            u.u_project.append(add_pro)
            db.session.add(u)

        return render_template('bumen/houqin.html',
                               p=p,
                               pro_end=pro_end,
                               pro_unend=pro_unend,
                               endpoint='user.updatepros')
    flash('您还没有登陆,请登陆后进入')
    return redirect(url_for('user.login'))
예제 #36
0
def seed_products():
    adelae = Product(name='Drosera adelae',
                     description='hello',
                     quantity=5,
                     price=200.00)
    Briggsiana = Product(name='Nepenthes xBriggsiana',
                         description='hello',
                         quantity=5,
                         price=200.00)
    agnatared = Product(name='Pinguicula agnata red',
                        description='hello',
                        quantity=5,
                        price=200.00)
    alpina = Product(name='Utricularia alpina',
                     description='hello',
                     quantity=5,
                     price=200.00)
    BainesKloof = Product(name='Drosera capensis BainesKloof',
                          description='hello',
                          quantity=5,
                          price=200.00)
    Cephalotus = Product(name='Cephalotus Hummers Giant',
                         description='hello',
                         quantity=5,
                         price=200.00)
    falconeri = Product(name='Drosera falconeri',
                        description='hello',
                        quantity=5,
                        price=200.00)
    fulva = Product(name='Drosera fulva',
                    description='hello',
                    quantity=5,
                    price=200.00)
    gramogolensis = Product(name='Drosera gramogolensis',
                            description='hello',
                            quantity=5,
                            price=200.00)
    hamata = Product(name='Nepenthes hamata',
                     description='hello',
                     quantity=5,
                     price=200.00)
    lanata = Product(name='Drosera lanata',
                     description='hello',
                     quantity=5,
                     price=200.00)
    LotusEater = Product(name='Drosera capensis Lotus Eater',
                         description='hello',
                         quantity=5,
                         price=200.00)
    madagascariensis = Product(name='Drosera madagascariensis',
                               description='hello',
                               quantity=5,
                               price=200.00)
    Microdent = Product(name='Dionaea muscipula Microdent',
                        description='hello',
                        quantity=5,
                        price=200.00)
    paradoxa_TYPE = Product(name='Drosera paradoxa TYPE',
                            description='hello',
                            quantity=5,
                            price=200.00)
    petiolaris = Product(name='Drosera petiolaris',
                         description='hello',
                         quantity=5,
                         price=200.00)
    Porcelain = Product(name='Nepenthes ventricosa Porcelain',
                        description='hello',
                        quantity=5,
                        price=200.00)
    potosiensis = Product(name='Pinguicula potosiensis',
                          description='hello',
                          quantity=5,
                          price=200.00)
    slackii = Product(name='Drosera slackii',
                      description='hello',
                      quantity=5,
                      price=200.00)
    yuccaDo1713 = Product(name='Pinguicula Yucca Do 1713',
                          description='hello',
                          quantity=5,
                          price=200.00)
    nelumbifoliaxreniformis1 = Product(
        name='Utricularia (nelumbifolia x reniformis)',
        description='hello',
        quantity=5,
        price=200.00)

    db.session.add(adelae)
    db.session.add(Briggsiana)
    db.session.add(agnatared)
    db.session.add(alpina)
    db.session.add(BainesKloof)
    db.session.add(Cephalotus)
    db.session.add(falconeri)
    db.session.add(fulva)
    db.session.add(gramogolensis)
    db.session.add(hamata)
    db.session.add(lanata)
    db.session.add(LotusEater)
    db.session.add(madagascariensis)
    db.session.add(Microdent)
    db.session.add(paradoxa_TYPE)
    db.session.add(petiolaris)
    db.session.add(Porcelain)
    db.session.add(potosiensis)
    db.session.add(slackii)
    db.session.add(yuccaDo1713)
    db.session.add(nelumbifoliaxreniformis1)
    db.session.commit()
예제 #37
0
def gen_prop(request):
    # generate prototype
    # print request.body
    # if request.POST:
    result = dict()
    try:
        data = json.loads(request.body)
        pt = Prototype()
        try:
            merchant = MainUser.objects.get(id=data["merchant_id"])
        except:
            return HttpResponse("error", status=500)

        pt.merchant = merchant
        ist = pytz.timezone("Asia/Kolkata")
        pt.key = hashlib.md5(str(datetime.datetime.now(tz=ist)) + "42HACKSTREET").hexdigest()
        pt.save()

        qr_data = dict()
        qr_data["merchant"] = merchant.name
        qr_data["address"] = merchant.address
        qr_data["key"] = pt.key
        qr_data["type"] = 1
        qr_data["products"] = []

        for p in data["products"]:
            name = p["name"]
            sku = p["sku"]
            manufacturer = p["manufacturer"]
            price = p["price"]
            currency = p["currency"]
            desc = p["desc"]
            quantity = p["quantity"]
            pd = Product()
            pd.name = name
            pd.sku = sku
            pd.manufacturer = manufacturer
            pd.price = Decimal(price)
            pd.currency = currency
            pd.desc = desc
            pd.prototype = pt
            pd.quantity = quantity
            pd.save()
            qr_data["products"].append(
                {"name": name, "price": "{0:.2f}".format(pd.price), "quantity": quantity, "currency": currency}
            )
        qr = qrcode.QRCode(version=2, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4)
        qr.add_data(str(json.dumps(qr_data)))
        qr.make(fit=True)
        img = qr.make_image()
        output = StringIO.StringIO()
        img.save(output, "GIF")
        contents = output.getvalue()
        data = base64.b64encode(contents)
        result["status"] = "success"
        result["data"] = data
        return HttpResponse(json.dumps(result))
    except Exception, e:
        print e
예제 #38
0
 def test_need_to_eat_with_short_date(self):
     """
     need_to_eat() doit retourner True pour les produits dont la date est < à aujourd'hui + 3 jours
     """
     short_date_product = Product(exp_date=timezone.now() + datetime.timedelta(days=2))
     self.assertEqual(short_date_product.need_to_eat(), True)
예제 #39
0
def gen_prop(request):
    #generate prototype
    # print request.body
    # if request.POST:
    result = dict()
    try:
        data = json.loads(request.body)
        pt = Prototype()
        try:
            merchant = MainUser.objects.get(id=data['merchant_id'])
        except:
            return HttpResponse("error", status=500)

        pt.merchant = merchant
        ist = pytz.timezone("Asia/Kolkata")
        pt.key = hashlib.md5(
            str(datetime.datetime.now(tz=ist)) + "42HACKSTREET").hexdigest()
        pt.save()

        qr_data = dict()
        qr_data['merchant'] = merchant.name
        qr_data['address'] = merchant.address
        qr_data['key'] = pt.key
        qr_data['type'] = 1
        qr_data['products'] = []

        for p in data['products']:
            name = p['name']
            sku = p['sku']
            manufacturer = p['manufacturer']
            price = p['price']
            currency = p['currency']
            desc = p['desc']
            quantity = p['quantity']
            pd = Product()
            pd.name = name
            pd.sku = sku
            pd.manufacturer = manufacturer
            pd.price = Decimal(price)
            pd.currency = currency
            pd.desc = desc
            pd.prototype = pt
            pd.quantity = quantity
            pd.save()
            qr_data['products'].append({
                'name': name,
                'price': "{0:.2f}".format(pd.price),
                'quantity': quantity,
                'currency': currency
            })
        qr = qrcode.QRCode(
            version=2,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(str(json.dumps(qr_data)))
        qr.make(fit=True)
        img = qr.make_image()
        output = StringIO.StringIO()
        img.save(output, 'GIF')
        contents = output.getvalue()
        data = base64.b64encode(contents)
        result['status'] = 'success'
        result['data'] = data
        return HttpResponse(json.dumps(result))
    except Exception, e:
        print e
예제 #40
0
def add_product(db):
    type1 = ProductType.query.filter_by(id=1).first()
    product1 = Product()
    product1.name = u'鸡肉汉堡'
    product1.description = u'美味的xxx汉堡诱惑你的味蕾'
    product1.type = type1
    product1.price = 20

    product2 = Product()
    product2.name = u'牛肉汉堡'
    product2.description = u'美味的xxx汉堡诱惑你的味蕾'
    product2.type = type1
    product2.price = 25

    product3 = Product()
    product3.name = u'蔬菜汉堡'
    product3.description = u'美味的xxx汉堡诱惑你的味蕾'
    product3.type = type1
    product3.price = 30

    type2 = ProductType.query.filter_by(id=2).first()
    product4 = Product()
    product4.name = u'泰式面条'
    product4.description = u'美味的xxx面条诱惑你的味蕾'
    product4.type = type2
    product4.price = 25

    product5 = Product()
    product5.name = u'川辣面条'
    product5.description = u'美味的xxx面条诱惑你的味蕾'
    product5.type = type2
    product5.price = 30

    product6 = Product()
    product6.name = u'韩式面条'
    product6.description = u'美味的xxx面条诱惑你的味蕾'
    product6.type = type2
    product6.price = 25

    db.session.add(product1)
    db.session.add(product2)
    db.session.add(product3)
    db.session.add(product4)
    db.session.add(product5)
    db.session.add(product6)
    db.session.commit()
예제 #41
0
def import_csv():
    try:
        with open('csv/product_subset_filtered.csv') as f:
            reader = csv.reader(f)
            for count, row in enumerate(reader, start=0):
                if count == 0:
                    print('Skipping headers')
                    continue

                query = Product(id=row[0],
                                title=row[1],
                                description=row[2],
                                tiny_description=row[3],
                                short_description=row[4],
                                medium_description=row[5],
                                long_description=row[6],
                                price=row[7],
                                shelf_time=row[8],
                                campus_id=row[9],
                                last_update=row[10],
                                archived=row[11],
                                taxable=row[12],
                                category_names=row[13],
                                vendor=row[14],
                                source=row[15],
                                notes=row[16],
                                total_cal=row[17],
                                num_servings=row[18],
                                ingredients=row[19],
                                calories=row[20],
                                proteins=row[21],
                                sugar=row[22],
                                carbohydrates=row[23],
                                fat=row[24],
                                consumer_category=row[25],
                                ws_case_size=row[26],
                                kiosk_ship_qty=row[27],
                                pick_station=row[28],
                                fc_title=row[29],
                                width_space=row[30],
                                height_space=row[31],
                                depth_space=row[32],
                                slotted_width=row[33],
                                tag_volume=row[34],
                                delivery_option=row[35],
                                tag_applied_by=row[36])
                db.session.add(query)
        try:
            db.session.commit()  # aren't added until this is called
            result = "Import Successful {} records processed".format(count)
            print(result)
            flash(result)
            return redirect(url_for('main.index'))
        except IntegrityError as e:
            result = "Integrity Error {}".format(e)
            print(result)
            flash("Data Import Already Complete")
            return redirect(url_for('main.index'))
    except IOError as e:
        flash("Error connecting to csv for import")
        print(e)
        return redirect(url_for('main.index'))
예제 #42
0
 def test_sort_by_highest_review(self):
     """Show the product with the highest review first"""
     watch = Product(name="I Watch", price=329)
     watch.set_id(2)
     watch.set_image_id("001")
     watch.set_description("Smart Watch")
     watch_review_list = [
         Review(username="******", score=4, detail="OK"),
         Review(username="******", score=4, detail="As expected"),
         Review(username="******", score=3, detail="So So")
     ]
     watch.set_review_list(watch_review_list)
     server.Product.catalog.save(watch)
     self.assertEqual(watch.get_name(), "I Watch")
     self.assertEqual(watch.get_price(), 329)
     self.assertEqual(watch.get_id(), 2)
     self.assertEqual(watch.get_image_id(), "001")
     self.assertEqual(watch.get_description(), "Smart Watch")
     self.assertEqual(watch.get_review_list(), watch_review_list)
     tv = Product(name="Apple TV", price=9999)
     tv.set_id(3)
     tv.set_image_id("001")
     tv.set_description("Hi-end TV")
     tv_review_list = [
         Review(username="******", score=5, detail="Excellent"),
         Review(username="******", score=5, detail="Loving this!!"),
         Review(username="******",
                score=5,
                detail="Highly recommend!"),
         Review(username="******", score=5, detail="Nice!")
     ]
     tv.set_review_list(tv_review_list)
     server.Product.catalog.save(tv)
     self.assertEqual(tv.get_name(), "Apple TV")
     self.assertEqual(tv.get_price(), 9999)
     self.assertEqual(tv.get_id(), 3)
     self.assertEqual(tv.get_image_id(), "001")
     self.assertEqual(tv.get_description(), "Hi-end TV")
     self.assertEqual(tv.get_review_list(), tv_review_list)
     resp = self.app.get('/products?sort=review')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     data = json.loads(resp.data)
     self.assertEqual(data[0]['name'], 'Apple TV')
     self.assertEqual(data[1]['name'], 'I Watch')
예제 #43
0
 usersubscription.end_date = datetime.strptime('06-02-2020 05:58:00',
                                               '%d-%m-%Y %H:%M:%S')
 usersubscription.subscription_type = subtype
 food_category = ProductCategory('food')
 clothes_category = ProductCategory('cloth')
 food_article = ArticleCategory('food-article')
 clothes_article = ArticleCategory('cloth-article')
 status = ArticleStatus('draft')
 order_status = OrderStatus('completed')
 db.session.add(order_status)
 db.session.add(food_article)
 db.session.add(clothes_article)
 db.session.add(food_category)
 db.session.add(clothes_category)
 for x in range(10):
     product = Product(randomString(10))
     product.image = 'https://i.imgur.com/xyAZ6sF.jpg,https://i.imgur.com/TcT4srW.jpg,https://i.imgur.com/79QF80y.jpg,https://i.imgur.com/CIAcwiV.jpg'
     product.images_album = 'P95VLN7'
     article = Article(randomString(10))
     order = Order()
     order_item = OrderItem()
     order_item.quantity = 1
     order_item.start_date = datetime.strptime('1-4-2020', '%d-%m-%Y')
     order_item.end_date = datetime.strptime('8-4-2020', '%d-%m-%Y')
     order.order_items = []
     order.order_items.append(order_item)
     article_category = food_article
     category = food_category
     if x % 2 == 0:
         category = clothes_category
         article_category = clothes_article
예제 #44
0
def GetStoreProducts(id):
	page = request.args.get('page', 1, type=int)
	per_page = min(request.args.get('per_page', 10, type=int), 100)
	data = Product.ToCollectionDict(Product.query.filter(Product.store_id == id), page, per_page, 'api.GetStoreProducts', id=id)
	return jsonify(data)
예제 #45
0
def test_instantiation():
    product = Product(id="ID001", name="Test Product", kind="generic")

    assert product.id == "ID001"
    assert product.name == "Test Product"
    assert product.kind == "generic"
예제 #46
0
def gen_prop(request):
    #generate prototype
    # print request.body
    # if request.POST:
    result = dict()
    try:
        data = json.loads(request.body)
        pt = Prototype()
        try:
            merchant = MainUser.objects.get(id=data['merchant_id'])
        except:
            return HttpResponse("error", status=500)

        pt.merchant = merchant
        ist = pytz.timezone("Asia/Kolkata")
        pt.key = hashlib.md5(str(datetime.datetime.now(tz=ist))+"42HACKSTREET").hexdigest()
        pt.save()

        qr_data = dict()
        qr_data['merchant'] = merchant.name
        qr_data['address'] = merchant.address
        qr_data['key'] = pt.key
        qr_data['type'] = 1
        qr_data['products'] = []

        for p in data['products']:
            name = p['name']
            sku = p['sku']
            manufacturer = p['manufacturer']
            price = p['price']
            currency = p['currency']
            desc = p['desc']
            quantity = p['quantity']
            pd = Product()
            pd.name = name
            pd.sku = sku
            pd.manufacturer = manufacturer
            pd.price = Decimal(price)
            pd.currency = currency
            pd.desc = desc
            pd.prototype = pt
            pd.quantity = quantity
            pd.save()
            qr_data['products'].append({
                'name': name,
                'price': "{0:.2f}".format(pd.price),
                'quantity': quantity,
                'currency': currency
            })
        qr = qrcode.QRCode(
            version=2,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(str(json.dumps(qr_data)))
        qr.make(fit=True)
        img = qr.make_image()
        output = StringIO.StringIO()
        img.save(output, 'GIF')
        contents = output.getvalue()
        data = base64.b64encode(contents)
        result['status'] = 'success'
        result['data'] = data
        return HttpResponse(json.dumps(result))
    except Exception,e:
        print e
예제 #47
0
def add_product(db):
    type1 = ProductType.query.filter_by(id=1).first()
    product1 = Product()
    product1.name = u'鸡肉汉堡'
    product1.description = u'美味的xxx汉堡诱惑你的味蕾'
    product1.type=type1
    product1.price=20

    product2 = Product()
    product2.name = u'牛肉汉堡'
    product2.description = u'美味的xxx汉堡诱惑你的味蕾'
    product2.type=type1
    product2.price=25

    product3 = Product()
    product3.name = u'蔬菜汉堡'
    product3.description = u'美味的xxx汉堡诱惑你的味蕾'
    product3.type=type1
    product3.price=30

    type2 = ProductType.query.filter_by(id=2).first()
    product4 = Product()
    product4.name = u'泰式面条'
    product4.description = u'美味的xxx面条诱惑你的味蕾'
    product4.type=type2
    product4.price=25

    product5 = Product()
    product5.name = u'川辣面条'
    product5.description = u'美味的xxx面条诱惑你的味蕾'
    product5.type=type2
    product5.price=30

    product6 = Product()
    product6.name = u'韩式面条'
    product6.description = u'美味的xxx面条诱惑你的味蕾'
    product6.type=type2
    product6.price=25

    db.session.add(product1)
    db.session.add(product2)
    db.session.add(product3)
    db.session.add(product4)
    db.session.add(product5)
    db.session.add(product6)
    db.session.commit()
예제 #48
0
def index():    
    arch_name = '/tmp/test.zip'
    zfile = open(arch_name, 'w')
    zfile.write(urllib2.urlopen(url).read())
    zfile.close()
    
    fh = open(arch_name, 'rb')
    z = zipfile.ZipFile(fh)
    for name in z.namelist():
        outfile = open(name, 'wb')
        outfile.write('/tmp/' + z.read(name))
        outfile.close()
    fh.close()
    
    product_file = open('product.txt')
    
    # miss titles
    for row in product_file:
        break
    i = 0
    for row in product_file:
        pr = row.split('\t')
        if not Product.query.filter(Product.ndc == pr[1]).first():    
            p = Product()
            p.id = pr[0]
            p.ndc = pr[1]
            p.typename = pr[2]
            p.proprietary_name = pr[3]
            p.proprietary_name_suffix = pr[4]
            p.non_proprietary_name = pr[5]
            p.dos_age_for_name = pr[6]
            p.route_name = pr[7]
            p.start_marketing_date = pr[8]
            p.end_marketing_date = pr[9]
            p.marketing_category_name = pr[10]
            p.application_number = pr[11]
            p.label_name = pr[12]
            p.substance_name = pr[13]
            p.active_numerator_strength = pr[14]
            p.active_ingred_unit = pr[15]
            p.pharm_classes = pr[16]
            p.deaschedule = pr[17]
            p.packages = []
            db.session.add(p)
            db.session.commit()
        i += 1
        if i > 1000:
            break
    product_file.close()

    return render_template('index.html')
예제 #49
0
def init():
    mer1 = Merchant(999, 'Test Company', 'Testing', 5.0)
    mer2 = Merchant(998, 'Test Company2', 'Testing', 5.2)
    mer3 = Merchant(997, 'Test Company3', 'Testing', 5.3)
    mer4 = Merchant(996, 'Test Company4', 'Testing', 5.5)
    mer5 = Merchant(995, 'Test Company5', 'Testing', 5.6)
    mer6 = Merchant(994, 'Test Company6', 'Testing', 5.7)
    sc1 = Subcategory(ps_id=999, ps_name="sc1")
    sc2 = Subcategory(ps_id=998, ps_name="sc2")
    sc3 = Subcategory(ps_id=997, ps_name="sc3")
    sc4 = Subcategory(ps_id=996, ps_name="sc4")
    sc5 = Subcategory(ps_id=995, ps_name="sc5")
    sc6 = Subcategory(ps_id=994, ps_name="sc6")
    c1 = Category(pc_id=999, pc_name="c1", ps_id=999)
    c2 = Category(pc_id=998, pc_name="c2", ps_id=998)
    c3 = Category(pc_id=997, pc_name="c3", ps_id=997)
    c4 = Category(pc_id=996, pc_name="c4", ps_id=996)
    c5 = Category(pc_id=995, pc_name="c5", ps_id=995)
    c6 = Category(pc_id=994, pc_name="c6", ps_id=994)

    p5 = Product(pid=995, pname='Disney Toy Story', qty=3, price=155, mid=995, status="Good", pc_id=995, ps_id=995,
                 link="https://images.hktv-img.com/images/HKTV/18800/H1283ToyStoryBook_main_36832182_20200409124617_01_1200.jpg")
    p6 = Product(pid=994, pname='FRONTLINE - Plus for Cats & Kittens 8 Weeks or Older', qty=4, price=159, mid=994,
                 status="Good", pc_id=994, ps_id=994,
                 link="https://images.hktvmall.com/h0888001/129563/h0888001_10130629_171018034423_01_1200.jpg")

    d1 = Disney(id=995, name="Disney Toy Story",
                link="https://images.hktv-img.com/images/HKTV/18800/H1283ToyStoryBook_main_36832182_20200409124617_01_1200.jpg",
                price=155, product_id=995)
    pet1 = Pets(id=995, name="FRONTLINE - Plus for Cats & Kittens 8 Weeks or Older",
                link="https://images.hktvmall.com/h0888001/129563/h0888001_10130629_171018034423_01_1200.jpg",
                price=159,
                product_id=994)
    p1 = Product(pid=999, pname='Testing Product1', qty=1, price=45, mid=999, status="Good", pc_id=999, ps_id=999,
                 link="https://picsum.photos/273/190")
    p2 = Product(pid=998, pname="TW Disposable Mask Protective Pad", qty=1, price=55, mid=998, status="Good", pc_id=998,
                 ps_id=998,
                 link="https://images.hktv-img.com/images/HKTV/10787/MIT-001A_main_35311815_20200310182421_01_1200.jpg")
    p3 = Product(pid=997, pname="FitBoxx - Everlast Evercool Gloves Bag", qty=1, price=56, mid=997, status="Good",
                 pc_id=997, ps_id=997, link="https://images.hktvmall.com/h0395001/m/photos/8831465193522_1_1200.jpg")
    p4 = Product(pid=996, pname="HKQgamers - Switch Game - Pokemon Sword", qty=2, price=44, mid=996, status="no",
                 pc_id=996, ps_id=996,
                 link="https://images.hktv-img.com/images/HKTV/10823/GA20191104A08_main_31312491_20191112141038_01_1200.jpg")
    h1 = Housewares(id=995, name="TW Disposable Mask Protective Pad",
                    link="https://images.hktv-img.com/images/HKTV/10787/MIT-001A_main_35311815_20200310182421_01_1200.jpg",
                    price=55, product_id=998)
    s1 = SportsAndTravel(id=995, name="FitBoxx - Everlast Evercool Gloves Bag",
                         link="https://images.hktvmall.com/h0395001/m/photos/8831465193522_1_1200.jpg", price=65,
                         product_id=997)
    t1 = ToysAndBooks(id=995, name="HKQgamers - Switch Game - Pokemon Sword",
                      link="https://images.hktv-img.com/images/HKTV/10823/GA20191104A08_main_31312491_20191112141038_01_1200.jpg",
                      price=44, product_id=996)
    admin = User(id=0, first_name="a", last_name="a", username="******", email="*****@*****.**", phone=132,
                 password_hash="pbkdf2:sha256:50000$K1aBNTtq$a627489faa2332223c5225bbc26a9c875d57437fa4865b83875eeb957b3f04dd")
    db.session.add(admin)
    v1 = Voucher(v_id=1,code="hktv",discount="10")
    db.session.add(v1)
    db.session.add(mer1)
    db.session.add(mer2)
    db.session.add(mer3)
    db.session.add(mer4)
    db.session.add(mer5)
    db.session.add(mer6)
    db.session.add(sc1)
    db.session.add(sc2)
    db.session.add(sc3)
    db.session.add(sc4)
    db.session.add(sc5)
    db.session.add(sc6)
    db.session.commit()
    db.session.add(c1)
    db.session.add(c2)
    db.session.add(c3)
    db.session.add(c4)
    db.session.add(c5)
    db.session.add(c6)
    db.session.commit()
    db.session.add(p1)
    db.session.add(p2)
    db.session.add(p3)
    db.session.add(p4)
    db.session.add(p5)
    db.session.add(p6)
    db.session.commit()
    db.session.add(h1)
    db.session.add(s1)
    db.session.add(t1)
    db.session.add(d1)
    db.session.add(pet1)
    db.session.commit()
    return redirect(url_for('main.index'))
예제 #50
0
def update_stock(stock, pk):
    product = Product.update(stock=stock).where(Product.id == pk).execute()
    print("Stock updated")
    return 200
예제 #51
0
from app import db

from app.models import Product

import json

# read products json file
with open('products.json') as f:
    file_data = json.load(f)

# loop though each product in json file and add to Product database and commit changes
for obj in file_data:
    new_row = Product(brand=obj["brand"],
                      name=obj["name"],
                      price=obj["price"],
                      quantity=obj["in_stock_quantity"])
    db.session.add(new_row)
    db.session.commit()
예제 #52
0
def list_product():
    print(Product.list_category())
    return jsonify(result=Product.list_category())
예제 #53
0
def product(product_id):
    product = Product()
    product.read_product(product_id)

    return product
예제 #54
0
    def setup_dummy_suppliers_with_old_and_new_domains(self, n):
        with self.app.app_context():
            framework = Framework.query.filter_by(
                slug='digital-outcomes-and-specialists').first()
            self.set_framework_status(framework.slug, 'open')

            for i in range(1, n + 1):
                if i == 2:
                    ps = PriceSchedule.from_json({
                        'serviceRole': {
                            'category':
                            'Technical Architecture, Development, Ethical Hacking and Web Operations',
                            'role': 'Senior Ethical Hacker'
                        },
                        'hourlyRate': 999,
                        'dailyRate': 9999,
                        'gstIncluded': True
                    })
                    prices = [ps]
                else:
                    prices = []

                NON_MATCHING_STRING = 'aaaaaaaaaaaaaaaaa'

                name = "Supplier {}".format(i - 1)
                summary = "suppliers of supplies" if name != 'Supplier 3' else NON_MATCHING_STRING
                name = name if name != 'Supplier 3' else NON_MATCHING_STRING

                t = pendulum.now('UTC')

                s = Supplier(
                    code=i,
                    name=name,
                    abn='1',
                    description="",
                    summary=summary,
                    data={'seller_type': {
                        'sme': True,
                        'start_up': True
                    }} if i == 2 else {
                        'sme': True,
                        'start_up': False
                    },
                    addresses=[
                        Address(address_line="{} Dummy Street".format(i),
                                suburb="Dummy",
                                state="ZZZ",
                                postal_code="0000",
                                country='Australia')
                    ],
                    contacts=[],
                    references=[],
                    prices=prices,
                    last_update_time=t + pendulum.interval(seconds=(i % 3)))

                if i == 2:
                    s.add_unassessed_domain('Data science')

                if i == 4:
                    s.add_unassessed_domain('Content and Publishing')

                if i == 3:
                    s.add_unassessed_domain('Content and Publishing')
                    s.add_unassessed_domain('Data science')
                    s.update_domain_assessment_status('Data science',
                                                      'assessed')

                p1 = Product(name='zzz {}'.format(i),
                             summary='summary {}'.format(i))
                p2 = Product(name='otherproduct {}'.format(i),
                             summary='othersummary {}'.format(i))

                s.products = [p1, p2]

                sf = SupplierFramework(supplier_code=s.code,
                                       framework_id=framework.id,
                                       declaration={})

                db.session.add(s)
                db.session.add(sf)

            ds = Supplier(
                name=u"Dummy Supplier",
                abn=Supplier.DUMMY_ABN,
                description="",
                summary="",
                addresses=[
                    Address(address_line="{} Dummy Street".format(i),
                            suburb="Dummy",
                            state="ZZZ",
                            postal_code="0000",
                            country='Australia')
                ],
                contacts=[],
                references=[],
                prices=prices,
            )

            ds.add_unassessed_domain('Content and Publishing')
            ds.add_unassessed_domain('Data science')
            ds.update_domain_assessment_status('Data science', 'assessed')

            db.session.add(ds)

            sf = SupplierFramework(supplier_code=ds.code,
                                   framework_id=framework.id,
                                   declaration={})

            db.session.add(sf)
            db.session.commit()
예제 #55
0
def create_book(name="Sherlock Homes", description="a house hunting real estate agent"):
    book = Product(name="Sherlock Homes", description="a house hunting detective", price_cents=500)
    db.session.add(book)
    db.session.commit()
    return book
예제 #56
0
def new_product():
    product = Product()
    product.import_data(request.json)
    db.session.add(product)
    db.session.commit()
    return jsonify({}), 201, {'Location': product.get_url()}
예제 #57
0
파일: main.py 프로젝트: polmarin/Bazar
def search():

    for user in User.query.all():
        time.sleep(2)
        print("User: "******"(" + user.email + ")")
        """ GET STORED PRODUCTS """
        search_data = Search.query.filter_by(user_id=user.id).all()
        search_terms = [s.name for s in search_data
                        ]  # List of search terms for current user
        product_data = Product.query.filter(
            Product.search.in_(search_terms)).all()
        d = {}
        if product_data != []:
            for product in product_data:
                prices = Price.query.filter_by(asin=product.asin).all()
                if product.search not in d:
                    d[product.search] = {product.asin: prices[-1].price}
                else:
                    d[product.search][product.asin] = prices[-1].price
        """ GET STORED SEARCH TERMS """
        search_list = []
        for search in search_data:
            search_list.append((search.name, search.category, search.max_price,
                                search.min_price, search.black_list))
        """ SCRAPE DATA """
        products = {}
        while products == {} or len(products[list(products.keys())[0]]) <= 1:
            products = scraper(d, search_list)

            #print("ERROR scraping data:")
            #print("User: "******"(" + user.email + ")")
            #print("Exception: " + str(e))
            #print("--------------------- Restarting ---------------------")
            time.sleep(2)

        print(products)

        print("SCRAPED")
        """ UPDATE DATABASE """
        dropped_prices = {}  # { "search" : [( prod , preu), (prod , preu)] }
        for search in products:
            for product in products[search][:-1]:

                asin = product.asin
                print("----------------")
                print(asin)
                if asin != "":
                    exists = Product.query.filter_by(
                        asin=asin).first() is not None

                    if not exists:
                        # PRODUCT NOT IN DATABASE
                        if product.rating != "":
                            new_product = Product(search, product.asin,
                                                  product.link, product.name,
                                                  product.prev_price,
                                                  product.last_price,
                                                  product.rating)
                        else:
                            new_product = Product(search, product.asin,
                                                  product.link, product.name,
                                                  product.prev_price,
                                                  product.last_price)
                        print(product)
                        db.session.add(new_product)
                        db.session.commit()
                        print("Added!")
                    else:
                        # PRODUCT ALREADY IN DATABASE
                        update_data_product = Product.query.filter_by(
                            asin=asin).first()
                        update_data_product.link = product.link
                        update_data_product.name = product.name
                        update_data_product.rating = product.rating
                        if product.last_price < update_data_product.last_price:
                            print("Price drop")
                            if search not in dropped_prices:
                                dropped_prices[search] = [
                                    (product, update_data_product.last_price)
                                ]
                            else:
                                dropped_prices[search].append(
                                    (product, update_data_product.last_price))
                        update_data_product.last_price = product.last_price

                    new_price = Price(
                        asin, product.last_price,
                        datetime.now(pytz.timezone("Europe/Madrid")).replace(
                            tzinfo=None))
                    db.session.add(new_price)
                    db.session.commit()

        if dropped_prices != {}:
            print(
                user.email +
                " should receive a mail with the products that just drpped their price."
            )
            send_last_hour_mail(dropped_prices, mail=user.email)