def delete(self,item_id): try: Item.query.filter_by(id=item_id).delete() Item.update_all() return '',204 except: return '',500
def post(self): try: pd = json.loads(request.get_data()) for url in pd: i = Item() i.from_url(url) except: return "",500
def post(self): try: pd = json.loads(request.get_data()) for asin in pd: i = Item() i.from_asin(asin) except: return "",500
def post(self): title = request.form.get('title') description = request.form.get('description') fulfilled = False bucketlist_id = request.form.get('bucketlist_id') Item.create( title=title, bucketlist=bucketlist_id, description=description, fulfilled=fulfilled ) res = {'Status': 'OK'} return jsonify(res)
def get(self, item_id): if item_id is not None: item = Item.find_item_by_id(bson_obj_id(item_id)) return bson_to_json(item) params = {} for k, v in request.args.items(): if v: Item.add_param(params, k, v) cursor = Item._find_many(params) items = [bson_to_json(item) for item in cursor] return json.dumps(items)
def item_add(): form = ItemAddForm() if form.validate_on_submit(): item = Item() item.set_name(form.name.data) item.set_unit(form.unit.data) item.set_quantity(form.quantity.data) item.set_room(form.room.data) db.session.add(item) db.session.commit() flash('Item cadastrado com sucesso') return redirect(url_for('item_list')) return render_template('item/add.html', title='Cadastrar item', form=form)
def post(list_id): """Adds an item to a shoppinglist""" user_id, message, status, status_code, _ = parse_auth_header(request) if user_id is None: return jsonify({ "status": status, "message": message }), status_code shoppinglist, message, status, status_code = get_shoppinglist( user_id, list_id) if shoppinglist: # form fields name = request.form.get("name") price = request.form.get("price") quantity = request.form.get("quantity") status = request.form.get("status") has_been_bought = True if status and status.strip().title() == "True" else False name = name.strip() if name else "" price = price.strip() if price else "" quantity = quantity.strip() if quantity else "" if name and price and quantity: name = name.lower() name_already_exists = Item.query.filter( Item.shoppinglist_id == list_id).filter(Item.name == name).all() if name_already_exists: return jsonify({ "status": "failure", "message": f"an item with name '{name}' already exists" }), 409 item = Item(list_id, name, quantity, price, status=has_been_bought) item.save() return jsonify({ "status": "success", "message": f"'{item.name}' has been added" }), 201 return jsonify({ "status": "failure", "message": "'name', 'price' and 'quantity' of an item must be" " specified whereas 'status' is optional" }), 400 return jsonify({ "status": status, "message": message }), status_code
def test_item(self): # set up Vendor.generate_fake(10) Item.generate_fake(10) statisitc.init_statistic() self.add_user() self.redis.delete('INDEX_ITEMS:ITEMS') # item list response = self.client.get(url_for('item.item_list')) self.assert_ok_html(response) response = self.client.get(url_for('main.index')) self.assert_ok_html(response)
def setUp(self): super().setUp() category = Category(name='test_category') item = Item(name='test_item') item.category = category record_1 = Record(start=datetime(2019, 1, 10, 6, 0, 0), finish=datetime(2019, 1, 10, 7, 0, 0), remark='test_record_1') record_2 = Record(start=datetime(2019, 1, 11, 6, 0, 0), finish=datetime(2019, 1, 11, 7, 0, 0), remark='test_record_2') item.records = [record_1, record_2] db.session.add(item) db.session.commit()
def add_wishlist_items_to_db(wishlist_items): for i in wishlist_items: logger.info('Checking to see if {0} is in our db already'.format(i['ASIN'])) # check to see if we already have it, if not, add it to the database item_to_add = Item.query.filter_by(ASIN=i['ASIN']).filter(Item.live_data==False).first() if item_to_add is None: logger.info(' Don''t have it, adding now') item_to_add = Item(ASIN=i['ASIN']) item_to_add.is_on_wishlist = True db.session.add(item_to_add) db.session.commit() else: logger.info(' Yep, we had it')
def list_items(): """ Returns all of the Items """ items = [] price = request.args.get('price') name = request.args.get('name') if price: items = Item.find_by_price(price) elif name: items = Item.find_by_name(name) else: items = Item.all() results = [item.serialize() for item in items] return make_response(jsonify(results), status.HTTP_200_OK)
def upload_form(): form = UploadForm() if form.validate_on_submit(): if not form.pic.data: flash('Please select the file') else: suffix = os.path.splitext(form.pic.data.filename)[1] filename = random_string() + suffix photos.save(form.pic.data, name=filename) category = Category.query.filter_by( name=form.category.data).first() if form.store_location.data == 'No selection': item = Item(item_name=form.item_name.data, status=form.status.data, location=form.location.data, time=form.time.data, category_id=category.id, description=form.description.data, pic=filename, uploader_id=current_user.id) else: storage = Storage.query.filter_by( location_name=form.store_location.data).first() item = Item(item_name=form.item_name.data, status=form.status.data, location=form.location.data, time=form.time.data, category_id=category.id, description=form.description.data, pic=filename, uploader_id=current_user.id, store_location_id=storage.id) db.session.add(item) item_change = Item.query.filter_by( item_name=form.item_name.data, time=form.time.data, location=form.location.data, description=form.description.data).first() change = Change(changer_id=current_user.id, method='upload', item_id=item_change.id, item_name=item_change.item_name, content='create a ' + form.status.data + ' item named ' + form.item_name.data) db.session.add(change) db.session.commit() return 'success' return render_template('upload_form.html', form=form, current_user=current_user)
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.user = User(email="*****@*****.**", password="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.item = Item(name="Needs of bucket items", bucketlist_id=self.bucket_item.id) self.item.save()
def create_item(typeId): form = ItemForm() form['csrf_token'].data = request.cookies['csrf_token'] if form.validate_on_submit(): item = Item( name=form.data['name'], description=form.data['description'], user_id=current_user.id, type_id=typeId, ) db.session.add(item) db.session.commit() return {"item": item.to_dict()} return {"errors": "error with item form / post route"}
def addItems(app): with app.app_context(): app.logger.info("Adding order items...") db.session.add( Item( name="2021 Badge", description="The badge for the 2021 Kohoutek Online event", image="2021.png", unit_cost=1, index=1, )) db.session.add( Item( name="2020 Badge", description="The 2020 event badge", image="2020.png", unit_cost=1, limited=True, stock=100, index=2, )) db.session.add( Item( name="2019 Badge", description="The 2019 event badge", image="2019.png", unit_cost=1, limited=True, stock=150, index=3, )) db.session.add( Item( name="UOBGAS Badge", description= "The 'UOBGAS' (University of Bristol Guides and Scouts) club badge", image="uobgas.png", unit_cost=1, limited=True, stock=30, index=4, )) db.session.commit() app.logger.info("...done!")
def setUp(self): # setup the app and push app context: self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() # setup the db: db.drop_all() db.create_all() # create test datas for the users, bucketlists, and items: user = User( username='******', email='*****@*****.**', password='******' ) user.save() self.user = User(email="*****@*****.**", password="******", username="******") self.user.save() self.bucket_item = Bucketlist(name="Bucket List 1", user_id=self.user.id) self.bucket_item.save() self.item = Item(name="Item 1", bucketlist_id=self.bucket_item.id) self.item.save() self.user2 = User(email="*****@*****.**", password="******", username="******") self.user2.save() self.bucket_item2 = Bucketlist(name="Bucket List 2", user_id=self.user2.id) self.bucket_item2.save() self.item2 = Item(name="Item 1", bucketlist_id=self.bucket_item2.id) self.item2.save() bucket_item = Bucketlist(name="Bucket List", user_id=user.id) bucket_item.save() item = Item(name="Item 1", bucketlist_id=bucket_item.id) item.save() self.client = self.app.test_client() #create default login login_details = { 'email': '*****@*****.**', 'password': '******'} response = self.client.post( url_for('api.login'), headers=self.get_api_headers(), data=json.dumps(login_details) ) self.token = json.loads(response.data)['token']
def item(django_db_setup, django_db_blocker, merchant): ''' creating dummy items ''' with django_db_blocker.unblock(): for i in range(3): item = Item(name=f"item{i+1}", price=f"{i+1}00", description=f"desc{i+1}", merchant=merchant[i % 2]) item.save() item = Item.objects.all() # merchant = mixer.blend('app.Merchant') return item
def test_delete_a_item(self): """ Delete a Item """ item = Item(0, "fido", "dog") item.save() self.assertEqual(len(Item.all()), 1) # delete the item and make sure it isn't in the database item.delete() self.assertEqual(len(Item.all()), 0)
def is_full(): min = {"_id": "0", "value": 100000} cursor.execute( "select items.id, items.name, items.type, items.value, items.rare\ from items, users, storage\ where items.id=storage.item_id and users.id=storage.user_id and users.id=%s" % current_user.id) res = cursor.fetchall() items = [] for i in res: item = Item(i) items.append(item) if len(items) >= MAX_ITEM: for item in items: if item.value < min["value"]: min["_id"] = item.id min["value"] = item.value cursor.execute( "DELETE FROM storage WHERE item_id=%s AND user_id = %s " % (min['_id'], current_user.id)) cursor.execute("INSERT INTO explore VALUES (%s)" % min['_id']) conn.commit() return True else: return False
def equipment(oid): if not current_user.is_authenticated: return redirect(url_for('login')) cursor.execute("SELECT * FROM items WHERE id=%s" % oid) res = cursor.fetchone() item = Item(res) equiped = 0 cursor.execute("SELECT * FROM market WHERE item_id=%s" % oid) res = cursor.fetchone() if res: on_sale = 1 else: on_sale = 0 if item.type == 'weapon': type = '武器' pattern = '攻击力' if oid == str(current_user.weapon_id): equiped = 1 else: type = '盔甲' pattern = '防御力' cursor.execute("SELECT * FROM users, armors\ WHERE id=user_id AND id=%s AND armor_id=%s" % (current_user.id, oid)) res = cursor.fetchone() if res is not None: equiped = 1 return render_template('equipment.html', item=item, type=type, equiped=equiped, pattern=pattern, on_sale=on_sale)
def addItem(user_id): form = ItemForm(request.form, csrf_enabled=False) if form.validate_on_submit(): name = form.name.data url = form.item_url.data description = form.description.data if url: r = requests.get(url) html_content = r.text soup = BeautifulSoup(html_content) if "amazon" in url: image_url = soup.find('img', { 'id': 'miniATF_image' }).get('src') elif "ebay" in url: image_url = soup.find('img', {'id': 'icImg'}).get('src') print(image_url) item = Item(name, description, url, image_url, user_id) db.session.add(item) db.session.commit() return redirect(url_for('displayList', user_id=user_id)) return render_template("newItem.html", form=form, user_id=user_id)
def update_item(item_name, catagory_name): """Post endpoint to update an item. If form is invalid will return create item page with errors displayed, otherwise update item and redirect to item page. """ try: item = Item.fetch_by_name_and_catagory_name(item_name, catagory_name) except NoResultFound: abort(404) errors = form_errors(request.form) new_item_name = request.form.get('name') new_catagory_name = request.form.get('catagory') new_description = request.form.get('description') if errors: values = { 'name': new_item_name, 'catagory': new_catagory_name, 'description': new_description } catagories = [c.name for c in Catagory.fetch_all()] return render_template( 'add_item.html', catagories=catagories, values=values, errors=errors ) item.update( name=new_item_name, catagory_name=new_catagory_name, description=new_description ) return redirect(url_for( 'read_item', item_name=new_item_name, catagory_name=new_catagory_name ))
def sell(): if not session.get('logged_in'): flash(f'Please login to continue.', 'warning') return redirect('/login') form = SellForm() if form.validate_on_submit(): fileName = photos.save(request.files.get('imageUrl'), None, str(uuid.uuid4()) + ".") imageUrl = '/static/images/uploads/' + fileName item = Item(userId=int(session['user_id']), productName=form.productName.data, manufacturer=form.manufacturer.data, quantity=form.quantity.data, category=form.category.data, price=form.price.data, estimatedPrice=form.estimatedPrice.data, imageUrl=imageUrl) db.session.add(item) db.session.commit() flash(f'You item has been posted for sale!', 'success') return redirect('/item/' + str(item.itemId)) else: if form.errors: error_msg = list(form.errors.values())[0][0] flash(f'{error_msg} Please try again.', 'error') return render_template('sell.html', form=form)
def test_calculation_of_category(self): """ api: /category/<int:category_id>/calculation methods: get: 获取每一个分类下的所有条目的记录的时间总和(秒) """ category = Category.query.first() item = Item(name='test_item') record = Record(start=datetime(2019, 1, 10, 6, 0, 0), finish=datetime(2019, 1, 10, 7, 0, 0)) item.category = category record.item = item db.session.add(record) db.session.commit() res = self.client.get(BASE_URL + '/category/calculation').get_json() self.assertEqual(200, res['status']) self.assertEqual(3600, res['data'][0]['value'])
def shopping_list(): if request.method == "POST": print("Posted Data") post_data = request.get_json() item = Item(item=post_data.get('item'), quantity=post_data.get('quantity'), status=post_data.get('bought')) db.session.add(item) db.session.commit() return jsonify("Item Added") if request.method == "GET": all_items = Item.query.all() # use the AlchemyEncoder helper class to encode the query object in to JSON output = json.dumps(all_items, cls=AlchemyEncoder) output = json.loads(output) return jsonify({"list": output, 'status': 'success'}) if request.method == 'DELETE': Item.query.delete() db.session.commit() return jsonify("All Deleted")
def add_item(self, vendor_id): item = Item( vendor_id=vendor_id, item=self.item.data, price=self.price.data, second_material_id=self.second_material_id.data, category_id=self.category_id.data, scene_id=self.scene_id.data, length=self.length.data, width=self.width.data, height=self.height.data, area=self.area.data, stove_id=self.stove_id.data, outside_sand_id=self.outside_sand_id.data, inside_sand_id=self.inside_sand_id.data if self.inside_sand_id.data else 0, paint_id=self.paint_id.data, decoration_id=self.decoration_id.data, style_id=self.style_id.data, carve_type_id=self.carve_type_id.data, story=self.story.data, suite_id=0, amount=1, is_suite=False, is_component=False ) db.session.add(item) db.session.commit() self.add_attach(item.id) statisitc.init_statistic() return item
def add_suite(self, vendor_id): suite = Item( vendor_id=vendor_id, item=self.item.data, price=self.price.data, second_material_id=self.second_material_id.data, category_id=0, scene_id=self.scene_id.data, length='', width='', height='', area=self.area.data, stove_id=self.stove_id.data, outside_sand_id=self.outside_sand_id.data, inside_sand_id=self.inside_sand_id.data, paint_id=0, decoration_id=0, style_id=self.style_id.data, carve_type_id=self.carve_type_id.data, story=self.story.data, suite_id=0, amount=1, is_suite=True, is_component=False ) db.session.add(suite) db.session.commit() statisitc.init_statistic() return suite
def update_item(id: int): item = Item.query.filter_by(id=id).first() if item is None: return not_found('item não encontrado') data = request.get_json() or {} error = Item.check_data(data=data) if 'registry' in data and data['registry'] is not None \ and data['registry'] != item.registry and \ Item.query.filter_by(registry=data['registry']).first() is not None: error = 'tombo já existe' if 'category_id' in data and data['category_id'] is not None and \ Category.query.get(data['category_id']) is None: error = 'category_id não existe' if error: return bad_request(error) item.from_dict(data) try: db.session.commit() except Exception: return internal_server() return jsonify(item.to_dict())
def list_items_from_an_order(order_id): """ Returns all items from an Order --- tags: - Orders produces: - application/json description: The Orders endpoint allows you to query Orders to get all items in that order parameters: - name: order_id in: path description: ID of Order to retrieve type: integer required: true responses: 200: description: An array of Items in an order schema: type: array items: schema: $ref: '#/definitions/Items' """ items = Item.find_by_order_id(order_id) results = [item.serialize() for item in items] return make_response(jsonify(results), status.HTTP_200_OK)
def setUp(self): """ Unittest setup method to initialize app in testing mode and create test data. :return: """ self.app = create_app("testing") self.client = self.app.test_client # binds the app to the current context with self.app.app_context(): # create all tables db.create_all() UnitMeasurement.insert_unit_measurement() Item.insert_items() db.session.commit()
def update_items(order_id, item_id): """ Update an Item This endpoint will update an Item for an order based on the body that is posted --- tags: - Items consumes: - application/json produces: - application/json parameters: - name: order_id in: path description: ID of the order that has item to be updated type: integer required: true - name: item_id in: path description: ID of the item that needs updating of a specified order type: integer required: true - in: body name: body schema: id: data required: - name - product_id - quantity - price name: type: string description: the item name product_id: type: integer description: the product_id of the item quantity: type: integer description: the quantity of the item price: type: number description: the price of the item responses: 200: description: Item updated schema: $ref: '#/definitions/Item' 400: description: Bad Request (the posted data was not valid) """ check_content_type('application/json') item = Item.get(item_id) if not item: raise NotFound("Item with id '{}' was not found.".format(item_id)) item.deserialize(request.get_json(), order_id) item.id = item_id item.save() return make_response(jsonify(item.serialize()), status.HTTP_200_OK)
def add_component(self, vendor_id, suite_id): component = Item( vendor_id=vendor_id, item=self.component.data, price=0, second_material_id=0, category_id=self.category_id.data, scene_id=0, length=self.length.data, width=self.width.data, height=self.height.data, area=self.area.data, stove_id=0, outside_sand_id=0, inside_sand_id=0, paint_id=self.paint_id.data, decoration_id=self.decoration_id.data, style_id=0, carve_type_id=0, story='', suite_id=suite_id, amount=self.amount.data, is_suite=False, is_component=True ) db.session.add(component) db.session.commit() self.add_attach(component.id) return component
def get_item(item_id): """ Retrieve a single Item This endpoint will return a Item based on it's id --- tags: - Items produces: - application/json parameters: - name: item_id in: path description: ID of item to retrieve type: integer required: true responses: 200: description: Item details returned schema: $ref: '#/definitions/Item' 404: description: Item not found """ item = Item.get(item_id) if not item: raise NotFound("Item with id '{}' was not found.".format(item_id)) return make_response(jsonify(item.serialize()), status.HTTP_200_OK)
def add_item(user_id): user = db.session.query(User).filter_by(id=user_id).first() tokens = map(lambda x: x.token, user.tokens) check = check_auth_header(request.headers) if not check[0]: return check[1] if not authenticate_user(tokens, request.headers['AuthToken']): return unauthorized_message() data = MultiDict(mapping=request.json) inputs = ItemForm(data, csrf_enabled=False) if not inputs.validate(): return bad_request_error(inputs.errors) data = request.get_json() name = data['name'] description = data['description'] thumbnail_url = data['thumbnail_url'] item_url = data['item_url'] item = Item(name, description, thumbnail_url, user_id, item_url) db.session.add(item) db.session.commit() response = jsonify({ 'name': item.name, 'description': item.description, 'thumbnail_url': item.thumbnail_url }) response.status_code = 201 return response
def post(self): # get the post data post_data = request.get_json() # check if item already exists item = Item.query.filter_by(item=post_data.get('item')).first() if not item: try: item = Item(item=post_data.get('item'), item_name=post_data.get('item_name'), item_description=post_data.get('item_description')) # insert the item db.session.add(item) db.session.commit() responseObject = { 'status': 'success', 'message': 'Item added successfully.' } return make_response(jsonify(responseObject)), 201 except Exception as e: responseObject = { 'status': 'fail', 'message': 'Some error occurred. Please try again.' } return make_response(jsonify(responseObject)), 401 else: if item: responseObject = { 'status': 'fail', 'message': 'Item with the same name already exists.', } return make_response(jsonify(responseObject)), 202
def delete_list_item(code, list_id, item): if (not current_user.is_authenticated) or (not List().check_correct_user( current_user.get_username(), code)): return abort(404) if not Item().delete_item(list_id, item): return ('', 400) return ('', 204)
def del_attr(): if request.method == 'POST': title = request.json['title'] attr_name = request.json['attr_name'] status = Item.del_attr(title, attr_name) if status: return jsonify(status=True, reason="删除属性成功") else: return jsonify(status=True, reason="删除失败")
def add_attr(): if request.method == 'POST': title = request.json['title'] attr_name = request.json['attr_name'].strip() attr_type = request.json['attr_type'] attr_value = request.json['attr_value'].strip() if not attr_name: return jsonify(status=False, reason="属性名不能为空") if not attr_value: return jsonify(status=False, reason="属性值不能为空") if Item.find_attr(title, attr_name) is not None: return jsonify(status=False, reason="属性已存在") status = Item.add_attr(title, attr_name, attr_value, attr_type) if status: if current_user.is_authenticated: current_user.add_edit() html = TypeRender.render_html(attr_name, attr_value, attr_type) return jsonify(status=True, reason="添加属性成功", html=html)
def get(self): if request.args.get('item') is not None: bucketlist_id = int(request.args.get('item')) table = Item.db.table('bucketlists') result = table.get(where('id') == bucketlist_id) if result is None: return jsonify({}) return jsonify(result) items = jsonify(Item.all()) return items
def search(): q = request.args.get('q', None) if q is None: abort(404) keyword = q.strip() regx = re.compile(r'%s' %keyword, re.IGNORECASE) list = Item.find_items(regx) if list.count() == 0: flash('没有找到结果', 'search') return render_template('explore.html', items=list, title='搜索')
def put(self, item_id): data = request.json or {} attr_name = data.get('attr_name', None) attr_value = data.get('attr_value', None) attr_type = data.get('attr_type', None) if item_id and attr_name and attr_value and attr_type: if Item.edit_attr_by_id(item_id, attr_name, attr_value, attr_type): return jsonify(status=True) else: return jsonify(status=False) return jsonify(status=False)
def post(self): item = request.json or {} title = item.get('title', None) type = item.get('type', None) if title and type: id = Item.create_item(title, type) if id: return jsonify(status=True) else: return jsonify(status=False) return jsonify(status=False)
def make_object(self, data): try: print data['url'] u = urlopen(data['url']) except: raise URLOpenError("Can't access Url") parser = FeedParser() if not parser.parse(u): abort(400) feed = Feed(**parser.feed) feed.user_id = g.current_user.id for item in parser.items: new_item = Item(**item) new_item.feed_title = feed.title feed.items.append(new_item) g.current_user.feeds.append(feed) db.session.add(g.current_user) db.session.commit() return feed
def save_wishlist_item(user_id, wishlist_name): token = request.headers.get('auth-token') data = MultiDict(mapping=request.json) inputs = ItemForm(data, csrf_enabled=False) if not inputs.validate(): return jsonify({'error': 'invalid inputs'}) wishlist = db.session.query(Wishlist).filter(user_id=user_id, name=wishlist_name).first() name = data['name'] description = data['description'] item = Item(name, description=description) wishlist.items.append(item) db.session.add(item) db.session.commit() return jsonify(item.__repr__())
def test_saving_and_retrieving_items(self): first_item = Item() first_item.text = 'The first (ever) list item' first_item.save() second_item = Item() second_item.text = 'Item the second' second_item.save() saved_items = Item.objects.all() self.assertEqual(saved_items.count(), 2) first_saved_item = saved_items[0] second_saved_item = saved_items[1] self.assertEqual(first_saved_item.text, 'The first (ever) list item') self.assertEqual(second_saved_item.text, 'Item the second')
def pk(): if request.method == 'POST': pk_str = request.form.get('pk').strip() g = pk_regx.match(pk_str) if g: pk1_title = g.groups()[0] pk2_title = g.groups()[2] pk1_regx = re.compile(pk1_title, re.IGNORECASE) pk2_regx = re.compile(pk2_title, re.IGNORECASE) pk1_item = Item.find_item(pk1_regx) pk2_item = Item.find_item(pk2_regx) if pk1_item and pk2_item: # 按首字母大小排序 rows_by_name = defaultdict(list) for attr in pk1_item['attributes']: rows_by_name[attr['attr_name']].append(attr) for attr in pk2_item['attributes']: # 保证顺序 if not attr['attr_name'] in rows_by_name.keys(): rows_by_name[attr['attr_name']].append({}) rows_by_name[attr['attr_name']].append(attr) for key, attrs in rows_by_name.items(): if len(attrs) == 1: attrs.append({}) return render_template('pk.html', pk1=pk1_item, pk2=pk2_item,\ rows=rows_by_name, TypeRender=TypeRender) else: if not pk1_item: flash('搜索不到%s'%pk1_title, 'red') if not pk2_item: flash('搜索不到%s'%pk2_title, 'red') else: flash('输入格式有误', 'red') return redirect(url_for('.index'))
def create_entry(): entry_form = BaseEntryForm() if entry_form.validate_on_submit(): title = request.form['title'].strip() type = request.form['type'].strip() if not title: flash('属性不能为空', 'red') elif not type: flash('类型不能为空', 'red') elif Item.find_item(title): flash('词条已存在', 'yellow') else: status = Item.create_item(title, type) if status: Item.add_type(type) if current_user.is_authenticated: current_user.add_create() return redirect(url_for('.item', title=title)) else: for field, errors in entry_form.errors.items(): for error in errors: flash("%s: %s" %(getattr(entry_form, field).label.text, error), 'red') types = Item.types() return render_template('create.html', entry_form=entry_form, title='创建条目', types=types)
def test_iFrame5(self): item = Item('test_id') item.lock = True item.save() rv = self.app.get('/test_id') assert rv.status_code == 404 assert 'The item is being ingested' in rv.data item.lock = False item.save() rv = self.app.get('/test_id') assert rv.status_code == 200
def edit_attr(): if request.method == 'POST': title = request.json['title'] attr_name = request.json['attr_name'].strip() attr_type = request.json['attr_type'] attr_value = request.json['attr_value'].strip() if not attr_name: return jsonify(status=False, reason="属性名不能为空") if not attr_value: return jsonify(status=False, reason="属性值不能为空") status = Item.edit_attr(title, attr_name, attr_value, attr_type) if status: if current_user.is_authenticated: current_user.add_edit() return jsonify(status=True, reason="修改属性成功") else: return jsonify(status=True, reason="修改失败")
for city in cities: datacenter = Datacenter() datacenter.name = "DC %s" % city datacenter.address = city datacenters.append(datacenter) db.session.add(datacenter) log.info(datacenter) try: db.session.commit() for num in range(1, DC_RACK_MAX): rack = Rack() rack.num = num rack.datacenter = datacenter db.session.add(rack) except Exception as e: log.error("Creating Datacenter: %s", e) db.session.rollback() for i in range(1, ITEM_MAX): item = Item() item.serial_number = serial_generator() item.model = get_random_name(models) db.session.add(item) log.info(item) try: db.session.commit() except Exception as e: log.error("Creating Item: %s", e) db.session.rollback()
def api_add_new_item(request): if request.POST: if request.POST.get('name', None) is None: return HttpResponse("Invalid request (You're missing a required field)", content_type="text/plain") i = Item() i.item_name = request.POST.get('name', '') i.item_author = request.POST.get('author', '') i.item_store = request.POST.get('store', '') if request.POST.get('priority', 'false') == 'true' or request.POST.get('priority', 'false') == 'yes': i.item_is_priority = True elif request.POST.get('priority', 'false') == 'false' or request.POST.get('priority', 'false') == 'no'\ or request.POST.get('priority', 'false') is None: i.item_is_priority = False i.item_category = request.POST.get('category', '') i.item_purchased = False i.item_date_added = datetime.datetime.today() i.save() return HttpResponse(serializers.serialize('json', Item.objects.filter(pk=i.pk)), content_type="application/json", status=200) else: return HttpResponse("Invalid request (Missing POST data)", content_type="text/plain")
def add_item(request): print("Request for new item is being processed...") print(request.POST['name']) print(request.POST['author']) print(request.POST['store']) i = Item() i.item_name = request.POST['name'] i.item_author = request.POST['author'] i.item_store = request.POST['store'] if request.POST.get('priority', 'false') == 'true' or request.POST.get('priority', 'false') == 'yes' or request.POST.get('priority', 'false') == 'on': i.item_is_priority = True elif request.POST.get('priority', 'false') == 'false' or request.POST.get('priority', 'false') == 'no'\ or request.POST.get('priority', 'false') is None: i.item_is_priority = False i.item_category = request.POST['category'] i.item_purchased = False i.item_date_added = timezone.now() i.save() print("Request processed.") return HttpResponseRedirect(reverse('index'))
def delete(self, item_id): if Item.del_item_by_id(item_id): return jsonify(status=True) else: return jsonify(status=False)
def item(title): item = Item.find_item(title) if not item: abort(404) Item.inc_view(title) return render_template('item.html', item=item, TypeRender=TypeRender)
def get(self, request, post_id=None, format=None): start, num_of_records = self.paginator(request) ################################################# # You can overwrite start and num_of_records here # start = 0; num_of_records = 100 # ####################################### # get list of items owned by a specific user # Don't need any authentication params = request.GET order_by = None order_by_model = None bounds = {} if params.get("user_id"): if request.user.is_anonymous(): Q_perm = Q(visibility="Public") else: Q_perm = reduce(operator.or_, [ Q(visibility="Public"), Q(visibility="Ex-owners", previous_owners=request.user) ]) Q_kwargs = reduce(operator.and_, [ Q(owner__id=params["user_id"]), Q_perm, ]) return run_and_respond( retrieve_records, Item, ItemSerializer, start, num_of_records, Q_kwargs, ) if params.get("tags"): tags = params.get("tags").split(",") kwargs_tags = reduce( operator.and_, [Q(tags=tag) for tag in tags] ) kwargs_tags_private = reduce( operator.and_, [Q(tags=tag) for tag in tags] ) sqs = (SearchQuerySet().models(self.model) .filter(kwargs_tags).filter_or(kwargs_tags_private) .filter(owner=request.user) ) print("\tReturned %s search results: %s" % (sqs.count(), sqs)) if not sqs: return Response(status=st.HTTP_404_NOT_FOUND) sqs = [sq.object for sq in sqs] return Response(data=self.serializer(sqs, many=True).data) # get list of items of the current authenticated user elif not request.user.is_anonymous(): if params.get("order_by"): # <order_by> is the field name that is ordering by order_by = params['order_by'] # <order_by_model> is the field type # e.g. customized_char_fields # Use Item.customized_fields() to normalize the names order_by_model = params["order_by_model"] for key, val in Item.customized_fields().items(): if order_by_model == val.__name__: order_by_model = key bounds = {} if "lower_bound" in params: lower_bound = params["lower_bound"] bounds["%s__value__gt" % (order_by_model)] = lower_bound if "upper_bound" in params: upper_bound = params["upper_bound"] bounds["%s__value__lt" % (order_by_model)] = upper_bound data, status = retrieve_records( Item, ItemSerializer, start, num_of_records, owner=request.user, order_by_model=order_by_model, order_by=order_by, **bounds ) return Response(data=data, status=status) # unauthenticated user cannot get any item list else: return Response( status=st.HTTP_401_UNAUTHORIZED, data={"error_message": "Please log in."} )
def lucky(): # 总条数 item = Item.get_random_item() if item: return redirect(url_for('.item', title=item['title'])) return redirect(url_for('.index'))
def explore(): items = Item.find_items() return render_template('explore.html', items=items, title='发现')
"price":".50", "price_type":"each", "description":"Oh, here we go with the colors again..", "post_date":datetime.datetime(2016, 1, 1, 13, 00), "user_id":random.randint(1,10) }, 24: {"title":"Rooster Potatoes by the Pound", "category":"Vegetable", "price":"3.00", "price_type":"each", "description":"Way to mix it up.", "post_date":datetime.datetime(2016, 1, 1, 13, 00), "user_id":random.randint(1,10) } } for i in range(0, 25): item = Item(item_dict[i]["title"], item_dict[i]["category"], \ item_dict[i]["price"], item_dict[i]["price_type"], \ item_dict[i]["description"], item_dict[i]["user_id"]) item.post_date = item_dict[i]["post_date"] db.session.add(item) db.session.commit() """ 25: {"title" = "Eggs Are Good", "category" = "Protein", "price" = ".15", "price_type" = "each", "description" = "Some good eggs here, folks", "post_date" = datetime.datetime(2016, 1, 1, 13, 00), "user_id" = random.randint(0,9) },
sci_fi = Category('Sci-Fi', ''' There are a films in Sci-Fi genre ''', user.id) db_session.add(sci_fi) db_session.commit() sci_fi = Category.query.filter_by(name='Sci-Fi').one() pitch = Item('Pitch Perfect 2', ''' After a humiliating command performance at Lincoln Center, the Barden Bellas enter an international competition that no American group has ever won in order to regain their status and right to perform. ''', comedy.id, user.id) pitch.image_name = 'pitch_perfect_2.jpg' db_session.add(pitch) db_session.commit() home = Item('Home', ''' Oh, an alien on the run from his own people, lands on Earth and makes friends with the adventurous Tip, who is on a quest of her own.