示例#1
0
文件: cli.py 项目: studiosi/todoapp
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 __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))
示例#3
0
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.")
示例#4
0
 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
示例#5
0
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 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)
示例#7
0
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
示例#8
0
    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)
示例#9
0
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"})
示例#10
0
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))
示例#11
0
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))
示例#12
0
    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')
示例#13
0
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
示例#14
0
def create_warrior_from_json(data: str):
    # Constructs an Item() to use the method/hook
    return Item().deserialize(data)
示例#15
0
    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))
示例#16
0
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)
]

示例#17
0
 def get_item_by_id(self, id, helper):
     row = self.item_df.loc[self.item_df['item'] == id]
     item = Item(row, helper)
     return item