def post(self): id = self.request.get('id') shop = Shop.all().filter('id = ', id).get() op = '' if shop: op = 'updated' shop.area = self.get_area_key(self.request.get('area')) shop.name = self.request.get('name') shop.address = self.request.get('address') shop.geo = db.GeoPt(lat = self.request.get('lat'), lon = self.request.get('lon')), shop.extra = self.request.get('extra') else: op = 'created' shop = Shop(id = int(id), area = self.get_area_key(self.request.get('area')), name = self.request.get('name'), address = self.request.get('address'), geo = db.GeoPt(lat = self.request.get('lat'), lon = self.request.get('lon')), extra = self.request.get('extra'), ) shop.put() self.response.out.write('%s %s.' % (self.request.get('name'), op))
def shops_updater(bot: Bot, job: Job) -> None: logger.debug("Entering: shops_updater") resp = requests.get(config.SHOP_API, verify=False) if resp.status_code == 200: logger.debug('Retrieved shop data. Dropping and recreating tables.') dbOffer.drop_table(with_all_data=True) dbShop.drop_table(with_all_data=True) db.create_tables(True) shops = resp.json() with orm.db_session: # TODO: Get f*****g marshmallow deserialisation working for shop in shops: logger.debug("creating shop %s", shop['name']) s = dbShop(link=shop['link'], name=shop['name'], ownerName=shop['ownerName'], ownerCastle=shop['ownerCastle'], kind=shop['kind'], mana=shop['mana']) for offer in shop['offers']: logger.debug("adding offer %s to shop %s", offer['item'], shop['name']) s.offers.create(**offer) else: logger.debug("Exiting: shops_updater") return
def addShop(request): name1 = request.POST['name'] location = request.POST['location'] description = request.POST['description'] shop = Shop(name=name1,location=location,description=description) shop.save() return displayShops(request,shop)
def __add_shop_to_database(self): shop = Shop(name=self.request.get('name'), area=self.request.get('area'), city=self.request.get('city'), postal_code=self.request.get('postal_code'), groceries=self.__return_basket_from_form() ) shop.price = get_basket_price_from_groceries(shop.groceries) self.__recalculate_price_classes(shop)
def setShopGrade(request): d = request.REQUEST data = json.loads(d['data']) print data result = Anlysis.judgeShop(data) shop = Shop(shopId=data["id"], grade=result["grade"], rid=result["rid"]) # print shop["shopId"] shop.save() return HttpResponse(json.dumps({"status": "success", "grade": shop.grade}))
def setShopGrade(request): d = request.REQUEST data = json.loads(d['data']) print data result = Anlysis.judgeShop(data) shop = Shop(shopId = data["id"], grade = result["grade"], rid = result["rid"]) # print shop["shopId"] shop.save() return HttpResponse(json.dumps({"status": "success", "grade": shop.grade}))
def get_shop(shop_uid): try: shop = Shop.get(uid=shop_uid) data = shop.get_display_data() except: data = None return data
class ShopTest(unittest.TestCase): def setUp(self): self.shop = Shop('4aa53e646bf84faca9a76c020b0682de', 'Kitten store', 18.06061237898499, 59.33265972650577) def test_add_tags(self): self.assertListEqual([], self.shop.tags) self.shop.add_tag('hej') self.assertListEqual(['hej'], self.shop.tags) self.shop.add_tag('hopp') self.assertListEqual(['hej', 'hopp'], self.shop.tags)
def product_create(request, values): shop = Shop.get(slug=values.get('slug')) if shop is None: raise NotFound() if request.method == 'GET': categories = Category.all() return render_template('product-form.html', { 'categories': categories, 'shop': shop }) name = request.form.get('name') price = request.form.get('price') description = request.form.get('description') categories = request.form.getlist('category') image = request.files.get('image') if image and allowed_image(image.filename): image_name = secure_filename(image.filename) image.save(os.path.join(MEDIA_ROOT, image_name)) else: image_name = '' product = Product.create(name=name, price=price, image=image_name, shop_id=shop.id, description=description) for category in categories: product.add_category(category) return redirect(f'/shops/{shop.slug}/products/{product.id}')
def setUp(self): self.design = Design(css_product='product.css', css_home='qshops-home.css', home_template='qshops-home.html', product_template='product.html') self.design.put() namespace_manager.set_namespace('b') self.shop = Shop().all().get() self.shop.design = self.design self.shop.put()
def post(self, subdomain): namespace_manager.set_namespace(subdomain) visible = False if self.request.get('visible') == 'yes': visible = True name = self.request.get('name') categories = self.request.get('category').split(',') logging.info(categories) cat_refs = [] for category in categories: logging.info(category) if Category.get_by_key_name(category): cat_refs.append(Category.get_by_key_name(category).key()) logging.info(cat_refs) entity = Product(key_name=name, name=name, shop_id=Shop.get_by_key_name(subdomain), stock=int(self.request.get('qty')), description=self.request.get('description'), price=float(self.request.get('price')), tags=self.request.get('tags').split(','), video=self.request.get('video'), visible=visible, categories=cat_refs ) entity.put() self.redirect(webapp2.uri_for('addproducts'))
def __recalculate_price_classes(self, newShop): # Get all shops in DB and append the newly added shop. shops = Shop.query_book().fetch() shops.append(newShop) prices = [] # Get a list of all prices for shop in shops: prices.append(shop.price) # Sort prices in ascending order prices.sort() # Define low and high price ranges lowPrice = 0.0 highPrice = 0.0 if(len(prices) > 0): minPrice = min(prices) maxPrice = max(prices) diff = maxPrice - minPrice lowPrice = minPrice+0.25*diff highPrice = minPrice+0.75*diff # Assign new price class and price index for every shop priceIndex = 1 for shop in shops: if shop.price < lowPrice: shop.priceClass = 1 elif shop.price > highPrice: shop.priceClass = 3 else: shop.priceClass = 2 shop.put()
def __create_shops_which_are_shown(self): amount_of_shops = 5 orde = 'Halvin' if self.request.get('order'): orde = self.request.get('order') if self.request.get('no_of_shops'): amount_of_shops = int(self.request.get('no_of_shops')) if self.request.get('area'): shops_to_show = Shop.query_book(order=orde, qo=Shop.area == self.request.get('area')).fetch(amount_of_shops) elif self.request.get('postal_code'): shops_to_show = Shop.query_book(order=orde, qo=Shop.postal_code == self.request.get('postal_code')).fetch(amount_of_shops) elif self.request.get('city'): shops_to_show = Shop.query_book(order=orde, qo=Shop.city == self.request.get('city')).fetch(amount_of_shops) else: shops_to_show = Shop.query_book(order=orde).fetch(amount_of_shops) return shops_to_show
def create(data): id = generate_id() owner = User.get(User.id == data['owner_id']) pk = Shop.insert(id=id, name=data['name'], city=data['city'], owner=owner).execute() return id
class TestStyles(unittest.TestCase): def setUp(self): self.design = Design(css_product='product.css', css_home='qshops-home.css', home_template='qshops-home.html', product_template='product.html') self.design.put() namespace_manager.set_namespace('b') self.shop = Shop().all().get() self.shop.design = self.design self.shop.put() def test_reserved(self): namespace_manager.set_namespace('b') self.assertTrue(True, 'Not reserving correctly')
def post(self): id = self.request.get('id') shop = Shop.all().filter('id = ', int(id)).get() if shop: shop.delete() self.response.out.write('%s deleted.' % self.request.get('name')) else: self.response.out.write('%s not found' % self.request.get('name'))
def get(self, subdomain): '''Saving current namespace''' namespace = namespace_manager.get_namespace() '''Changing the namespace''' namespace_manager.set_namespace(subdomain) '''The following query only look into the current namespace''' query = Shop.all().filter('shopname',subdomain).get() if query is None: entity = Shop(key_name=subdomain, shopname=subdomain, times_visited=0) entity.put() ''' We set the previous namespace back ''' namespace_manager.set_namespace(namespace) self.response.write('Shop created') else: self.response.write('The shop already exists')
def callback(): shop = request.args.get('shop') code = request.args.get('code') given_hmac = request.args.get('hmac') #validate the hmac, to make sure we're not being screwed around with h = dict([(key, value) for key, value in request.args.items() if key not in ['hmac', 'signature']]) # now sort lexicographically and turn into querystring query = '&'.join(["{0}={1}".format(key, h[key]) for key in sorted(h)]) # generate the digest digest = hmac.new(app.config['SHOPIFY_APPLICATION_SECRET'], msg=query, digestmod=hashlib.sha256).hexdigest() if given_hmac != digest: abort(403, "Authentication failed. Digest provided was: {0}".format(digest)) else: # we're in! get an access token payload = { 'client_id': app.config['SHOPIFY_APPLICATION_KEY'], 'client_secret': app.config['SHOPIFY_APPLICATION_SECRET'], 'code': code } result = requests.post( "https://{}/admin/oauth/access_token".format(shop), data=payload) current_shop = Shop.query.filter(Shop.shopify_domain == shop).first() if current_shop is None: access_token = json.loads(result.text)['access_token'] current_shop = Shop(shop, access_token) current_shop.Save() if current_shop is not None: session["shop_id"] = current_shop.id session["shopify_domain"] = current_shop.shopify_domain return redirect("/")
def index(): if session.get("shop_id"): current_shop = Shop.query.filter( Shop.id == session.get("shop_id")).first() with current_shop: flash("Hello {}".format(Shop.current().shop_owner)) return render_template("embedded/index.html") else: return redirect("/login")
def get(self, subdomain): namespace_manager.set_namespace(subdomain) shop = Shop.all().get() designs = Design.all() context = { 'url':webapp2.uri_for('addproducts'), 'designs':designs, 'shop':shop, } self.render_response('admin-products.html',**context)
def get(self, request): state = request.GET.get('state', None) session_state = request.session.get('state', None) if not state or not session_state or state != session_state: return HttpResponseForbidden() params = { 'shop': request.GET.get('shop', None), 'code': request.GET.get('code', None), 'timestamp': request.GET.get('timestamp', None), 'signature': request.GET.get('signature', None), 'state': request.GET.get('state', None), 'hmac': request.GET.get('hmac', None), } session = shopify.Session( 'https://%s.%s%s' % (request.GET.get('shop', None), settings.SHOPIFY_URL, settings.SHOPIFY_AUTHORIZE_SUFIX)) session.setup(api_key=settings.SHOPIFY_API_KEY, secret=settings.SHOPIFY_SECRET) try: token = session.request_token(params) except shopify.ValidationException: return HttpResponseForbidden() context = {} context["shop"] = request.GET.get('shop', None) context["api_key"] = settings.SHOPIFY_API_KEY shop = Shop.objects.filter(name=context["shop"]) request.session['shop_name'] = request.GET.get('shop', None) request.session['shop_token'] = token if not shop: shop_obj = Shop(name=context["shop"], token=token) shop_obj.save() activate_shopify_session(request) webhook = shopify.Webhook() webhook.topic = "app/uninstalled" webhook.address = "https://app.roojet.com/uninstall/" webhook.format = "json" success = webhook.save() return render(request, self.template_name, context)
def new_shop(): form = ShopForm() if form.validate_on_submit(): if Shop.query.filter_by(name=form.name.data).first(): flash('Shop already exists. Enter new one...') else: shop = Shop(name=form.name.data) db.session.add(shop) db.session.commit() return redirect('/new-shop') return render_template('shop.html', shops=Shop.query.all(), form=form)
def create(data): try: id = generate_id() owner = Shop.get(Shop.id == data['shop_id']) pk = User.insert(id=id, name=data['name'], city=data['city'], shop=shop).execute() return id except: return 'Can\'t create product'
async def command_add_new_shop_action_final(message: types.Message, state: FSMContext): cash_machine = message.text cash_machine = cash_machine.strip() await state.update_data(cash_machine=cash_machine) data = await state.get_data() new_shop = Shop(data['district'], data['shop_name'], data['official_shop_name'], data['address'], data['owner'], data['phone_number'], data['seller_name'], data['cash_machine']) new_shop.add_shop() await message.answer(f"Готово!\n" f"Торговая точка была добавлена в базу!\n\n" f"{data['shop_name']}\n" f"{data['owner']} {data['official_shop_name']}\n" f"Адрес: {data['district']}, {data['address']}\n" f"Телефон: {data['phone_number']}\n" f"Продавец: {data['seller_name']}\n" f"Кассовый аппарат: {data['cash_machine']}") await state.finish()
def shop_review_create(request, values): shop = Shop.get(slug=values.get('slug')) if shop is None: raise NotFound() username = request.form.get('username') text = request.form.get('text') ShopReview.create(username=username, text=text, shop_id=shop.id) return redirect(shop.get_absolute_url())
def get(self, key): shops = Shop.all().order('area') template_vars = { 'shops': shops } if key: entry = db.get(key) if entry.user == users.get_current_user(): template_vars['object'] = entry self.render_response('blog/blog_edit.html', template_vars) else: self.redirect('/blog/edit') else: self.render_response('blog/blog_edit.html', template_vars)
def shop_detail(request, values): shop = Shop.get(slug=values.get('slug')) if shop is None: raise NotFound() categories = Category.all() return render_template('shop.html', { 'shop': shop, 'categories': categories })
def insert_data(self): self.session.add_all([ Shop(name="Auchan", address=None, staff_amount=250), Shop(name="IKEA", address="Street Žirnių g. 56, Vilnius, Lithuania.", staff_amount=250) ]) self.session.commit() self.session.add_all([ Department(sphere="Furniture", staff_amount=250, shop_id=1), Department(sphere="Furniture", staff_amount=300, shop_id=2), Department(sphere="Dishes", staff_amount=200, shop_id=2) ]) self.session.commit() self.session.add_all([ Item(name="Table", description="Cheap wooden table", price=300, department_id=1), Item(name="Table", description=None, price=750, department_id=2), Item(name="Bed", description="Amazing wooden table", price=1200, department_id=2), Item(name="Cup", description=None, price=10, department_id=3), Item(name="Plate", description="Glass Plate", price=20, department_id=3) ]) self.session.commit()
def __get_cities_and_postal_codes(self): #TODO: This is nasty and costly one. We are just fetching all shops from the DB. shops = Shop.query_book().fetch(1000) cities = [] postal_codes = [] areas = [] for shop in shops: if shop.city not in cities: cities.append(shop.city) if shop.area not in areas: areas.append(shop.area) if shop.postal_code not in postal_codes: postal_codes.append(shop.postal_code) return sorted(cities), sorted(areas), sorted(postal_codes)
def shop_create(request, values): name = request.form.get('name') slug = request.form.get('slug') image = request.files.get('image') if image and allowed_image(image.filename): image_name = secure_filename(image.filename) image.save(os.path.join(MEDIA_ROOT, image_name)) else: image_name = '' shop = Shop.create(name=name, slug=slug, image=image_name) return redirect(shop.get_absolute_url())
def get_shop_list(shop_type=None,cat=None,price_range=None,trade_mark_style=None,region=None,\ trade_mark_transfer=None, is_all_red=None, is_no_punishment=None, sort=None, page=1,per_page=5): price_ranges=[(0,3),(3,5),(5,10),(10,20),(20,30),(30,50),(50,1000)] shop_type_filter=Shop.shop_type==shop_type if shop_type else None price_filter=Shop.price.between(price_ranges[price_range][0],price_ranges[price_range][1])\ if price_range in [0,1,2,3,4,5,6] else None category_filter=Shop.category==cat if cat else None region_filter=Shop.region==region if region else None trade_mark_filter=Trademark.mark_type==trade_mark_style if trade_mark_style else None trade_mark_transfer_filter = Trademark.transfer==trade_mark_transfer if trade_mark_transfer else None is_all_red_filter = Shop.is_all_red==True if is_all_red else None is_no_punishment_filter = Shop.is_no_punishment==True if is_no_punishment else None multi_filter=[] for i in [shop_type_filter,category_filter,price_filter,region_filter,trade_mark_filter,\ trade_mark_transfer_filter,is_all_red_filter,is_no_punishment_filter]: if i: multi_filter.append(i) if multi_filter: if trade_mark_filter or trade_mark_transfer_filter: query = Shop.select().join(Trademark).where(*multi_filter) else: query = Shop.select().where(*multi_filter) else: query =Shop.select() # 排序 if sort == 'time': query = query.order_by(Shop.level.desc(), Shop.created_datetime.desc()) elif sort == 'price': query = query.order_by(Shop.price.asc(), Shop.level.desc()) # 分页 shops =query.paginate(page=page,paginate_by=per_page) return { 'code': 0, 'total_count':query.count(), 'data': [q.get_display_data() for q in shops], 'message': u'正常' }
def generate_shop(session: Session, count: int) -> list: faker = Faker() result = [] for i in range(count): name = faker.company() description = faker.bs() site = faker.domain_name() shop = Shop(name=name, description=description, site=site) result.append(shop) session.add(shop) log.debug(f"Generate shop: {shop}") session.commit() for i in result: session.refresh(i) return result
def shop_category(request, values): shop = Shop.get(slug=values.get('slug')) if shop is None: raise NotFound() category = Category.get(name=values.get('category')) if category is None: raise NotFound() products = Product.get_by_shop_category(shop.id, category.id) return render_template('category.html', { 'category': category, 'shop': shop, 'products': products })
def product_update(request, values): shop = Shop.get(slug=values.get('slug')) product = Product.get(pk=values.get('id')) product_categories = [category.id for category in product.get_categories()] if shop is None or product is None: categories = Category.all() return render_template( 'product-form.html', { 'categories': categories, 'shop': shop, 'product': product, 'product_categories': product_categories, }) name = request.form.get('name') price = request.form.get('price') description = request.form.get('description') categories = request.form.getlist('category') image = request.files.get('image') if image and image.filename != product.image: if allowed_image(image.filename): image_name = secure_filename(image.filename) image.save(os.path.join(MEDIA_ROOT, image_name)) if product.image != '': os.remove(os.path.join(MEDIA_ROOT, product.image)) else: image_name = '' else: image_name = '' product.update( name=name or product.name, price=price or product.price, description=description or product.description, image=image_name or product.image, ) # TODO: update categories return redirect(f'/shops/{shop.slug}/products/{product.id}')
def post(self, *args): form = BlogEntryForm(data=self.request.POST) if form.is_valid(): shop = db.get(self.request.get('shop')) if self.request.get('key'): entry = db.get(self.request.get('key')) entry.shop = shop entry.title = self.request.get('title') entry.body = self.request.get('body') else: entry = BlogEntry(user = users.get_current_user(), shop = shop, title = self.request.get('title'), body = self.request.get('body'), ) entry.put() self.redirect('/blog') else: shops = Shop.all().order('area') template_vars = { 'shops': shops, 'form': form } self.render_response('blog/blog_edit.html', template_vars)
def fill_db(name): shop = Shop(name) list_supplier = [['reep', '*****@*****.**'], ['megacorp', '*****@*****.**'], ['ajax', '*****@*****.**'], ['jungle', '*****@*****.**'], ['gnom', '*****@*****.**'], ['qwerty', '*****@*****.**']] list_product = [['автомобили', 122, 953, 4], ['авиатехника', 121, 755, 3], ['автомобили_грузовые', 8123, 56, 2], ['корабли', 125, 978, 1], ['одежда', 126, 877, 4], ['электроинструменты', 126, 777, 2], ['мотоциклы', 126, 677, 3], ['украшения', 126, 777, 1], ['мебель', 345, 889, 5], ['игрушки_авиамодели', 324, 998, 6], ['drons', 234, 876, 3], ['книги_журналы', 324, 898, 5], ['робототехника', 567, 987, 6]] list_foodstaff = [['бананы', 124, 23, 'аргентина', '11,09,17', 1], ['киви', 127, 234, 'chili', '12,09,17', 2], ['апельсины', 128, 73, 'египет', '13,09,17', 3], ['виноград', 120, 355, 'chili', '12,09,17', 4], ['манго', 128, 70, 'египет', '13,09,17', 3], ['яблоки', 528, 71, 'черногория', '13,09,17', 4], ['лимоны', 128, 70, 'марокко', '13,07,17', 5], ['сахар', 128, 70, 'куба', '13,09,17', 6], ['персики', 328, 77, 'армения', '23,11,17', 2]] for i in list_supplier: shop.add_supplier(i[0], i[1]) for i in list_product: shop.add_product(i[0], i[1], i[2], i[3]) for i in list_foodstaff: shop.add_foodstuff(i[0], i[1], i[2], i[3], i[4], i[5])
def list_shops(bot: Bot, update: Update) -> None: logger.debug("Entering: list_shops") chat = update.effective_chat # type: Chat msg = update.effective_message # type: Message usr = update.effective_user # type: User responses = [] with orm.db_session: shops = dbShop.select(lambda s: s).order_by(dbShop.kind, dbShop.ownerCastle) num = shops.count() for page in range(1, ceil(num / config.RESULT_SIZE) + 1): response = '' for shop in shops.page(page, pagesize=config.RESULT_SIZE): response += f'<a href="https://t.me/share/url?url=/ws_{shop.link}">{shop.kind}{shop.name}</a> ' response += f'<i>{shop.mana}💧</i> by <b>{shop.ownerCastle}{shop.ownerName}</b>' response += '\n\n' responses.append(response) for response in responses: msg.reply_text(response, parse_mode='HTML')
def post(self): lnd = self.request.get('lnd') if lnd: geo = Geocoder(apikey=apikey) lnd_coord = geo.geocode(location=lnd) if lnd_coord: shops = Shop.all() shops = [ (shop, calc_distance(shop, lnd_coord), mapurl(shop.geo.lat, shop.geo.lon) ) for shop in shops ] shops.sort(key=lambda k: k[1]['distance']) self.render_response('mobile/search_result.html', { 'lnd': lnd, 'lnd_map': mapurl(lnd_coord['lat'], lnd_coord['lng']), 'shops': shops[0:30] }) else: self.response.out.write('not found') else: self.redirect('/m/search')
def setUp(self): """Make demo data.""" Image.query.delete() Shop.query.delete() User.query.delete() user = User.signup(**USER) shop = Shop(**SHOP) image_1 = Image(**IMAGE_1) image_2 = Image(**IMAGE_2) db.session.add_all([user, shop, image_1, image_2]) db.session.commit() db.session.refresh(user) db.session.refresh(shop) db.session.refresh(image_1) db.session.refresh(image_2) db.session.expunge_all() self.user = user self.shop = shop self.image_1 = image_1 self.image_2 = image_2
def get(self): shops = Shop.all().order('area') template_vars = { 'object_list': shops } self.render_response('shop/shop_list.html', template_vars)
def get(self, id): shop = Shop.all().filter('id = ', int(id)).get() template_vars = { 'object': shop } self.render_response('shop/shop_detail.html', template_vars)
users = [ User.signup(username="******", password="******", first_name="Desmond", last_name="McLemore"), User.signup(username="******", password="******", first_name="Justin", last_name="Ludington") ] db.session.add_all(users) shops = [ Shop(name="Dog Photos", description="Just a bunch of cute dog pics!!", is_private=False, user="******"), Shop(name="Practice Shots", description="Practice shots", is_private=True, user="******"), Shop(name="Not Practice Shots", description="These ones aren't practice.", is_private=False, user="******") ] db.session.add_all(shops) images = [ Image(
Publisher(id=1, name='Поставщик №1'), Publisher(id=2, name='Поставщик №2'), Publisher(id=3, name='Поставщик №3') ]) session.commit() session.add_all([ Book(id=1, title='Книга 1 поставщика №1', id_publisher=1), Book(id=2, title='Книга 2 поставщика №1', id_publisher=1), Book(id=3, title='Книга 3 поставщика №1', id_publisher=1), Book(id=4, title='Книга 1 поставщика №2', id_publisher=2), Book(id=5, title='Книга 2 поставщика №2', id_publisher=2), Book(id=6, title='Книга 1 поставщика №3', id_publisher=3) ]) session.commit() session.add_all([ Shop(id=1, name='Магазин №1'), Shop(id=2, name='Магазин №2') ]) session.commit() session.add_all([ Stock(id=1, count=3, id_book=1, id_shop=1), Stock(id=2, count=2, id_book=1, id_shop=2), Stock(id=3, count=5, id_book=2, id_shop=2), Stock(id=4, count=0, id_book=3, id_shop=1), Stock(id=5, count=2, id_book=4, id_shop=1), Stock(id=6, count=3, id_book=4, id_shop=2), Stock(id=7, count=4, id_book=6, id_shop=1) ]) session.commit() session.add_all([ Sale(id=1, price=15, date_sale='11.02.2020', id_stock=1, count=3),
def make_shop(self, data): return Shop(**data)
def trade_add(request): goods_top = Trade.objects.values('goods__id','goods__title').annotate(goods_count=Count('goods')).order_by('-goods_count')[:10] price1 = 0 results = [] if request.method == 'POST': # If the form has been submitted... form = TradeForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... #return HttpResponseRedirect('/thanks/') # Redirect after POST #results = GClass.objects.filter(title__icontains=form.cleaned_data['goodstitle']) isOldTrade = False if int(form.cleaned_data["trade_pk"]) > 0: isOldTrade = True shop1 = None if int(form.cleaned_data["shop_pk"]) > 0: shop1 = Shop.objects.get(pk=form.cleaned_data["shop_pk"]) else: shop1 = Shop(title=form.cleaned_data["shop"], type='mag') shop1.save() #gclass1 = None #if int(form.cleaned_data["gclass_pk"]) > 0: # gclass1 = GClass.objects.get(pk=form.cleaned_data["gclass_pk"]) #else: # gclass1 = GClass(title=form.cleaned_data["gclass"], section=GSection.objects.get(pk=1)) #TODO GSection # gclass1.save() goods1 = None if int(form.cleaned_data["gtitle_pk"]) > 0: goods1 = Goods.objects.get(pk=form.cleaned_data["gtitle_pk"]) goods1.title = form.cleaned_data["gtitle"] goods1.ed = form.cleaned_data["ed"] #goods1.gclass = gclass1 goods1.save() else: goods1 = Goods(title=form.cleaned_data["gtitle"], ed=form.cleaned_data["ed"]) goods1.save() price1 = "%.2f" % ( float(form.cleaned_data['cost']) / float(form.cleaned_data['amount']) ) if isOldTrade: trade1 = Trade.objects.get(pk=form.cleaned_data["trade_pk"]) else: trade1 = Trade() trade1.user = request.user trade1.shop = shop1 trade1.goods = goods1 trade1.time = form.cleaned_data["time"] trade1.amount = form.cleaned_data["amount"] trade1.price = price1 trade1.cost = form.cleaned_data["cost"] trade1.currency = form.cleaned_data["currency"] trade1.spytrade = form.cleaned_data["spytrade"] trade1.save() return HttpResponseRedirect("/") else: data = {'time': datetime.datetime.now, 'trade_pk': '0', 'shop_pk': '0', 'gclass_pk': '0', 'gtitle_pk': '0' } form = TradeForm(initial=data) # An unbound form return render_to_response('trade_add.html', {'price': price1, 'results': results, 'form': form, 'goods_top': goods_top}, context_instance=RequestContext(request))
def getById(id): return Shop.select().where(Shop.id == id)
def delete(id): try: shop = Shop.get(Shop.id == id) return shop.delete_instance() except: return 'Shop not found'
def find(keyword): return Shop.select().where(Shop.name.contains(keyword))
def get(self, key): shops = Shop.all().order('area') template_vars = { 'shops': shops } if key: template_vars['object'] = db.get(key) self.render_response('photo/photo_edit.html', template_vars)
def setUp(self): self.shop = Shop('4aa53e646bf84faca9a76c020b0682de', 'Kitten store', 18.06061237898499, 59.33265972650577)
# запись результата запросов потоками в .txt файлы и запуск сервера from models import Shop from fill_db import fill_db import os import json import threading import sys DIR = 'save_query_files' shop = Shop('shop_base.db') # имя бд sqlite shop.create_new() fill_db('shop_base.db') # автозаполнение бд class WriteStream(threading.Thread): def __init__(self, name_file, query): super().__init__() self.name_file = name_file self.query = query def run(self): result = [] for i in self.query: result.append(i) with open(os.path.join(DIR, self.name_file), 'w', encoding='UTF-8') as f: json.dump(result, f) class ReadStream(threading.Thread): def __init__(self, name_file):
def update(data, id): return Shop.update(data).where(Shop.id == id)
def get(self): shops = Shop.all().order('area') template_vars = {'object_list': shops} self.response.headers['Content-Type'] = 'text/plain; charset=utf-8' self.render_response('shop/shop_kml.xml', template_vars)