def attr(self, name): if name == 'url': r = self.doc.request query = dict(hl = self.hl, disc = r('disc'), adpr = r('adpr'), cdef = r('cdef')) if isfiche(self.source): return self.doc.geturl(self.param[:1] + self.param[2:], query = query, view = self.view, addmod = False) else: return self.doc.geturl(self.param[:const.PRODUCT_URL_LEN] + [self.partno1], query = query, addview = False, addmod = False) elif name == 'image': return self.doc.getimage(self.id_image, self, self.param) elif name == 'imagebig': if isproduct(self.source) and self.images: return self.images[0] elif name == 'images': q = sql.get_fval(['id_image'], 'image_deps', 'id_obj') q = sql.order(q, 'id') res = [] i = 1 for id in self.db.fetchvals(q, [self.id]): img = self.doc.getimage(id, self, self.param, i) res.append(img) i += 1 return res elif name == 'stored': qstore = sql.get_fval('SUM(quantity)', 'store', 'id_product') return self.db.fetchval(qstore, [self.id]) elif name == 'store': fields = ['SUM(s.quantity) AS quantity', 'pr.val1 AS eta', 'peta.name AS etaname'] f = ['p.id = s.id_store', 'id_product = %s'] f.append('pr.id_prop = p.id') f.append('pr.name = "ETA"') f.append('peta.translit = pr.val1') qstore = sql.get_f(fields, ['store s', 'prop p', 'param pr', 'prop peta'], f) qstore = sql.group(qstore, 'eta') qstore = sql.order(qstore, 'eta') res = Storage() res.data = self.db.fetchobj(qstore, [self.id]) res.quantity = self.stored res.available = True if self.stored else False q = sql.get_f('p.*', ['param pr', 'prop p'], ['pr.id_prop = %s', 'pr.name = "ETA"', 'p.translit = pr.val1']) res.default = self.db.fetchrowobj(q, [self.view.id_cat]) return res return None
def SearchProducts(self, res, doc): keys = [] for key in re.split(r'[,;\s]+', res.text): if key: keys.append(real_translit(key)) qlist = [] params = [] db = self._db for field in ('id', 'partno1', 'partno2'): qlist.append(sql.get_f('id', 'product', sql.fin(field, keys, True))) params += keys idl = db.fetchvals(sql.union(qlist), params) if not idl: return False res.count = len(idl) f = ['ps.id_product = p.id', 'pv.id_cat = ps.id_prop1'] q = sql.get_f('pv.id', ['pview pv', 'prop_set ps'], f) q = sql.order(q, 'pv.num') q = sql.limit(q, 0, 1) q = sql.get_f(['id', '(%s) AS id_view' % q], 'product p', sql.fin('id', idl)) for (idp, id) in db.fetchall(q): if id in res.filters: view = res.filters[id] else: view = classes.View(doc, id) view.k = doc.getk([view.id_cat], 'id') + [None] * 7 view.parsemap(view.k) view.products = [] res.filters[id] = view view.products.append(idp) for view in res.filters.itervalues(): view.frow = [sql.fin('id_product', view.products)] view.count = len(view.products)
def prodlist(self, doc, qsort): # SQL запрос - временная таблица 1 с ID товарами фильтра sqlpids = self.sqlpids(self.doc.view.pview, self.ppair) q = sql.temp(sqlpids, 'plist', sql.get(['count(*)'], '%s'), ['id_product']) # Блокируем DB для выполнения пакета запросов в одной сессии db = site.db.self() try: # Задаем кол-во товаров и страницы self.prodcount = db.fetchval(q) t = [self.doc.tproduct, sql.tempname('plist') + ' ps'] f = ['ps.id_product = p.id'] q = sql.get_f(['p.id'], t, f) q = sql.order(q, qsort) q = sql.limit(q, self.ppg * (self.page - 1), self.ppg) pids = db.fetchvals(q) if not pids: return [] pl = self.__proddata(db, doc.view, pids) if not doc.view.iss: self.__prodhint(db, doc.view, pl) finally: pass #db.shunlock() prodlist = map(lambda pid: pl[pid], pids) return prodlist
def CG8(): t1 = table.Table("data/posthistory.xml") t2 = group(t1,["UserId"],["PostId","CreationDate"],"list") t3 = order(t2,"PostId","CreationDate") # In each row, order postIds by date t4 = expand(t3) # Generate table with one row for each consecutive pair of postIds in each row of the original table g = graph.Graph("directed",False) g.addNodes(t1,"PostId") g.addEdges(t4,"PostId1","PostId2") return g
def f(): q = sql.get_f('s.id', 'store s', ['p.id = s.id_product', 's.quantity > 0']) q = sql.get_f('p.id', 'product p', sql.exists(q)) q = sql.order(q, 'p.id') pids = db.fetchvals(q) idmax = len(pids) - 1 idl = map(lambda x: str(pids[random.randint(0, idmax)]), xrange(10)) idl = ",".join(idl) site.config.set("RANDOM_PRODUCTS", idl) site.config.set("STATIC_PRODUCT", pids[0])
def prepare(self, doc): fblock = Storage() filters = [] ft = [] fp = [] params = {} filters = [] URL = '/lib/ichain.html' for key in ['mnf', 'mgroup', 'model', 'myear']: val = self(key) if val: ft.append(key + '=%s') fp.append(val) params[key] = val f = Storage() f.url = URL f.key = key f.val = val f.params = "&".join(map(lambda x: x[0] % urlquote(x[1]), zip(ft, fp[:-1]))) filters.append(f) else: q = sql.get_f('DISTINCT ' + key, 'dc_chain', ft) q = sql.order(q, key) fblock.data = [] for val in db.fetchvals(q, fp): if not val: continue row = Storage() row.name = val purl = params.copy() purl[key] = val row.url = URL row.params = dic2str(purl, "&", "%s=%s") fblock.data.append(row) fblock.key = key break if self('mgroup'): q = sql.get_f(['model', 'myear', 'chain', 'links'], 'dc_chain', ft) q = sql.order(q, 'model, myear') chains = db.fetchobj(q, fp) self.add(chains = chains) self.add(fblock = fblock, filters = filters, params = params)
def prepare(self, doc): gid = db.pgbytr("advert") t = ['prop p', 'sysid s'] f = ['p.id = s.id', 'p.id_group = %s'] q = sql.get_f('p.*, s.*', t, f) q = sql.order(q, 's.addate DESC') q = sql.limit(q, 0, 1) adverts = [] for row in db.fetchobj(q, [gid]): row = classes.Prop(doc, row) adverts.append(row) self.add(adverts = adverts)
def prepare(self, doc): gid = db.pgbytr("news") t = ['prop p', 'sysid s'] f = ['p.id = s.id', 'p.id_group = %s'] q = sql.get_f('p.*, s.*', t, f) q = sql.order(q, 's.addate DESC') news = [] for row in db.fetchobj(q, [gid]): row = classes.Prop(doc, row) row.new = newmarker(row.addate) news.append(row) self.add(news = news)
def prepare(self, doc): if self('static'): pid = site.config('STATIC_PRODUCT') else: idl = site.config('RANDOM_PRODUCTS') idl = idl.split(",") idx = random.randint(0, len(idl) - 1) pid = idl[idx] pid = toint(pid) product = classes.Product(doc, pid) self.add(product = product) gid = db.pgbytr("news") t = ['prop p', 'sysid s'] f = ['p.id = s.id', 'p.id_group = %s'] q = sql.get_f('p.*, s.*', t, f) q = sql.order(q, 's.addate DESC') q = sql.limit(q, 0, 3) news = [] for row in db.fetchobj(q, [gid]): row = classes.Prop(doc, row) row.new = newmarker(row.addate) news.append(row) self.add(news = news) gid = db.pgbytr("articles") t = ['prop p', 'sysid s'] f = ['p.id = s.id', 'p.id_group = %s'] q = sql.get_f('p.*, s.*', t, f) q = sql.order(q, 's.addate DESC') q = sql.limit(q, 0, 3) articles = [] for row in db.fetchobj(q, [gid]): row = classes.Prop(doc, row) row.new = newmarker(row.addate) row.url = doc.geturl([MOD_ARTICLE, row.translit], alwaysext = True) articles.append(row) self.add(articles = articles)
def f(): f = ['ps.id_product = p.id', 'pr.id_prop = ps.id_prop1', 'pr.name = "ETA"'] q = sql.get_f('pr.val1', ['prop_set ps', 'param pr'], f) q = '(%s)' % sql.limit(q, 0, 1) q = sql.update('eta', 'product p') % q db.execute(q) f = ['s.id_product = p.id', 'pr.id_prop = s.id_store', 'pr.name = "ETA"'] q = sql.get_f('pr.val1', ['store s', 'param pr'], f) q = sql.order(q, 'pr.val1') q = '(%s)' % sql.limit(q, 0, 1) fu = sql.get_f('id', 'store s', 's.id_product = p.id') fu = sql.exists(fu) q = sql.update('eta', 'product p', filter = fu) % q db.execute(q) db.commit()
def __slowid(self, params): img = self.request.img url = self.request.url p = self.request.params # IMAGE - Property if len(p) == 1: q = sql.get_fval('id_image', 'prop', 'translit') id = db.fetchval(q, p[0]) # Prop image by num if not id: mo = re.search(r'\-([a-z0-9])$', p[0]) if mo: f = ['p.id = id.id_obj', 'p.translit = %s', 'id.num = %s'] q = sql.get_f('id.id_image', ['image_deps id', 'prop p'], f) plist = [p[0][:-len(mo.group(0))], mo.group(1)] id = db.fetchval(q, plist) if id: url = url[6:] # IMAGE - Product else: pid = None if len(p) == const.IMAGE_URL_LEN + 1: pid = db.fetchval(sql.get_fval('id', 'product', 'partno1'), params[-1]) if pid: params.pop() DocCatalog.params(self, params) if not pid: pid = self.getpid() # Full Image if isint(img): q = sql.get_fval(['id_image'], 'image_deps', 'id_obj') q = sql.order(q, 'id_obj') idl = db.fetchvals(q, [pid]) if (img > 0) and img <= len(idl): id = idl[img - 1] else: self.NotFound('Image Index %d out of range' % img) # Preview else: q = sql.get_fval(['id_image'], self.tproduct, 'id') id = db.fetchval(q, [pid]) img_addcrc(db, url, id) return id
def prodlist(self, doc, qsort): q = doc.sqlpids(doc.view.pview, self.ppair) pid = db.fetchvals(q) if not pid: self.NotFound('Fiche not found') pid = pid[0] k = doc.kseries modellist = map(lambda k: k.name, (k[1], k[3], k[2])) translist = map(lambda k: k.translit, doc.kseries) fiche = db.fetchobject(doc.tproduct, pid) fiche.model = '%s %s %s' % tuple(modellist) fiche.img = doc.geturl(translist, ext = 'gif') fiche.imgs = doc.geturl(translist, img ='preview', ext = 'gif') img_addcrc(db, fiche.img, fiche.id_image) img_addcrc(db, fiche.imgs, fiche.id_image) self.add(fiche = fiche) q = sql.get_fval(['*'], doc.tprice, 'id_product') if qsort[0][0] == 'name': qsort[0] = ('CAST(num AS UNSIGNED)', 'ASC') q = sql.group(q, 'num, name') q = sql.order(q, qsort) prices = db.fetchobj(q, [pid]) log.t_trace('DOCatFiche.Prepare.Price requested') for row in prices: row.price = float(row.price) * float(site.config("CURRENCY", 2)) row.price = doc.getprice(row.price, True, row.currency) row.code = formatnumber(row.id, 9) row.req = row.req or '' log.t_trace('DOCatFiche.Price formatted') self.add(show_all = True) self.ppg = site.config('PROD_PER_PAGE', 2) self.prodcount = len(prices) i = self.ppg * (self.page - 1) prices = prices[i:i + self.ppg] log.t_trace('DOCatFiche.Prepare.Before return') return prices
from sql import select, project, rename, join, group from condition import Condition t1 = table.Table("data/posthistory.xml") t2 = group(t1,["PostId","UserId"]) t3 = join(t2,t2,["UserId"],["UserId"],["PostId"],["PostId"],["UserId","PostId1","PostId2"]) t4 = group(t3,["PostId1","PostId2"]) g = makeGraph(t4,"PostId1","PostId2","undirected",False) #CG8 import table import graph import sql from condition import Condition t1 = table.Table("data/posthistory.xml") t2 = sql.group(t1,["UserId"],["PostId","CreationDate"],"list") t3 = sql.order(t2,"PostId","CreationDate") # In each row, order postIds by date t4 = sql.expand(t3) # Generate table with one row for each consecutive pair of postIds in each row of the original table g = graph.Graph("directed",False) g.addNodes(t1,"PostId") g.addEdges(t4,"PostId1","PostId2") # CG9 import table import graph from gbuild import makeGraph from sql import select, project, rename, join, group from condition import Condition t1 = table.Table("data/badges.xml") #[UserId","Name"...] t2 = table.Table("data/posts.xml") #["Id","PostTypeId","OwnerUserId",...] t3 = join(t1,t2,["UserId"],["OwnerUserId"],["Name"],["PostTypeId","ParentId","Id"]) t4 = select(t3, Condition("PostTypeId", "==", 1)) #Questions
t1 = table.Table("data/posthistory.xml") t2 = group(t1, ["PostId", "UserId"]) t3 = join(t2, t2, ["UserId"], ["UserId"], ["PostId"], ["PostId"], ["UserId", "PostId1", "PostId2"]) t4 = group(t3, ["PostId1", "PostId2"]) g = makeGraph(t4, "PostId1", "PostId2", "undirected", False) #CG8 import table import graph import sql from condition import Condition t1 = table.Table("data/posthistory.xml") t2 = sql.group(t1, ["UserId"], ["PostId", "CreationDate"], "list") t3 = sql.order(t2, "PostId", "CreationDate") # In each row, order postIds by date t4 = sql.expand( t3 ) # Generate table with one row for each consecutive pair of postIds in each row of the original table g = graph.Graph("directed", False) g.addNodes(t1, "PostId") g.addEdges(t4, "PostId1", "PostId2") # CG9 import table import graph from gbuild import makeGraph from sql import select, project, rename, join, group from condition import Condition t1 = table.Table("data/badges.xml") #[UserId","Name"...]
def __loadmap(self): q = 'pview_map pm LEFT JOIN prop_group pg ON pg.id = pm.id_group' q = sql.get_fval(['pg.name', 'pm.*'], q, 'pm.id_pview') q = sql.order(q, 'pm.num') self.map = self.db.fetchobj(q, [self.id])
def getfblocks(self, doc): # Creating filter blocks blocks = doc.view.blocks Q_IDPRP = 'ps.id_prop%d' fblocks = [] i = 0 for b in blocks: log.t_trace("Cat Filter.beforeblock") if b.show: t = doc.tpropset f = map(lambda x: (Q_IDPRP + ' = %d') % x, b.filter.iteritems()) f.append("ps.pview = '%s'" % doc.view.pview) f.append(Q_IDPRP % b.propno + ' IS NOT NULL') f += doc.view.adfilter.sql(True) q = sql.get_f([Q_IDPRP % b.propno], t, f) f = ['ps.pview'] + map(lambda x: Q_IDPRP % x, b._group + [b.propno]) q = sql.group(q, f) idl = db.fetchvals(q) proplist = [] if idl: f = ["id IN (%s)" % (", ".join(map(str, idl)))] q = sql.get_f(['name', 'fname', 'translit', 'id_image'], 'prop', f) q = sql.order(q, 'name') proplist = db.fetchobj(q) b.hidden = b.hidden or not len(proplist) block = Storage() block.group = b.group block.active = False bd = [] block.data = bd url = doc.geturl(b.params) bd.append(Storage(dict(url = url, name = LEX_ALL, st = 'ACT'))) log.t_trace("Cat Filter.beforequery") avgwidth = 0 for prop in proplist: params = b.params[:] params[i] = prop.translit prop.url = doc.geturl(params) if b.k and b.k.translit == prop.translit: prop.st = 'ACT' bd[0]['st'] = 'GEN' block.active = True else: prop.st = 'GEN' width = min(len(prop.name), 30) * 6 prop.image = doc.getimage(prop.id_image, prop, [prop.translit]) #if prop.image: # width = prop.image.width avgwidth += width bd.append(prop) if avgwidth: avgwidth /= len(proplist) log.t_trace("Cat Filter.afterequery") block.columns = self.getcolumns(avgwidth, len(bd), b) block.b = b fblocks.append(block) i += 1 log.t_trace("Cat Filter.afterblock") return fblocks
def params(self, params): log.t_trace('dyna.params.start') if len(params) == 0: self.NotFound("Params length = 0") ptranslit = None if len(params) > 1: q = ['pv.id_cat = p.id', 'p.translit = %s', 'pv.translit = %s'] q = sql.get_f('pv.translit', 'pview pv, prop p', q) ptranslit = db.fetchval(q, params[:2]) if ptranslit: params.pop(1) self.opt.check = False self.k = self.getk(params) self.cat = classes.Cat(self, self.k[0]) self.__settables() self.__tryproduct(params) self.checkk(self.opt.dk, params) # Fetching view's information q = sql.get_fval(['*'], 'pview', 'id_cat') q = sql.order(q, 'num') log.t_trace('dyna.params.check3') self.view = None self.view0 = None self.views = [] for row in db.fetchobj(q, [self.cat.id]): view = classes.View(self, row) self.views.append(view) if self.opt.pid: if view.main: self.view = view elif ptranslit: if row.translit == ptranslit: self.view = view else: if row.num == 1: self.view = view if not self.view0 and (view.main or (self.cat.isfiche)): self.view0 = view if not self.view: self.NotFound("View is None (not found)") if not self.view0: self.NotFound("Default view is None (not found)") self.view.putk() self.view.parsemap() self.__markers() tlist = [] exc = eval(self.cat.params('EXC_%s_HINTS' % self.view.pview) or '[]') for i in xrange(len(self.k)): if i in exc: continue tlist.append(self.k[i]) self.title = formatname(tlist, lambda s: s.fname) plist = {} for k in self.kseries: p = k.params for row in p.data: plist[str(row.name)] = p(row.name, 1) self.addshared(**plist) self.add(price_min = parse_price_def(self.site.config, self('price_min'))) self.add(price_max = parse_price_def(self.site.config, self('price_max'))) self.savelist('show_store', 'price_min', 'price_max', 'list_view') log.t_trace('dyna.params.end')
def __proddata(self, db, view, pids): doc = self.doc view = doc.view0 fields = ['p.id', 'p.partno1'] tables = [doc.tpropset] k = len(view.groups) + 1 for i in xrange(1, k): tables.append('LEFT JOIN prop p%d ON ps.id_prop%d = p%d.id' % (i, i, i)) fields.append('MAX(p%d.translit) AS t%d' % (i, i)) tables = ["\n ".join(tables)] fields += ['p.name, p.note, p.price, p.price_in, p.price_out, p.currency, p.eta'] fields += ['img.id AS id_img'] tables.append(doc.tproduct + ' LEFT JOIN ' + doc.timage + ' ON p.id_image = img.id') fq = sql.get_f(['ids.id_image'], 'image_deps ids', 'ids.id_obj = p.id') fq = sql.order(fq, 'ids.id') fq = sql.limit(fq, 0, 1) fq = '(%s) AS id_img_big' % fq fields.append(fq) fstore = sql.get_f('SUM(s.quantity)', 'store s', ['s.id_product = p.id', 's.quantity > 0']) fstore = '(%s) AS stored' % fstore fields += [fstore] f = [sql.fin('p.id', pids)] f.append("p.id = ps.id_product") f.append("ps.pview = '%s'" % view.pview) q = sql.get_f(fields, tables, f) q = sql.group(q, 'p.id') pl = {} iml = [] for (key, row) in db.fetchdic(q).iteritems(): param = [] for prop in xrange(1, k): param.append(row['t' + str(prop)]) row.param = param row.smallprice = doc('list_view') == "store" p = classes.Product(doc, row) p.hints = [] p.rates = [] p.view = view pl[key] = p iml.append(p.id_img) iml.append(p.id_img_big) iml = notemptylist(iml) if iml: f = sql.fin('id', iml) q = sql.get_f(['id', 'name', 'type', 'width', 'height', 'size'], 'image', f) images = db.fetchdic(q) else: images = {} crclist = [] for p in pl.itervalues(): p.img = doc.getimage(images.get(p.id_img, None), p, p.param, crclist = crclist) p.img_big = doc.getimage(images.get(p.id_img_big, None), p, p.param, 1, crclist = crclist) img_addcrclist(db, crclist) return pl