def seed_db(): from models.Item import Item from models.User import User from models.Order import Order from models.OrderShipping import OrderShipping from main import bcrypt from faker import Faker import random faker = Faker() for i in range(3): user = User() user.email = f"test{i}@test.com" user.password = bcrypt.generate_password_hash("123456").decode("utf-8") db.session.add(user) admin = User() admin.email = "*****@*****.**" admin.password = bcrypt.generate_password_hash("123456").decode("utf-8") admin.admin = True db.session.add(admin) db.session.commit() for i in range(10): item = Item() item.name = faker.currency_name() item.description = faker.paragraph(nb_sentences=3) item.price = 53.25 db.session.add(item) db.session.commit() ordershipping = [] for i in range(5): shipping = OrderShipping() shipping.first_name = faker.first_name() shipping.last_name = faker.last_name() shipping.address = faker.street_address() shipping.state = faker.city() shipping.zip_code = faker.postcode() db.session.add(shipping) ordershipping.append(shipping) db.session.commit() orders = [] for i in range(5): order = Order() order.shipping_id = random.choice(ordershipping).id db.session.add(order) orders.append(order) db.session.commit() print("Tables seeded.")
def fetch(item_id, incoming): requested_item = Item(item_id=item_id) response = {'exists' : False, 'status': 'failure'} if requested_item._exists == True: response['exists'] = True response['status'] = 'success' response['data'] = requested_item.export() return response
def seed_database(): # List with three items seeded_list_items = List("Example list #0") seeded_list_items.add_item(Item("Example content #0", 0)) seeded_list_items.add_item(Item("Example content #1", 1)) seeded_list_items.add_item(Item("Example content #2", 2)) db.session.add(seeded_list_items) # List without items seeded_list_empty = List("Example list #1") db.session.add(seeded_list_empty) # Commit the changes to the database db.session.commit() print("Database seeded")
def delete_item(current_user, item_id): if current_user.admin is False: return jsonify( {"message": "You are not authorised to perform this function"}) # r = request.json item = Item.get_item_by_id(id=item_id) if not item: return jsonify({"message": "Item does not exist"}) try: Item.delete_item(id=item_id) return jsonify({"message": "{} deleted".format(item["name"])}) except: return jsonify( {"message": "An error occurred, Item could not be deleted"})
def update_item(current_user, item_id): if current_user.admin is False: return jsonify( {"message": "You are not authorised to perform this function"}) item = Item.get_item_by_id(id=item_id) if not item: return jsonify({"message": "Item does not exist"}) try: r = request.json Item.update_item(id=item_id, data=r) return jsonify({"message": "Item updated"}) except: return jsonify( {"message": "An error occurred, Item could not be updated"})
def convert_resource(itemWithNeededResource: Item, surplusResource, item: Item): """ Convert a surplus resource into a needed resource. Args: itemWithNeededResource (Item): surplusResource (): item (): """ value = surplusResource.average() / itemWithNeededResource.resource( surplusResource.name).average() item.add_to_resource(itemWithNeededResource.name, value) surplusResource.min = 0 surplusResource.max = None
def create_item(current_user): if current_user.admin is False: return jsonify( {"message": "You are not authorised to perform this function"}) try: r = request.json item = Item(name=r['name'], description=r['description'], type=r['type'], price=r['price'], quantity=r['quantity']) item.save_to_mongo() return jsonify({"message": "{} Created".format(item.name)}) except: return jsonify( {"message": "An error occurred, Item could not be created"})
def __init__(self): self.storeItems = [] self.itemPrices = [] c.execute('SELECT name, price FROM Inventory') self.storeItems = c.fetchall() for name, price in self.storeItems: self.itemPrices.append(Item(name, price))
def rain(incoming): response = {} filters = {} all_item_ids = enumerate_table('items', filters) if len(all_item_ids) == 0: response['status'] = 'failed' response['message'] = 'No relevant data found!' else: response['status'] = 'success' response['data'] = [] for an_item_id in all_item_ids: an_item = Item(item_id=an_item_id) response['data'].append(deepcopy(an_item.export())) return response
def create_warrior_from_json2(data): # loads() only creates a data object (dict - no methods) # In complex objects you will get a dict of dicts warriorData = Item(**json.loads(data)) # Build out the objects from the JSON data object. resources = [] for resource in warriorData.resources: resources.append(Resource(resource['name'], resource['count'])) # Instanciate the top level using the return Item(warriorData.name, resources)
def dispatch_items_randomly(self, level): """ Function to dispatch randomly each items :param level: :return: """ for item in self.list: item.position = Item.define_random_position(item, level)
def generateRandomStoreItems(self, amt): storedItemCounter = 0 while (storedItemCounter < amt): itemName = self.itemNames[rnd(0, len(self.itemNames) - 1)] itemPrice = rnd(10, 100) newItem = Item(name=itemName, price=itemPrice) self.storeItems.append(newItem) storedItemCounter = storedItemCounter + 1
def create_warrior(): resources = [] resources.append(Resource("Water", 100)) resources.append(Resource("Metal", 10)) resources.append(Resource("Bone", 25)) result = Item("He-Man", resources) return result
def item_create(): # create new item item_fields = item_schema.load(request.json) admin = User.query.get(get_jwt_identity()) if not admin.admin: return abort(401, description="Invalid user action.") new_item = Item() new_item.name = item_fields["name"] new_item.description = item_fields["description"] new_item.price = round(item_fields["price"], 2) db.session.add(new_item) db.session.commit() return jsonify(item_schema.dump(new_item))
def get_by_keyword(keyword): config = get_config() request_url = config['api'][ 'product_url'] + '/search?query=' + keyword + '&' + config['api'][ 'api_version'] + '&' + config['api']['product_key'] response = requests.get(request_url) item_sku = int(response.json()['results'][0]['sku']) item_name = keyword return Item(item_sku, item_name)
def buy(item_id): try: item = Item.get_item_by_id(id=item_id) if not item: return jsonify({"message": "Item does not exist"}) if request.data and request.json["quantity"]: quantity = int(request.json["quantity"]) else: quantity = 1 item["quantity"] -= quantity Item.update_item(id=item_id, data=item) return jsonify({ "message": "{} unit(s) of {} Purchased".format(quantity, item["name"]) }) except: return jsonify( {"message": "An error occurred, Item could not be purchased"})
def readStoreItems(self, storeFileName): try: root = et.parse(storeFileName).getroot() for child in root.findall("product"): self.storeItems.append( Item( child.find("name").text, float(child.find("price").text))) except IOError: print("Store File Not Exists... Generating Random Store") self.generateRandomStoreItems(8)
def add_list_element(list_id=None): if list_id is None: abort(404) todo_list = List.query.filter_by(id=list_id).first() if todo_list is None: abort(404) content = request.form['content'] content = content.strip() if content == '': flash("There are errors or missing fields on the form", "error") return redirect(url_for('show_list', list_id=list_id)) order = 0 if len(todo_list.items) > 0: order = max([x.order for x in todo_list.items]) + 1 item = Item(content, order) todo_list.add_item(item) db.session.commit() return redirect(url_for('show_list', list_id=list_id))
def __init__(self, type, position, name, status, is_allowed_to_move, icon, items_list): """ :param type: Type of the persona. Type string :param position: current position of the persona. Type is tuple :param name: name of the persona. Type is string :param status: Status can the following value 'alive', bad guy', 'dead', 'winner'. Type is string :param is_allowed_to_move: persona is allowed to move. Type is boolean :param icon: path to the picture to get the persona icon. Type is string :param items_list: list of items to retrieve. Type is dictionary """ self.type = type self.position = position self.name = name self.status = status self.is_allowed_to_move = is_allowed_to_move self.icon = icon self.grabbedItems = items_list self.has_sering = Item('sering', 'resources//pictures//seringue.png')
def get_item_by_id(self, id, helper): row = self.item_df.loc[self.item_df['item'] == id] item = Item(row, helper) return item
from models.Item import Item inventory = [ Item('tshirt', 7.25, 12), Item('pants', 9.44, 6), Item('shorts', 8.33, 10), Item('longsleeve', 6.22, 6) ]
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters passwd = Utils.required(self, 'passwd') uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') # check password if self.error == '' and passwd != config.testing['passwd']: self.error = 'passwd is incorrect.' start_time = time.time() # start count # if error, skip this if self.error == '': # query player state for given uuid players = Player.all().filter('uuid =', uuid).ancestor( db.Key.from_path('Player', config.db['playerdb_name'])).fetch(1) didDelete = False # we have not delete anything yet for player in players: # we might have duplicate data, just delete them all # query scores for this player and delete them all scores = Score.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Score', config.db['scoredb_name'])) for score in scores: score.delete() # query items for this player and delete them all items = Item.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Item', config.db['itemdb_name'])) for item in items: item.delete() # query records for this player and delete them all records = Record.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Record', config.db['recorddb_name'])) for record in records: record.delete() # query buildings for this player and delete them all buildings = Building.all().filter( 'uuid =', player.uuid).ancestor( db.Key.from_path('Building', config.db['buildingdb_name'])) for building in buildings: building.delete() cars = Car.all().filter('uuid =', player.uuid).ancestor( db.Key.from_path('Car', config.db['cardb_name'])) for car in cars: car.delete() # delete all this user's challenge Challenge.DeleteByUserId(self, player.uuid) # and finally, delete this player player.delete() didDelete = True # compose result if didDelete == True: self.respn = '"' + uuid + ' was deleted successfully."' else: self.error = uuid + ' does not exist in Database.' # calculate time taken and return the result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') itid = Utils.required(self, 'itid') data = self.request.get('data') start_time = time.time() # start count # set variables default item = None player = None storeitem = None # if error, skip this if self.error == '': player = Player.getplayer_as_obj(self, uuid) if self.error == '' and player is not None and guid != '': if guid != player.state_obj['guid']: player = None self.error = config.error_message['dup_login'] # if error or player is none, skip this if self.error == '' and player is not None: storeitem = Data.getstoreitem_as_obj(self, config.softstore['version']) # if storeitem is not none if storeitem is not None: try: # try to get item with id=itid item = storeitem[str(itid)] except KeyError: # if item with that id/key doesn't exist storeitem = None # throw it to None self.error = 'given item id doesn\'t exist!' # and inform user that # if error or storeitem is none, skip to the end // return if self.error == '' and storeitem is not None: myitems = Item.getitems( self, uuid) # get all items user owned from Item model class helper add = True # this variable indicates is user eligible to purchase if item['dependencies'] != '': # check if the item has dependencies add = False # set item to unavailable first, we will change it available after we check all its dependencies self.respn = '{"warning":"you\'re not qualified to purchase this item!"}' # also inform user some good reason, not just die. this will eliminate after we check all its dependencies anyway depc = 0 # A variable stand from dependencies counter deps = item['dependencies'].replace(' ', '').split( ',' ) # and eliminate space from dependencies and split by commas ',' for dep in deps: # run through all dependencies of the item for myitem in myitems: # run through all user's list of items if myitem.itid == dep: # check if user have dependency item depc += 1 # increment counter if depc >= len( deps ): # alter all counting, if counter is more than all dependencies, it probably means user has all dependencies add = True # and then yeah!, we turn item to available if add is True and item[ 'maximum'] != '': # check if the item has maximum limitation depc = 0 # set counter to 0 again, we will use for next logic for myitem in myitems: # run through myitems if myitem.itid == item[ 'id']: # check if user has same item in hand depc += 1 # increment counter if int(depc) >= int( item['maximum'] ): # if counter is more than or equal the item's maximum add = False # that means user has reached the maximum, and should not available for him any more self.respn = '{"warning":"you\'ve reached maximum of this item!"}' # and yes! should inform him that # now if user is eligible to purchase this item, then do it if add is True: if player.state_obj['gold'] >= item[ 'gold']: # check if user has gold enough to purchase player.state_obj['gold'] -= item[ 'gold'] # deduct gold from user by item price itemobj = Item(parent=db.Key.from_path( 'Item', config.db['itemdb_name'] )) # now create an item and reward/deliver to user itemobj.itid = item[ 'id'] # assign an itemid.. to identiy item type itemobj.inid = Utils.genitemid( self) # generate and assign unique inventory id, itemobj.uuid = player.uuid # assign uuid, indicate who is the owner of this item itemobj.userData = '' if storeitem[ itemobj.itid]['type'] == Item.ItemType.BUILDING: itemobj.userData = data itemobj.status = 'pending' # assign status, probably this is pending itemobj.timestamp = int(start_time) + int( item['time'] ) # calculate time to deliver or reward, while status pending, user can't use it if itemobj.put(): # put it into database if player.state_obj[ 'token'] != '': # check if user already has token apns.add( player.state_obj['token'], storeitem[str(itemobj.itid)]['title'] + ' has been delivered to you!', itemobj.timestamp ) # if so, set a push notofication to be sent if Player.setplayer_as_obj( self, player ): # put player state back into the database self.respn = '{' self.respn += '"' + itemobj.inid + '":{' self.respn += '"itid":"' + itemobj.itid + '",' self.respn += '"type":"' + storeitem[ itemobj.itid]['type'] + '",' self.respn += '"title":"' + storeitem[ itemobj.itid]['title'] + '",' self.respn += '"desc":"' + storeitem[ itemobj.itid]['description'] + '",' self.respn += '"imgurl":"' + storeitem[ itemobj.itid]['image_url_sd'] + '",' self.respn += '"data":"' + itemobj.userData + '",' self.respn += '"status":"' + itemobj.status + '",' self.respn += '"timestamp":' + str( itemobj.timestamp) self.respn += '},' self.respn = self.respn.rstrip(',') + '}' """ myitems = Item.getspecificitems(self, uuid, item['id']) # get user items (only same type of purchased item), we want to list them all and return if myitems is not None: # make sure we have everything ready self.respn = '{' for myitem in myitems: # run through myitems if storeitem[str(myitem.itid)]: # check if item does exist save = False # this variable indicates should we update user's item data if myitem.status == 'pending' and start_time >= myitem.timestamp: # if item status is pending and it is time to reward myitem.status = 'reward' # then reward it, by changing item status myitem.timestamp = int(start_time) + int(storeitem[str(myitem.itid)]['produce_time']) # calculate next time to produce resource save = True # cause we change item status, so we need to update database elif myitem.status == 'reward': # if status is reward, myitem.status = 'rewarded' # we should change it to rewarded, so system won't duplicate reward save = True # and again, save it any time we change something # now, compose list of same type of purchased item self.respn += '"' + myitem.inid + '":{' self.respn += '"itid" : "' + myitem.itid + '",' self.respn += '"type" : "' + storeitem[myitem.itid]['type'] + '",' self.respn += '"title" : "' + storeitem[myitem.itid]['title'] + '",' self.respn += '"desc" : "' + storeitem[myitem.itid]['description'] + '",' self.respn += '"imgurl" : "' + storeitem[myitem.itid]['image_url_sd'] + '",' self.respn += '"data" : "' + myitem.userData + '",' self.respn += '"status" : "' + myitem.status + '",' self.respn += '"timestamp" : ' + str(myitem.timestamp) self.respn += '},' if save is True: # now we should know, should we update item data myitem.put() # if yes, please do so self.respn = self.respn.rstrip(',') + '}' else: # if we can't get my item, self.respn = '{}' # then return emtpy object """ self.respn = '{"uuid":"' + player.uuid + '", "state":' + player.state + ', "items":' + self.respn + '}' # compose final result else: # if user has not enough gold self.respn = '{"warning":"not enough gold!"}' # then tell him # calculate time taken and return result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))
def create_warrior_from_json(data: str): # Constructs an Item() to use the method/hook return Item().deserialize(data)
def view_items(): items = Item.get_items() if not items: return jsonify({"message": "No items found"}) return jsonify({"items": items})
def view_one_item(item_id): item = Item.get_item_by_id(id=item_id) if not item: return jsonify({"message": "Item does not exist"}) return jsonify(item)
def get_candidate_items(df): # generate item list of all candidate items. More constraints can be added when the dataset becomes bigger items = [] for index, row in df.iterrows(): items.append(Item(row, helper)) return items
def get(self): Utils.reset(self) # reset/clean standard variables # validate and assign parameters uuid = Utils.required(self, 'uuid') guid = self.request.get('guid') start_time = time.time() # start count # if error, skip this if self.error == '': player = Player.getplayer_as_obj( self, uuid) # get player state from Player model class helper if self.error == '' and player is not None and guid != '': if guid != player.state_obj['guid']: player = None self.error = config.error_message['dup_login'] # if error or player is none, skip this if self.error == '' and player is not None: storeitem = Data.getstoreitem_as_arr( self) # get store item from Storeitem model class helper # if error or storeitem is none, skip this if self.error == '' and storeitem is not None: myitems = Item.getitems(self, uuid) # get list of items owned # set result default self.respn = '[' reason = '' for item in storeitem: # run through each item in store items add = True # A variable indicates that is it available for user if item['dependencies'] != '': # if item has dependencies add = False # set item to unavailable first, we will change it available after we check all its dependencies reason = 'You need the following items first: ' + item[ 'dependencies'] # also inform user some good reason, not just die. this will eliminate after we check all its dependencies anyway depc = 0 # A variable stand from dependencies counter deps = item['dependencies'].replace(' ', '').split( ',' ) # and eliminate space from dependencies and split by commas ',' for dep in deps: # run through all dependences of the item for myitem in myitems: # run through all user's list of items if myitem.itid == dep: # check if user have dependency item depc = depc + 1 # increment counter if depc >= len( deps ): # alter all counting, if counter is more than all dependecies, it probably means user has all dependencies add = True # and then yeah!, we turn item to available if add == True and item[ 'maximum'] != '': # check if the item has maximum limitation depc = 0 # set counter to 0 again, we will use for next logic for myitem in myitems: # run through myitems if myitem.itid == item[ 'id']: # check if user has same item in hand depc = depc + 1 # increment counter if int(depc) >= int( item['maximum'] ): # if counter is more than or equal the item's maximum add = False # that means user has reached the maximum, and should not available for him any more reason = 'You\'ve reached the maximum of this item!' # and yes! should inform him that # hard compose item list self.respn += '{' self.respn += ' "itid":"' + item['id'] + '",' self.respn += ' "type":"' + item['type'] + '",' self.respn += ' "title":"' + item['title'] + '",' self.respn += ' "desc":"' + item['description'] + '",' self.respn += ' "depend":"' + item['dependencies'] + '",' self.respn += ' "imgurl":"' + item['image_url_sd'] + '",' self.respn += ' "gold":' + str(item['gold']) + ',' self.respn += ' "time":' + str(item['time']) + ',' self.respn += ' "platinum":' + str(item['platinum']) + ',' if add == True: self.respn += ' "lock":""' else: self.respn += ' "lock":"' + reason + '"' self.respn += '},' self.respn = self.respn.rstrip(',') + ']' # calculate time taken and return result time_taken = time.time() - start_time self.response.headers['Content-Type'] = 'text/html' self.response.write(Utils.RESTreturn(self, time_taken))