def post(self): update = self.request.get('update', False) cate_name = self.request.get('cate_name') tags_list = self.request.get_all('tags_name', []) title = self.request.get('title') blog = self.request.get('blog') if not blog: self.response.write('blog content empty!') cate = Category.query(Category.title==cate_name).get() if not cate: cate = Category(title=cate_name) cate.put() print tags_list tags = Tag.query(Tag.title.IN(tags_list)).fetch() tags_old = [tag.title for tag in tags] tags_new = [] for tag in tags_list: if tag not in tags_old: tag = Tag(title=tag) tag.put() tags_new.append(tag) print tags print tags_new tags += tags_new print tags print '===' print dir(tags[0]) tags = [tag.key for tag in tags] blog = Blog(title=title, text=blog, category=cate.key, tags=tags) blog.put() self.response.write('blog publish success') self.response.set_status(200)
def index(request): params = {} if settings.SHOWPAGES: pages = Page.all() pages.order("-modified") posts = pages.fetch(settings.SHOWPAGES) params['posts'] = posts return respond(request, 'base.html', params) else: home_category = 'Main' home_page = 'Home' page = db.GqlQuery("SELECT * FROM Page WHERE name = :1", home_page).get() if page == None: if users.get_current_user(): category = db.GqlQuery("SELECT * FROM Category WHERE name = :1", home_category).get() if category == None: category = Category(name=home_category, sequence=1) category.put() page = Page(name=home_page, category=home_category, sequence=1, content='<h1>Home Page</h1><h5>Change me!</h5>') page.put() else: return HttpResponseRedirect(users.create_login_url(request.get_full_path())) return viewPage(request, 'Main', 'Home')
def _get_next_level(self, current): if self.direction == 'down': return Category.get_all_children(current, version=self.version) elif self.direction == 'up': return Category.get_all_parents(current, version=self.version) else: raise Exception("Unknown direction %s" % self.direction)
def test_model_category(self): """Test category model""" obj = Category(name='test') obj.save() self.assertEquals('test', obj.name) self.assertNotEquals(obj.id, None) obj.delete()
def post(self, subdomain): namespace_manager.set_namespace(subdomain) visible = False if self.request.get('visible') == 'yes': visible = True name = self.request.get('name') categories = self.request.get('category').split(',') logging.info(categories) cat_refs = [] for category in categories: logging.info(category) if Category.get_by_key_name(category): cat_refs.append(Category.get_by_key_name(category).key()) logging.info(cat_refs) entity = Product(key_name=name, name=name, shop_id=Shop.get_by_key_name(subdomain), stock=int(self.request.get('qty')), description=self.request.get('description'), price=float(self.request.get('price')), tags=self.request.get('tags').split(','), video=self.request.get('video'), visible=visible, categories=cat_refs ) entity.put() self.redirect(webapp2.uri_for('addproducts'))
def category(action, id=None): if action=="edit": category = Category.query.get(id) if category == None: abort(404) name = category.name else: name = None form = category_form(name) if form.validate_on_submit(): if action == "new": category = Category( name=form.name.data, color=form.color.data, user=g.user) elif action == "edit": category.name = form.name.data category.color = form.color.data db.session.add(category) db.session.commit() return redirect(url_for('settings')) elif request.method != 'POST': if action=="edit": form.name.data = category.name form.color.data = category.color return render_template( 'category.html', title = "Configure category", form = form)
def new_category(): """ Add new category """ # Check if the user is loged in if 'username' not in login_session: return redirect('/login') if request.method == 'POST': # Get data from the front-end name = request.form['name'] description = request.form['description'] # Put the data into a model category = Category(name=name, user_id=login_session['user_id']) # Save description if there are one if description: category.description = description session.add(category) session.commit() return redirect(url_for('categories')) return render_template('categories/new_category.html')
def new_category(): """ Route that renders the page to add a new category. This method validate that the user is logged in. The category is associated with the current logged in user. Raises: If an error occurs the application will redirect to index page and a flash message will be displayed with the proper Exception message. """ try: logged_in = 'username' in login_session if not logged_in: flash("You must be logged to perform this operation", category="error") return redirect(url_for('index')) form = CategoryForm() category = Category() category.name = "New item" if form.validate_on_submit(): form.populate_obj(category) category.user_id = login_session["user_id"] db_session.add(category) db_session.commit() flash("Category '{}' successfully added".format(category.name)) return redirect(url_for('get_category', category_id=category.id)) else: categories = db_session.query(Category).order_by(Category.name).all() return render_template('new_category.html', categories=categories, active_category=-1, form=form, logged_in=logged_in, login_session=login_session) except Exception as e: flash('An error has occurred: {}'.format(str(e)), 'error') return redirect(url_for('index'))
def get(self, name = ''): objs = Category.get_cat_page_posts(name, 1) catobj = Category.get_cat_by_name(name) if catobj: pass else: self.redirect(BASE_URL) return allpost = catobj.id_num allpage = allpost/EACH_PAGE_POST_NUM if allpost%EACH_PAGE_POST_NUM: allpage += 1 output = self.render('index.html', { 'title': "%s - %s"%( catobj.name, SITE_TITLE), 'keywords':catobj.name, 'description':SITE_DECR, 'objs': objs, 'cats': Category.get_all_cat_name(), 'tags': Tag.get_hot_tag_name(), 'page': 1, 'allpage': allpage, 'listtype': 'cat', 'name': name, 'namemd5': md5(name.encode('utf-8')).hexdigest(), 'comments': Comment.get_recent_comments(), 'links':Link.get_all_links(), },layout='_layout.html') self.write(output) return output
def save_edited_category(): cat_name = request.form.get("category") key = request.form.get("key") existing = Category.all().filter("owner =", users.get_current_user()) for e in existing: if e.title.lower() == cat_name.lower(): if not str(e.key()) == key: error = "You already have a category with that name. Please choose a different name" return Response(status=400) category = Category.get(key) items_from_form = request.form.get("items").split(",") old_items_from_db = Item.all().ancestor(category) for item in old_items_from_db: if not item.title in items_from_form: db.delete(item) else: items_from_form.remove(item.title) for new_item in items_from_form: if not new_item == "": i = Item(parent=category, title=new_item) i.put() category.title = request.form.get("category") category.put() return jsonify(new_items=items_from_form)
def show_by_category(request, key): context = base_context() rpp = record_per_page() cur_page = 1 try: cur_page = int(request.REQUEST["jumpPage"].strip()) except: cur_page = 1 blogs_count = Blog.all().filter("category", Category.get(key)).count() max_page = blogs_count / rpp temp2 = blogs_count % rpp if temp2 != 0: max_page = max_page + 1 if cur_page > max_page or cur_page <= 0: cur_page = max_page if cur_page == 0 or cur_page > max_page: cur_page = max_page blogs = Blog.all().filter("category", Category.get(key)).order("-date").fetch(0) else: blogs = Blog.all().filter("category", Category.get(key)).order("-date").fetch(rpp, rpp * (cur_page - 1)) context.cur_page = cur_page context.max_page = max_page context.action_mode = "/category/" + key + "/show" context.range1 = range(1, max_page + 1) context.up_page = cur_page - 1 context.down_page = cur_page + 1 context.blogs = blogs template = loader.get_template("blogs/index.html") return HttpResponse(template.render(context))
def add_category_success(request): if request.method == "POST": name = request.POST['name'] description = request.POST['description'] c = Category(name=name, description=description) c.save() return render_to_response('blog/add_category_success.html', context_instance=RequestContext(request))
def post(self, *args): c = Category( name=self.request.get('name'), link=self.request.get('link') ) c.put() self.redirect('/admin')
def save(self): cd = self.cleaned_data category = Category( name=cd['name'] ) category.save()
def __init__(self, table_p, parent, product=None, *args, **kwargs): QDialog.__init__(self, parent, *args, **kwargs) self.table_p = table_p self.prod = product self.parent = parent self.filename = "Parcourire ..." self.path_filename = None if self.prod: self.title = u"Modification de l'article {}".format(self.prod.name) self.succes_msg = u"L'article <b>%s</b> a été mise à jour" % self.prod.name try: self.filename = self.prod.file_join.file_name except: pass else: self.succes_msg = u"L'article a été bien enregistré" self.title = u"Ajout de nouvel article" self.prod = Product() self.setWindowTitle(self.title) # self.code = LineEdit(self.prod.code) self.name_field = LineEdit(self.prod.name) try: self.category_name = Category.select().where( Category.name == self.prod.category.name).get().name except: self.category_name = "" self.category_field = LineEdit(self.category_name) self.number_parts_box_field = IntLineEdit( str(self.prod.number_parts_box)) self.number_parts_box_field.setValidator(QIntValidator()) completion_values = [catg.name for catg in Category.all()] completer = QCompleter(completion_values, parent=self) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.category_field.setCompleter(completer) vbox = QVBoxLayout() formbox = QFormLayout() formbox.addRow(FLabel(u"Nom"), self.name_field) formbox.addRow(FLabel(u"Categorie"), self.category_field) # formbox.addRow( # FLabel(u"Quantité (carton)"), self.number_parts_box_field) self.butt_parco = QPushButton( QIcon.fromTheme('document-open', QIcon('')), self.filename) self.butt_parco.clicked.connect(self.import_image) butt_cancel = Warning_btt(u"Annuler") butt_cancel.clicked.connect(self.cancel) # formbox.addRow(FLabel(u"Image"), self.butt_parco) butt = Button_save(u"&Enregistrer") butt.clicked.connect(self.add_or_edit_prod) formbox.addRow(butt_cancel, butt) vbox.addLayout(formbox) self.setLayout(vbox)
def setUp(self): testboss = User.objects.create(username='******') testuser = User.objects.create(username='******', password='******') category = Category(name="TEST") category.save() self.task = Task.objects.create(summary='Some job', content='', reported_by=testboss) self.task.categories.add(category)
def test_edit(self): title = "Vodka based" category = Category(title=title) category.save() self.assertEqual(Category.objects.all().count(), 1) url = category.get_absolute_url() res = self.app.get(url) edit_url = category.get_edit_url() self.assert_(edit_url in res.content) res = self.app.get(edit_url) self.assert_(title in res.content) self.assert_("Edit" in res.content) form = res.form title += ' edited' form['title'] = title datail_res = form.submit().follow() self.assert_(title in datail_res.content) self.assert_(edit_url in datail_res.content) self.assertEqual(Category.objects.all().count(), 1)
def post(self): json = {} if not self.current_user: json = { 'error': 1, 'msg': self._('Access denied') } self.write(json) return title = self.get_argument('title', None) slug = self.get_argument('slug', None) description = self.get_argument('description', '') # valid arguments if not title: json = { 'error': 1, 'msg': self._('Title field can not be empty') } self.write(json) return if not slug: json = { 'error': 1, 'msg': self._('Slug field can not be empty') } self.write(json) return elif self.get_category_by_slug(slug): json = { 'error': 1, 'msg': self._('Slug already exists') } self.write(json) return # create category category = Category() category.title = title category.slug = slug category.description = description self.db.add(category) self.db.commit() # delete cache keys = ['CategoryList', 'SystemStatus'] self.cache.delete_multi(keys) json = { 'error': 0, 'msg': self._('Successfully created'), 'category': { 'id': category.id, 'title': category.title, 'slug': category.slug, 'description': category.description, 'permalink': category.permalink, 'post_count': category.post_count } } self.write(json)
def admin_delete_category(cat_id): Category.delete(cat_id) posts = Post.query.filter_by(category_id=cat_id).all() if posts is not None: for p in posts: Post.update_category_id(p.post_id, 0) categories = Category.query.all() return render_template('admin_categories.html', title='Admin', user=current_user, categories=categories)
def add_category(request): if request.method == 'POST': category = Category() category.name = request.POST['name'] category.slug = request.POST['slug'] category.put(); return HttpResponseRedirect('/category/add') return render_to_response('add_category.html', context_instance=RequestContext(request))
def top_users(): user_m = UserManager() post_m = PostManager() top_users = user_m.top_users() top_posts = post_m.top_posts() top_comments = User.top_comments() Category.posts_without_cat() return render_template('top_users.html', users=top_users)
def pop_categories(): for n in range(10): category_title = "cat %s %s" % (n, datetime.datetime.now().strftime("%Y/%m/%d")) category_slug = category_title + ' slug' category_description = "Aenean erat felis, fermentum sit amet fringilla quis, porta eu dolor. Curabitur vel massa vel neque bibendum cursus non ac mi." new_cat = Category(title=category_title, slug=category_slug, description=category_description) new_cat.save() print('Saved %s to database.' % new_cat.title)
def test_ensure_views_are_positive(self): """ ensure_views_are_positive should results True for categories where views are zero or positive """ cat = Category(name='test',views=-1, likes=0) cat.save() self.assertEqual((cat.views >= 0), True)
def test_create_category_duplicate(self): """Makes sure categories can't be created with the same name and category id.""" create_category(category_id="001", description="testing") from peewee import IntegrityError with self.assertRaises(IntegrityError): create_category(category_id="001", description="testing") Category.get(Category.category_id == "001").delete_instance()
def add_category(request): if request.method == "POST": category = Category() category.name = request.POST["name"] category.slug = request.POST["slug"] category.put() return HttpResponseRedirect("/category/add") return render_to_response("add_category.html", context_instance=RequestContext(request))
def convert_to_entity(json): category_key = get_key(json['slug']) if category_key.get() != None: return None category = Category(key=category_key) category.title = json['title'] category.id = json['id'] category.time_added = datetime.utcnow() return category
def category_add(): if request.method == 'GET': all_categories = Category.select() template = env.get_template('post/category_add.html') return template.render(categories=all_categories) if request.method == 'POST': new_category = Category.create(category_name=post_get('category_name')) app.flash(u'Нова категорія була успішно додана') redirect('/category/add')
def setUp(self): self.client = Client() p = User.objects.create_user("admin", "*****@*****.**", "admin") p.is_staff = True p.is_active = True p.is_superuser = True p.save() p = Category(name="Jobs") p.save()
def test_slug_line_creation(self): """ slug_line_creation checks to make sure that when we add a category an appropriate slug line is created i.e. "Random Category String" -> "random-category-string" """ cat = Category(name='Random Category String') cat.save() self.assertEqual(cat.slug, 'random-category-string')
def post(self): try: title = self.request.get('title') desc = self.request.get('desc') except: self.redirect('/categories') if title: c = Category(title=title, desc=desc) c.put() self.redirect('/categories')
def product_all(): page = int(request.args.get("page", 1)) order = request.args.get("order") cid = request.args.get("cid") if cid: current_cate=Category.get(id=cid) else: current_cate=None periods=Period.get_list_periods(cid=cid,page=page,order=order) return render_template( 'new_list.html', periods=periods,order=order,cid=cid,current_cate=current_cate)
def new_category(): form = CategoryForm() if form.validate_on_submit(): name = form.name.data category = Category(name=name) db.session.add(category) db.session.commit() flash('Category created.', 'success') return redirect(url_for('.manage_category')) return render_template('admin/new_category.html', form=form)
def test_retrieve_categories_as_dict(self): Category.query.delete() cat = Category(type='temp') self.db.session.add(cat) self.db.session.commit() res = self.client().get('/api/categories') res = json.loads(res.data) categories = res['categories'] for k in categories.keys(): self.assertEqual(categories[k], 'temp')
def delete(self, id): category = Category.get_or_404(id) try: category.delete(category) response = make_response() return response, status.HTTP_204_NO_CONTENT except SQLAlchemyError as e: db.session.rollback() resp = jsonify({'error': str(e)}) return resp, status.HTTP_401_UNAUTHORIZED
def test_relationship_categories(self): """Test categories and user_categories relationship (many-to-many)""" category = Category.new("General") user_category = UserCategory.new(self.user1.id, category.id) with self.subTest(): self.assertIn(category, self.user1.categories) with self.subTest(): self.assertIn(user_category, self.user1.users_categories)
def edit_categories(): categories = Category.public() notes = utils.notesPerCategory(categories) return flask.render_template( "categories.html", categories=categories, notes=notes, )
def newCatagory(): """Creates a new catagory. """ if request.method == 'POST': newCategory = Category(name=request.form['name']) session.add(newCategory) session.commit() return redirect(url_for('showCategories')) else: return render_template('newCategory.html')
def create_post(): # https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/ post_category = Category(name='Python') Post(title='Hello Python!', body='Python is pretty cool', category=post_category) post = Post(title='Snakes', body='Ssssssss') post_category.posts.append(post) db.session.add(post_category) db.session.commit()
def new_category(): if request.method == 'POST': category = Category(name=request.form['category']) db.session.add(category) db.session.commit() return redirect('/') else: return render_template( 'new-category.html', page='new-category.html')
def delete_full_botlist(self): all_cats = Category.select_all() start = all_cats[0].current_message_id - 3 # Some wiggle room and GIF end = all_cats[-1].current_message_id + 4 # Some wiggle room self.notify_admin("Deleting all messages...") for m in range(start, end): try: self.bot.delete_message(self.channel.chat_id, m) except BadRequest as e: pass
def populate_db(): session = Session() categories = [ 'gold', 'toman', ] session.add_all([Category(name=name) for name in categories]) session.commit()
def edit_category(key): category = Category.get(key) expiration = "" if category.expiration: expiration = category.expiration.strftime("%m/%d/%Y") if category.owner != users.get_current_user(): error = "You cannot edit a category that you do not own!" return render_template('errors.html',error=error) items = Item.all().ancestor(category) return render_template('edit_category.html', items=items, count=items.count(), key=key, title=category.title, owner=category.owner.email(), expiration=expiration)
def create_category(payload): body = request.get_json() name = body.get('name', None) try: category = Category( name=name ) category.insert() return jsonify({ 'success': True, 'code': 200, 'created': category.format() }) except exc.SQLAlchemyError as sql_err: print(sql_err) abort(422)
def addCategory(): # Add a new Category. name = request.json.get('name') picture = request.json.get('picture') newCateg = Category(name=name, picture=picture) session = DBSession() session.add(newCateg) session.commit() return redirect('/', 200)
def save(self): """Save data in target table.""" if self.table == "Category": Category(self.db).insert_query(self.elements) elif self.table == "Brand": Brand(self.db).insert_query(self.elements) elif self.table == "Store": Store(self.db).insert_query(self.elements) elif self.table == "Product": Product(self.db).insert_query(self.elements)
def del_category_tag_lib(c_uuid, t_uuid): if c_uuid is not None: category = Category.by_uuid(c_uuid) category.delete() return {'status': True, 'msg': u'分类删除成功'} if t_uuid is not None: tag = Tag.by_uuid(t_uuid) tag.delete() return {'status': True, 'msg': u'标签删除成功'} return {'status': False, 'msg': u'参数不能为空'}
def add_category(): data = request.get_json() #data = json.loads(request.data.decode('utf-8')) #print(data) new_type = data.get('type', None) print(new_type) if (new_type == None): abort(422) try: new_category = Category(type=new_type) Category.insert(new_category) print("Inserted!") return jsonify({'success': True, 'created': new_category.id}) except Exception as e: print(e) abort(405)
def put_categories(request, id, category: CategoryBasic): category = category.dict() category["id"] = id try: category = CategoryUpdate(**category) except Exception as e: return jsoinify_error(e) category_record = Category.query().get(category.id) category_record.update(**category.dict()) return {"suucess": True, "category": category_record.deep()}
def GetCategories(): query = "SELECT * FROM CATEGORY" result = cur.execute(query) data = cur.fetchall() categories = [] for record in data: c = Category(record[0], record[1], record[2]) categories.append(c) return categories
def post_category(): body = request.get_json() new_type = str(body.get('type', None)) categories = Category.query.all() catgs = {cat.id: cat.type for cat in categories} try: new_category = Category(type=new_type) new_category.insert() categories = Category.query.all() catgs = {cat.id: cat.type for cat in categories} return jsonify({ 'success': True, 'categories': catgs, 'totalCategories': len(Category.query.all()) }) except: abort(422)
def test_retrieve_categories(self): cat1 = Category(type='type1') cat1.insert() cat2 = Category(type='type2') cat2.insert() res = self.client().get('/categories') data = json.loads(res.data) self.assertEqual(res.status_code, 200) self.assertTrue(data['success']) self.assertTrue(data['categories'])
def get_categories(): categories = Category.query.order_by(Category.type).all() if len(categories) == 0: not_found(404) return jsonify({ 'success': True, 'categories': Category.toDict(categories) })
def save_categories(request, slug): if request.method == 'POST': post = get_object_or_404(request.site['posts'], slug=slug) categories = request.POST['value'] post['categories'].delete() for category in categories.split(","): category, created = Category.query().get_or_create( name=category.strip().lower()) post['categories'].get_or_create(category=category) return HttpResponse(post.get_categories())
def post(self): args = parser.parse_args() print("printing args in new category") print(args) print(g.user.username) new = Category(args['categoryValue'], args['categoryName'], g.user.username) #add category to the database db.session.add(new) db.session.commit() return args, 201
def export_xml(key): category = Category.get(key) items = Item.all().ancestor(category) disposition_filename = category.title + "_" + category.owner.email() + ".xml" root = Element('CATEGORY') SubElement(root,'NAME').text = category.title for item in items: i = SubElement(root,'ITEM') SubElement(i,'NAME').text = item.title return Response(tostring(root),status=200,mimetype="application/xml",headers={"Content-Disposition":"attachment;filename="+disposition_filename})
def add_item(): """ add_item: Add new item to database Args: - Returns: If method is POST, redirect back to show_items.html, if method is GET, show the add_item.html template """ logged_in = True if request.method == 'POST': name = request.form['name'] description = request.form['description'] category = request.form['category'] new_category = request.form['new_category'] category_id = '' if category == 'new_category_option': # Create new category item category = new_category c = Category(name=category) session.add(c) session.commit() item_category = session.query(Category).filter_by( name=category).one() category_id = item_category.id category = item_category.name else: old_category = session.query(Category).filter_by( id=category).one() category_id = old_category.id category = old_category.name item = Item() item.name = name item.description = description item.category = category_id # Get the current user username = login_session['username'] user = session.query(User).filter_by(username=username).one() item.creator_id = user.id session.add(item) session.commit() return redirect(url_for('show_items', logged_in=logged_in, category=category)) else: categories = session.query(Category).all() return render_template("add_item.html", logged_in=logged_in, categories=categories)
def setUp(self): self.client = app.test_client() db.drop_all() db.create_all() c1 = Category( category_id=0, category_label="Technical Issue" ) p1 = Priority( priority_id=1, priority_label="Medium" ) s1 = Status( status_id=0, status_label="Submitted" ) ro1 = Role( role_id=0, role_label="user" ) ro2 = Role( role_id=1, role_label="assignee" ) ro3 = Role( role_id=2, role_label="admin" ) db.session.add_all([c1,p1,s1,ro1,ro2,ro3]) db.session.commit() User.query.delete() Issue.query.delete() user1 = User.register(**TEST_USER1) user2 = User.register(**TEST_USER2) user1.role = 2 db.session.add_all([user1,user2]) db.session.commit() issue1 = Issue(title="Test Issue 1", text="Issue 1 description", reporter=user1.id) issue2 = Issue(title="Test Issue 2", text="Issue 2 description", reporter=user2.id) db.session.add_all([issue1,issue2]) db.session.commit() comment1 = Comment(comment_text="This is a comment", comment_user=2, comment_issue=2) db.session.add(comment1) db.session.commit()
def handle_categories(): try: if request.method == 'GET': try: selection = Category.query.order_by('id').all() result = [item.format for item in selection] if not result: abort(400) return jsonify({ 'success': True, 'categories': result, 'total_categories': len(Category.query.all()) }) except(): abort(500) if request.method == 'POST': error = False data = request.get_json() new_category = Category( type=data.get('type', None), ) if not new_category.type: abort(400) # check if existed duplicate_category = Category.query.filter(Category.type == new_category.type).all() if bool(duplicate_category): abort(409) try: db.session.add(new_category) db.session.commit() except(): error = True print(sys.exc_info()) abort(400) selection = Category.query.order_by('id').all() result = [item.format for item in selection] return jsonify({ 'success': True, 'created': new_category.id, 'category created': new_category.type, 'categories': result, 'total_categories': len(Category.query.all()) }), 201 except(): abort(500)
def quiz(): """Start New Quiz""" if request.method == "POST": category_form = request.form['category'] num_questions = request.form['num_Questions'] num_correct_answers = request.form['num_correct_answers'] if Category.query.filter_by(name=category_form).first(): cat = Category.query.filter_by(name=category_form).first() user = g.user if User_Category.query.filter_by(user_id=user.id, category_id=cat.id).first(): user_cat = User_Category.query.filter_by( user_id=user.id, category_id=cat.id).first() user_cat.quizzes_taken += 1 user_cat.questions_answered += int(num_questions) user_cat.correct_answers += int(num_correct_answers) db.session.commit() return redirect(f'/user/{user.id}') user_cat = User_Category(user_id=user.id, category_id=cat.id, quizzes_taken=1, questions_answered=num_questions, correct_answers=num_correct_answers) db.session.add(user_cat) db.session.commit() else: category = Category(name=category_form) db.session.add(category) db.session.commit() cat = Category.query.filter_by(name=category_form).first() user = g.user user_cat = User_Category(user_id=user.id, category_id=cat.id, quizzes_taken=1, questions_answered=num_questions, correct_answers=num_correct_answers) db.session.add(user_cat) db.session.commit() return redirect(f'/user/{user.id}') form = NewQuiz() return render_template('quiz.html', form=form, user=g.user)
def test_search_question(self): #Create a category so it can be referenced by newly inserted questions cat = Category('Mystery') cat.insert() #prepare Question attributes answer = "yes" diff = 0 #prepare a question that should not be in the result not_a_target = Question( 'Will I be found using the chosen search term?', 'No', cat.id, diff).format() #prepare questions that are to be expected in the result question_strings = [ 'can you this find that?', 'where is THIS?', 'who is tHiS' ] target_questions = [ Question(s, answer, cat.id, diff) for s in question_strings ] for q in target_questions: q.insert() expected_res = [q.format() for q in target_questions] term = "this" res = self.client().post('/questions/search', json={'searchTerm': term}) data = json.loads(res.data) try: result_questions = data['questions'] count = data['total_questions'] self.assertTrue(result_questions) self.assertEqual(count, len(expected_res)) # assert that resulst are the same as the created questions for res_question in result_questions: self.assertTrue(res_question in expected_res) # assert that the question that does not include the search term is not in the result self.assertFalse(not_a_target in result_questions) except: for q in target_questions: q.delete()