def init_db(): db.create_all() db.session.commit() admin_group = models.UserGroup('admin') db.session.add(admin_group) db.session.commit() first_user = models.User('*****@*****.**', 'password') first_user.activated = True db.session.add(first_user) db.session.commit() admin_membership = models.UserGroupMembership(first_user, admin_group) db.session.add(admin_membership) db.session.commit() second_user = models.User('*****@*****.**', 'password') second_user.activated = True db.session.add(second_user) db.session.commit() third_user = models.User('*****@*****.**', 'password') third_user.activated = True db.session.add(third_user) db.session.commit() sprite = models.Item('Sprite', 0.60) db.session.add(sprite) db.session.commit() kitkat = models.Item('KitKat', 0.40) db.session.add(kitkat) db.session.commit() twix = models.Item('Twix', 0.75) db.session.add(twix) db.session.commit() purchase = models.Purchase(second_user, kitkat) db.session.add(purchase) db.session.commit() second_purchase = models.Purchase(second_user, sprite) db.session.add(second_purchase) db.session.commit() third_purchase = models.Purchase(third_user, twix) db.session.add(third_purchase) db.session.commit() db.session.close()
def json_to_item(obj, parent_id=None): kwargs = { 'onedrive_id': obj['id'], 'name': obj['name'], 'parent_id': parent_id, 'original_path': None, } if parent_id == 'root': kwargs['parent_id'] = None if 'folder' in obj: kwargs['is_folder'] = True elif 'file' in obj: kwargs['is_folder'] = False kwargs['size'] = obj['size'] try: kwargs['hash'] = obj['file']['hashes']['quickXorHash'] except KeyError: # File size == 0 usually does not have hash kwargs['hash'] = None kwargs['mdate'] = date_from_onedrive( obj['fileSystemInfo']['lastModifiedDateTime']) else: return None return models.Item(**kwargs)
def load_one_item(owner): item_test_data = items_data_list[0] it = models.Item.query( models.Item.place_name == item_test_data[ITEM_NAME]).get() if it: return it else: new_it = models.Item() cat = models.Category.get_by_id(item_test_data[ITEM_CATEGORY]) if not cat: cat = models.Category(id=item_test_data[ITEM_CATEGORY]).put() new_it.category = cat new_it.place_name = item_test_data[ITEM_NAME] home = geo.LatLng(lat=51.57, lng=-0.13) lat_long = geo.geoCodeAddress(item_test_data[1], home) new_it.lat = lat_long['lat'] new_it.lng = lat_long['lng'] new_it.address = item_test_data[ITEM_ADDRESS] new_it.owner = owner.key.integer_id() # new_it.descr = "blah" new_it.geo_hash = geohash.encode(new_it.lat, new_it.lng) img = models.DBImage() detail = geo.getPlaceDetailFromGoogle(new_it) img.remoteURL = detail['photo'] img.put() new_it.photo = img new_it.telephone = detail['telephone'] new_it.put() return new_it
def add(request): ''' takes { title: string, //(optional) } returns { id: name: ... } ''' if not request.user.get_profile().capability('canAddItems'): response = json_response(status=403, text='permissino denied') else: data = json.loads(request.POST['data']) data['title'] = data.get('title', 'Untitled') i = models.Item() i.data['title'] = data['title'] i.user = request.user p = i.save() if p: p.wait() else: i.make_poster(True) response = json_response(status=200, text='created') response['data'] = i.get_json() return render_to_json_response(response)
def generateItems(): my_stores = list(db.GqlQuery("SELECT * From Store")) for store in my_stores: store_id[store.name] = store._id db.delete(db.GqlQuery('SELECT * From Item')) f = open('parse/shop_items.csv', 'rb') with f as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='"') p = 0 for row in spamreader: if row[0] == 'Name': continue for i in range(len(row)): row[i] = row[i].decode('cp1251') cur_item = models.Item(name=row[0], subcategory=row[1], category=row[2], image="/static" + row[3], store=store_id[row[4]], price=int(row[5]), description=row[6], weight=row[7], _id=p) p += 1 cur_item.put()
def add(self, product, unit_price, quantity=1, override_quantity=False, options=None): try: item = models.Item.objects.get( cart=self.cart, product=product, ) except models.Item.DoesNotExist: item = models.Item() item.cart = self.cart item.product = product item.unit_price = unit_price item.quantity = quantity item.save() if options: item.options = options else: #ItemAlreadyExists if options: item.clear_options() item.options = options item.unit_price = unit_price item.quantity = quantity if override_quantity else item.quantity + int( quantity) item.save()
def item_form(category=None): """ Creates the form for adding new items""" if 'username' not in login_session: return Page( title="Unauthorized", contentmain="You are not authorized to see this page.").render() if request.method == 'POST': new_item = models.Item(name=request.form['name'], description=request.form['description'], user_id=login_session['user_id'], category_id=int(category)) session.add(new_item) session.commit() return Page( title='Success', contentmain=flask.render_template('success.html')).render() else: category = session.query(models.Category).get(category) page = Page( title="Create a new category", description= "This page allows the creation of new categories to the application", contentmain=flask.render_template('form_item.html', category=category)) return flask.render_template('base.html', page=page)
async def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): db_item = models.Item(**item.dict(), owner_id=user_id) await db.add(db_item) await db.commit() await db.refresh(db_item) return db_item
def create_folder(self, parent_id, name): create_url = '{}items/{}/children'.format(DRIVE_URL, parent_id) create_obj = { 'name': name, 'folder': {}, '@microsoft.graph.conflictBehavior': 'rename' } r = self.oauth.post(create_url, json=create_obj) if r.status_code == 429: logger.debug('Sleeping during folder creation') time.sleep(float(r.headers['Retry-After'])) return self.create_folder(parent_id, name) if r.status_code != 201: logger.error( 'Could not create folder %s. Status=%d, response=%s', name, r.status_code, r.text) return None item = r.json() if item['name'] != name: logger.info('Renamed to avoid conflict', name, item['name']) return models.Item( item['id'], item['name'], None, True, True, parent_id=parent_id)
def create_user_item(db: Session, item: schemas.ItemCreate, user_id: int): """Create user item""" db_item = models.Item(**item.dict(), owner_id=user_id) db.add(db_item) db.commit() db.refresh(db_item) return db_item
def create_product(self, product, quantity): item = models.Item() item.cart = self.cart item.product = product['product'] item.unit_price = product['product'].getFinalPrice() item.quantity = quantity item.save() return item
def test_basket_show(capsys): basket = models.Basket() basket.add(models.Item("Apple", 0.20), 2) basket.calculate_price() basket.show() out, err = capsys.readouterr() assert "Apple" in out assert f"{0.20 * 2:.2f}£" in out
def open_data(self): """Opens the data from self.filename""" """Reads in data into the internal data structure""" with open(self.filename, 'r') as files: for line in files: values = line.split(',') item = models.Item(values[0], values[1], values[2], values[3], values[4], values[5]) self.data.append(item)
def read_initial_data(self, filename): """Reads in data into the internal data structure""" with open(filename, 'r') as files: for line in files: line = string.lower(line) # Return a copy of s, but with upper case letters converted to lower case. Convenient for search values = line.split(',') item = models.Item(values[0], values[1], values[2], values[3], values[4], values[5]) self.data.append(item)
def create_category_items_by_id(db: Session, item: schemas.ItemCreate, category_id): db_item = models.Item(name=item.name, category_id=category_id, price=item.price) db.add(db_item) db.commit() db.refresh(db_item) return db_item
def create_form(db: Session, form: schemas.FormCreate): # TODO: Actually hash password. fake_hashed_password = form.password + "notreallyhashed" db_form = models.Form(hashed_password=fake_hashed_password) db.add(db_form) for item in form.items: db_form.items.append(models.Item(text=item.text)) db.commit() db.refresh(db_form) return db_form
def create_item(db: Session, item: schemas.ItemCreate): # convert schema object from rest api to db model object db_item = models.Item(name=item.name, price=item.price, is_offer=item.is_offer) # add in db cache and force insert db.add(db_item) db.commit() # retreive object from db (to read at least generated id) db.refresh(db_item) return db_item
async def adding_count(message: types.Message, state: FSMContext): try: async with state.proxy() as data: data['count'] = int(message.text) item = models.Item(name = data['name'], buy_sum = data['buy_sum'], count = data['count'], current_sum = data['current']) item.save() await state.finish() await bot.send_message(message.from_user.id, 'Предмет успешно создан\nName: {}\nЦена покупки: {} руб.\nТекущая цена: {} руб.*\nКол-во: {}\nПрофит: {}%\n\n*С учётом комиссии ТП 13%'.format(data['name'], str(data['buy_sum']), str(round(data['current']*0.87, 2)), str(data['count']), str(round((round(data['current']*0.87, 2)/data['buy_sum'] - 1) * 100, 2))), reply_markup = add_again) except Exception as e: print(e) await bot.send_message(message.from_user.id, 'Введите кол-во купленных предметов ещё раз')
def add_item(): form = ItemForm() if form.validate_on_submit(): title = form.title.data description = form.description.data price = form.price.data item = models.Item(title=title, description=description, price=price) db.session.add(item) db.session.commit() flash("Stored '{}'".format(description)) return redirect(url_for('index')) return render_template('add_item.html', form=form)
def parseJson(json_file): with open(json_file, 'r') as f: items = loads(f.read())['Items'] # creates a Python dictionary of Items for the supplied json file for item in items: """ TODO: traverse the items dictionary to extract information from the given `json_file' and generate the necessary .dat files to generate the SQL tables based on your relation design """ # create item object models.Item(item)
async def add_urldata(url: str = None, db: Session = Depends(get_db)): try: for entity in set(get_entities(get_text(url))): item = models.Item() item.url = url item.entity = entity item.text = str(get_entity_text(get_text(item.url), entity)) db.add(item) db.commit() finally: db.close() return {"message": "Successfully added data into the database"}
def unit_test_item(): obj = items["Knife"] itm = models.Item(obj["type"], obj["integrity"], obj["description"], obj["name"]) assert itm.kind() == obj["type"] assert itm.name() == obj["name"] assert itm.loseIntegrity() == True assert itm.integrity() == obj["integrity"] - 1 assert itm.loseIntegrity() == True assert itm.loseIntegrity() == True assert itm.loseIntegrity() == False assert itm.loseIntegrity() == 0 assert itm.description == obj["description"] obj = items["Key"] itm = models.Item(obj["type"], obj["integrity"], obj["description"], obj["name"]) assert itm.kind() == obj["type"] assert itm.name() == obj["name"] assert itm.loseIntegrity() == True assert itm.integrity() == obj["integrity"] - 1 assert itm.loseIntegrity() == True assert itm.loseIntegrity() == True assert itm.integrity() == 9996 assert itm.description == obj["description"] obj = items["Banana"] itm = models.Item(obj["type"], obj["integrity"], obj["description"], obj["name"]) assert itm.kind() == obj["type"] assert itm.name() == obj["name"] assert itm.loseIntegrity() == True assert itm.integrity() == obj["integrity"] - 1 assert itm.loseIntegrity() == False assert itm.description == obj["description"] obj = items["Treasure"] itm = models.Item(obj["type"], obj["integrity"], obj["description"], obj["name"]) assert itm.kind() == obj["type"] assert itm.name() == obj["name"] assert itm.loseIntegrity() == True assert itm.integrity() == obj["integrity"] - 1 assert itm.description == obj["description"]
def add(self, product, unit_price, quantity=1): try: item = models.Item.objects.get( cart=self.cart, product=product, ) except models.Item.DoesNotExist: item = models.Item() item.cart = self.cart item.product = product item.unit_price = unit_price item.quantity = quantity item.save()
def add(self, product): item = models.Item() item.cart = self.cart item.type = product[u'type'] item.sheet_type = product[u'sheet_type'] item.texture = product[u'texture'] item.square = product[u'square'] item.coating_main = product[u'coating_main'] item.coating_additional = product[u'coating_additional'] item.stained = product[u'stained'] item.save()
def getById(self, id): self.connect() c = self.conn.cursor() c.execute('SELECT * FROM Item WHERE Id = ?', (id, )) row = c.fetchone() item = models.Item() item.id = row[0] item.name = row[1] item.price = row[2] return item
def basket(): basket_ = models.Basket() basket_.add( models.Item( "Apple", 0.20, models.SpecialOffer( "Buy One Get One Free on Apples", 2 ) ), 4, ) return basket_
def add(self, product, unit_price, quantity=1): try: item = models.Item.objects.get(cart=self.cart, product=product, ) except models.Item.DoesNotExist: item = models.Item() item.cart = self.cart item.product = product item.unit_price = unit_price item.net_price = Decimal(unit_price / Decimal(1.2)).quantize(Decimal('.01'), rounding=ROUND_05UP) item.tax = item.unit_price - item.net_price item.quantity = quantity item.save() else: item.quantity += quantity item.save()
def execute(self): try: try: item = models.Item.get_by_id(self.item_name) if item.value != self.item_value: models.ValueCount.decrement(item.value) models.ValueCount.increment(self.item_value) item.value = self.item_value item.put() except AttributeError: item = models.Item(value=self.item_value, id=self.item_name) models.ValueCount.increment(self.item_value) item.put() except BadRequestError: no_op()
def add(self, product, unit_price, quantity): try: item = models.Item.objects.get( cart=self.cart, product=product, ) except models.Item.DoesNotExist: item = models.Item() item.cart = self.cart item.product = product item.unit_price = unit_price item.quantity = quantity item.save() else: #ItemAlreadyExists self.update(product, product.price, item.quantity + 1)
async def create_item(item: schemas.items.ItemCreate, user_id: int, db: orm.Session) -> schemas.items.ItemOwners: # Add item to item table db_item = models.Item(title=item.title, description=item.description) db.add(db_item) db.commit() db.refresh(db_item) # Add item owner db_owner = models.Owner(user_id=user_id, item_id=db_item.id) db.add(db_owner) db.commit() db.refresh(db_owner) return schemas.items.ItemOwners.from_orm(db_owner)