def uploadImage(_cu, categories, image, img_id, description="", hashtags=[]): usr = User.verifySession(_cu) if usr: hashtags_ = re.findall(r"#(\w+)", description) if hashtags_: hashtags_ = [hashtag.lower() for hashtag in hashtags_] hashtags_.extend(hashtags) img = Image(userID=usr.get('_id'), categories=categories, image=image, description=description, tags=hashtags_, img_id=img_id) img.saveImg() Category.updateCategories(categories, inc=1) # Category.updateCategory(cat) User.updateUploads(_cu) return True return 0
def parse_response(cls, content): """ Parse the XML response from eBay API :param content: XML data to parse :return: Categories dictionary """ print('--------> Parsing response from eBay...') categories = [] root = ElementTree.fromstring(content) ack_node = root.find('n:Ack', namespaces=cls._nsmap) # Verify whether response is success if ack_node is not None and ack_node.text == 'Success': count = root.find('n:CategoryCount', namespaces=cls._nsmap).text print('--------> {} categories found!'.format(count)) categories_root = root.find('n:CategoryArray', namespaces=cls._nsmap) # Traverse the categories for node in categories_root.findall('n:Category', namespaces=cls._nsmap): category = Category( cls.get_node_attrib(node, 'n:CategoryID'), cls.get_node_attrib(node, 'n:CategoryName'), cls.get_node_attrib(node, 'n:CategoryLevel'), cls.get_node_attrib(node, 'n:CategoryParentID'), cls.get_node_attrib(node, 'n:BestOfferEnabled'), cls.get_node_attrib(node, 'n:Expired'), cls.get_node_attrib(node, 'n:LeafCategory')) categories.append(category) else: print('--------> Error in eBay response!') return categories
def admin_edit_categories(): if not current_user.is_admin: abort(401) search_line = request.args.get('search_line', '') page = int(request.args.get('page', '1')) add_category_form = AddCategoryForm(prefix='add_category_form') db_sess = create_session() categories = db_sess.query(Category).filter( Category.title.like(f'%{search_line}%')) pages_count, categories, pagination = create_buttons_of_pagination( page, categories) categories = search_categories(categories) message = '' if request.method == 'POST' and add_category_form.validate_on_submit(): title = add_category_form.title.data if title in [ category.title for category in db_sess.query(Category).all() ]: message = 'Категория с таким именем уже есть' else: db_sess.add(Category(title=add_category_form.title.data)) db_sess.commit() elif request.method == 'POST': category_id = request.form.get('id', None) category = categories[int( category_id)] if category_id is not None else None if category is not None and category[1].validate_on_submit(): if any([ anecdote.category == category[0] for anecdote in db_sess.query(Anecdote).all() ]): message = 'К этой категории привязаны анекдоты' else: db_sess.delete(category[0]) db_sess.commit() categories = db_sess.query(Category).filter( Category.title.like(f'%{search_line}%')) pages_count, categories, pagination = create_buttons_of_pagination( page, categories) categories = search_categories(categories) context = { 'edit_categories': categories, 'add_category_form': add_category_form, 'search_line': search_line, 'pagination': pagination, 'page_count': pages_count, 'page': page, 'message': message } return make_response( render_template('admin_edit_categories.html', **context))
def get_all_categories(self): mycursor = self.mydb.cursor(dictionary=True) mycursor.execute('SELECT * FROM categories') categories = mycursor.fetchall() if bool(categories): result = [] for c in categories: result.append(Category(**c)) return result else: return None
def post(self): if not auth.current_user().is_admin or\ auth.current_user().is_banned: return make_response(jsonify({"error": "permission denied"}), 403) try: db_sess = db_session.create_session() category = Category(title=request.json["title"]) db_sess.add(category) db_sess.commit() except Exception: return make_response(jsonify({"error": "bad request"}), 400) return make_response(jsonify({"title": category.title}), 201)
def edit_category(title): # category represents category object(value) to title category = CATEGORIES[title] if request.method == 'POST': # what we put on the form is the title of the category object category.title = request.form['title'] return render_template('categories.html', categories=CATEGORIES, title=category.title) # IF its a get request we render the edit template to update the data on the form return render_template('edit_category.html', title=category.title, category=Category(title))
def get_category_by_id(self, category_id): """ Finds a category by id in db. :param category_id: Category id :return: """ cursor = self._connection.cursor() # Query db cursor.execute("""SELECT * FROM categories WHERE id = ?""", (category_id, )) row = cursor.fetchone() category = Category(row[0], row[1], row[2], row[3], row[4], row[5], row[6]) print(category) self._get_children(category) return category
def GetImgCategory(cat = None): if cat: return Image.GetImgsByCategory(cat) categories = Category.getAllCategories() finalCategories = [] for category in categories: img = Database.find( collection=Image.COLLECTION, query={ 'categories': category.get('category')}) if img: category.update({'image': img.get('image')}) finalCategories.append(category) return finalCategories
def _get_children(self, category): if category.leaf: return cursor = self._connection.cursor() # Query db cursor.execute( """SELECT * FROM categories WHERE parent = ? AND id != ?""", (category.id, category.id)) rows = cursor.fetchall() for row in rows: child = Category(row[0], row[1], row[2], row[3], row[4], row[5], row[6]) print(child) self._get_children(child) category.children.append(child)
def get_categories_by_user_id(self, user_id: int): mycursor = self.mydb.cursor(dictionary=True) mycursor.execute('SELECT * FROM user_category WHERE user_id = %s', (user_id, )) user_category_list = mycursor.fetchall() category_id_list = [] for ucl in user_category_list: category_id_list.append(UserCategory(**ucl).category_id) if bool(category_id_list): category_id_list = tuple(category_id_list) mycursor.execute('SELECT * FROM categories WHERE id IN {}'.format( category_id_list)) categories = mycursor.fetchall() result = [] for c in categories: result.append(Category(**c)) return result else: return None
def setUp(self): self.title = Category("lunch")
class Recipe_categoryTest(unittest.TestCase): def setUp(self): self.title = Category("lunch") def test_recipe_instantiation(self): self.assertIsInstance(self.title,Category, "Failed to instantiate") def test_add_recipe_added(self): self.assertEqual(self.title.add_recipe("pillawo"), "recipe added succesfully") def test_add_recipe_exists(self): self.title.add_recipe("pizza") self.assertEqual(self.title.add_recipe( "pizza"), "recipe already exists") def test_edit_recipe_not_found(self): self.assertEqual(self.title.edit_recipe( "chicken recipe", "beef recipe"), "no recipe to edit") def test_edit_recipe_edited_succesfully(self): self.title.add_recipe("pizza") self.assertEqual(self.title.edit_recipe("pizza", "chicken"), "recipe edited successfully") def test_delete_recipe_not_found(self): self.assertEqual(self.title.delete_recipe( "katogo"), "No recipe to delete") def test_recipe_item(self): self.title.add_recipe("katogo") self.assertEqual(self.title.delete_recipe("katogo"), "recipe deleted")
def add_category(): if request.method == 'POST': # Adding the Category object to the CATEGORIES dict CATEGORIES[request.form['title']] = Category(request.form['title']) return render_template('categories.html', categories=CATEGORIES) return redirect(url_for('dashboard')) # this is a get request
render_kw={"placeholder": "Martha_Jones96"}) password = PasswordField("Password", validators=[ InputRequired('Please Enter your Password'), Length(min=6, max=16, message='Invalid Password') ], render_kw={"placeholder": "******"}) submit = SubmitField("Login", validators=[InputRequired()]) Database.initialize('Atypical') categories = Category.getAllCategories(True) categories = [(cat, cat) for cat in categories] # print(categories) class UploadForm(FlaskForm): photo = FileField('Upload your Picture', validators=[ FileRequired('File not selected!'), FileAllowed(['jpg', 'png', 'jpeg'], 'Images only!') ]) # category = SelectField("Category", # choices=categories, # validators=[ # InputRequired('Please Choose a Category')])
def inject_stage_and_region(): categories = Category.getAllCategories() categories = [cat for cat in categories] return dict(categories=categories)