def data_good(request): if os.environ.get("TEST", None): request.session["userId"] = request.GET["userId"] try: if not "userId" in request.session: return HttpResponse("error") if not "user" in request.GET: return HttpResponse("error") if not request.GET["user"] == request.session["userId"]: return HttpResponse("error") user = request.GET["user"] user = User.objects.get(openId=user) target = int(request.GET["target"]) type = int(request.GET["type"]) item = Good.objects.filter(user=user,target=target,type=type) if type == 0: tmp = User.objects.get(id=target) elif type == 1: tmp = Plan.objects.get(id=target) goods = tmp.goods if item.count() == 0: item = Good(user=user,target=target,type=type) item.save() tmp.goods = goods + 1 else: tmp.goods = goods - 1 item[0].delete() tmp.save() return HttpResponse("success") except: return HttpResponse("error")
def addGood(request): buy_agent = MyBackend().authenticate(request.POST['username'], request.POST['password']) if buy_agent == None or (buy_agent.groups.all()[0].name != 'B' and not buy_agent.is_superuser) : return HttpResponse('borooo') today = jDateField() today = today.to_python(datetime.datetime.now()) order = Order.objects.filter(pk=int(request.POST['order']))[0] orderitem = OrderItem.objects.filter(pk=int(request.POST['orderitem']))[0] orderitem.status = 'I' orderitem.save() if not order.user == None: inform_user(user=order.user, message=render_to_string('mail/orderitem_available.html', {'orderitem': orderitem}), subject='سفارش شما در انبار موجود است') if not OrderItem.objects.filter(order=order).exclude(status='I'): order.status = 'D' order.save() for i in range(0, orderitem.quantity): good = Good(submitDate=today, category=orderitem.category, user=order.user, orderitem=orderitem, status='W') good.save() c = {'rlink': '../../allgoods/', 'success': "کالاها با موفقیت ثبت شدند"} return render_to_response("success.html", c)
def add(): if not is_admin_connected(): abort(401) good = Good() good.nom = request.form["name"] good.asso = request.form["asso"] good.semestre = request.form["semestre"] good.nb_exemplaires = request.form["exemplaires"] good.contenance = request.form["capacity"] good.commentaires = request.form["comment"] db.session.add(good) db.session.commit() db.session.flush() db.session.refresh(good) file = request.files['file'] if file: extension = file.filename.split(".")[-1] file.save( os.path.join(conf.UPLOAD_FOLDER, str(good.id) + "." + extension)) good.image_url = str(good.id) + "." + extension db.session.add(good) db.session.commit() flash("Écocup %s ajoutée" % good.nom, "success") return render_template("admin/index.html", **locals())
def save_offers_to_db(db, offers: List[dict]): # TODO make versions for offers (probably by date) for offer in offers: vader_id = offer["vader_id"] good_orm = Good(vader_id=vader_id) parameters = [ Parameter(good=good_orm, name=name, value=value) for name, value in offer["params"].items() ] good_orm.parameters = parameters db.add(good_orm) db.commit()
def add(): if not is_admin_connected(): abort(401) good = Good() good.nom = request.form["name"] good.asso = request.form["asso"] good.semestre = request.form["semestre"] good.nb_exemplaires = request.form["exemplaires"] good.contenance = request.form["capacity"] good.commentaires = request.form["comment"] db.session.add(good) db.session.commit() db.session.flush() db.session.refresh(good) file = request.files['file'] if file: extension = file.filename.split(".")[-1] file.save(os.path.join(conf.UPLOAD_FOLDER, str(good.id) + "." + extension)) good.image_url = str(good.id) + "." + extension db.session.add(good) db.session.commit() flash("Écocup %s ajoutée" % good.nom, "success") return render_template("admin/index.html", **locals())
def save_good( request ) : gname = request.GET['gname'].strip() gprice = request.GET['gprice'].strip() lang_name = request.GET['lang'] unit_name = request.GET['unit'] unit = Unit.objects.get(name = unit_name) cat = Category.objects.get(slug = request.GET['cat']) lang = Lang.objects.get(name = lang_name) tag = request.GET['tags'].strip() good = Good(name = gname, price = gprice, unit = unit, cath = cat) good.save() good.langs.add(lang) for tagname in TagDelim.split(tag) : try: T = Tag.objects.get( name = tagname) except Tag.DoesNotExist: T = Tag(name = tagname) T.save() good.tags.add(T) return render_to_response(u'goods.html',locals())
def main(): with open("test_goods.json") as fh: goods = json.load(fh) for good in goods: good = JSDict.from_dict(good) good_rec = Good(name=good.name, description=good.description, price=good.price) for img in good.images: img = JSDict.from_dict(img) img_rec = Image(path=img.path, good=good_rec) db.session.add(img_rec) db.session.add(good_rec) db.session.commit()
def create_g_o(c, params): if c[1] == 'G': #теперь создадим объект класса Good temp = Good(params['name'], params['country'], params['cost'], params['date']) type = 'good' #и сразу в файл его, в файл. elif c[1] == 'O': temp = Order(params['name'], params['country'], params['date']) temp.price_of_order = 0 type = 'order' else: print 'f**k(' return None new_id = settings['last_id'] + 1 print new_id obj = temp.to_dict() settings['last_id'] = new_id save_id(settings) full_path = "%s\%s-%s_%s_%d.json" % (STORAGE_ROOT, type, obj['name'], obj['country'], new_id) wfile = open(full_path, 'w') json.dump(obj, wfile) wfile.close()
def goods_state(self, message, entry=False): texts = self.get_texts() user = self.get_user(message) print("god") goods = group_by_name(Good.objects(city_id=str(user.city.id))) if self.botType == "fi": messId = message.chat.id keybd = keyboards2 elif self.botType == "sec": messId = message.from_user.id keybd = keyboards else: messId = "" keybd = "" if entry: print("su1") self._bot.send_message(messId, texts['choose_good_msg'], reply_markup=keybd.set_keyboard( texts, goods.keys(), back_btn=True)) else: print("su2") if self.botType == "fi": messText = message.text elif self.botType == "sec": messText = message.data else: messText = "" if messText == texts['back_btn']: self._go_to_state(message, self.cities_state) else: good = goods.get(messText) if good: user.good = good user.clicked_goods.append(good) user.save() self._go_to_state(message, self.districts_state) else: self._bot.send_message(messId, texts['use_buttons_msg'], reply_markup=keybd.set_keyboard( texts, goods.keys(), back_btn=True))
def create_dub(self, bot_id, bot_2): try: telebot.TeleBot(bot_2).get_me() except Exception: return 'ERROR, go back' bot_2 = loads( BotProfile.objects(token=bot_2).first().to_json())['_id']['$oid'] text = Texts.objects(bot_id=bot_id).first() if not (text is None): text_dict = loads(text.to_json()) dub_text = {} for key in text_dict: if key != '_id': dub_text.update({key: text_dict[key]}) dub_text['bot_id'] = bot_2 new_text = Texts(**dub_text) new_text.save() cities = City.objects(bot_id=bot_id) if cities is not None: for city in cities: if not (city is None): city_dict = loads(city.to_json()) dub_city = {} for key in city_dict: if key != '_id': dub_city.update({key: city_dict[key]}) dub_city['bot_id'] = bot_2 new_city = City(**dub_city) new_city.save() goods = Good.objects(city_id=city.id.binary.hex()) for good in goods: if good is not None: Good(name=good.name, city_id=new_city.id.binary.hex(), price=good.price, description=good.description, photo=good.photo, districts=good.districts).save() payment = Payment.objects(bot_id=bot_id).first() if not (payment is None): payment_dict = loads(payment.to_json()) dub_payment = {} for key in payment_dict: if key != '_id': dub_payment.update({key: payment_dict[key]}) dub_payment['bot_id'] = bot_2 new_payment = Payment(**dub_payment) new_payment.save() return str(bot_2)
def create_good_record(name, description, price): good = Good() good.name = name good.description = description good.price = price return good
logging.basicConfig(format='%(asctime)s %(levelname)-6s %(message)s', filename="logfile.log", level=logging.INFO) with app.app_context(): if not database_exists(db.engine.url): logging.info('Database "cursor_sqlalchemy_db" does not exists') create_database(db.engine.url) logging.info('Data "cursor_sqlalchemy_db" base created') db.create_all() logging.info('Database "cursor_sqlalchemy_db" exists') with app.app_context(): users = get_users() for user in users: db.session.add(User(**user)) db.session.commit() logging.info('Data written to table "users" in db "cursor_sqlalchemy_db" succesfuly') with app.app_context(): stores = get_stores() for store in stores: db.session.add(Store(**store)) db.session.commit() logging.info('Data written to table "stores" in db "cursor_sqlalchemy_db" succesfuly') with app.app_context(): goods = get_goods() for good in goods: db.session.add(Good(**good)) db.session.commit() logging.info('Data written to table "goods" in db "cursor_sqlalchemy_db" succesfuly')