def insert_category(category): a = Categories.select(Categories.name).where(Categories.name == category) if not a.exists(): id_company = random.randint(0, 7000000) Categories.create(id=id_company, name=category) return 'Done' return 'Genre already exists'
def post(self): user = users.get_current_user() c = Categories(name=self.request.get('name'), amount=float(self.request.get('amount'))) c.put() logging.info('************ ' + user.nickname() + ' Added Category ' + c.name + ' *******') return webapp2.redirect('/view_categories')
def edit_post(id): form = PostForm() if users.is_current_user_admin() and form.validate_on_submit(): try: tags = Tags() categories = Categories() updating_post = BlogPost.get(int(id)) title = request.json['title'] body = request.json['body'] raw_category = request.json['category'] editing_tags = request.json['tags'] raw_summary = request.json['summary'] tags_keys = tags.update(editing_tags, updating_post) category_key = categories.update(raw_category, updating_post.category) updating_post.edit(title, body, datetime.now(), tags_keys, category_key, raw_summary, raw_answers=request.json['answers']) except AttributeError: abort(500) return jsonify(updating_post.to_json()) # dangerous
def edit_post(id): form = PostForm() if users.is_current_user_admin() and form.validate_on_submit(): tags = Tags() categories = Categories() updating_post = BlogPost.get(int(id)) title = request.json['title'] body = request.json['body'] raw_category = request.json['category'] editing_tags = request.json['tags'] raw_summary = request.json['summary'] tags_keys = tags.update(editing_tags, updating_post) category_key = categories.update(raw_category, updating_post.category) updating_post.edit(title, body, datetime.now(), tags_keys, category_key, raw_summary, raw_answers=request.json['answers']) return jsonify(updating_post.to_json()) # dangerous
def add_new_category(): body = json.loads(request.data) name = body.get('name', None) if name is None: return jsonify({'error': 'name cannot be null'}) description = body.get('description', None) new_category = Categories(name=name, description=description) db.add(new_category) return jsonify({'result': new_category._dump()})
def delete_category(category): query = Categories.select( Categories.name).where(Categories.name == category) if query.exists(): get_save_id = Categories.select( Categories.id).where(Categories.name == category) Categories.delete().where(Categories.name == category).execute() MoviesCategory.delete().where( MoviesCategory.movie_id == get_save_id).execute() return 'DONE' return "Genre doesnt exists"
def main(): if users.is_current_user_admin(): if request.method == 'GET': #all entitites posts = Posts() return jsonify(posts.to_json()) elif request.method == "POST": form = PostForm() if form.validate_on_submit(): #new entity posts = Posts() categories = Categories() tags = Tags() raw_post = request.get_json() raw_category = raw_post["category"] editing_tags = raw_post["tags"] raw_summary = raw_post["summary"] tag_keys = tags.update(editing_tags) category_key = categories.update(raw_category) post_id = posts.add(raw_title=raw_post["title"], raw_body=raw_post["body"], category_key=category_key, tags_ids=tag_keys, summary=raw_summary, answers=raw_post["answers"]).id() post = BlogPost.get(post_id) if "images" in raw_post.keys() and raw_post["images"]: for img in raw_post["images"]: image_base64 = img["url"].split("base64,")[-1] mime_type = img["url"].split("base64,")[0].replace( 'data:', '').replace(';', '') image_filename = img["filename"].split("\\")[-1] if allowed_file(image_filename): image_filename = secure_filename(image_filename) post.add_blob(base64.b64decode(image_base64), image_filename, mime_type) return jsonify(post.to_json()) # Needs check else: return jsonify(msg="missing token") else: return jsonify({})
def edit_category(): cat = Categories.get_by_id(ctx.request['_id']) return dict( \ form_title='Edit Category', \ form_action='/api/categories/%s/update' % cat._id, \ name = cat.name, \ description = cat.description)
def edit_user_activity(token_info: dict, activity_id: str) -> Tuple[Response, int]: data = request.get_json() category = Categories.get_specific_category(data.pop("category_id")) start = _parse_to_utc_iso8610(data["activity_start"]) end = _parse_to_utc_iso8610(data["activity_end"]) data.update(category=category) data.update( duration=_calculate_duration_in_mins( start, end ) ) data["activity_start"] = start data["activity_end"] = end updated_activity = Activities.edit_specific_activity(activity_id, **data) print(updated_activity) return jsonify({"message": f"Activity {activity_id} successfully updated."}), 200
def addCategory(request): try: text="" user=request.session['username'] #session tracking if request.method == 'POST': catg = request.POST['category'] url = request.POST['url'] if 'http://in.reuters.com/news/archive/' in url: data = Categories(category=catg ,link=url) data.save() #save the category details if the link is of reuters archive type text = "Category added to the Mailing List" else: text = "Currently only 'http://in.reuters.com/news/archive/...' type of URL are allowed" return render(request, "CRM/Admin/addCategory.html",{'message':text}) except: return HttpResponseRedirect('/CRM/adminLogin')
def get(self, goal_id): user = users.get_current_user() iden = int(goal_id) cats = Categories.all().filter('owner =', user).order('name') goal = db.get(db.Key.from_path('Goals', iden)) db.delete(goal) logging.info('************ ' + user.nickname() + ' Deleted Goal ' + goal.name + ' *******') return webapp2.redirect('/view_goals')
def _calculate_category_duration(user_id: str, category_id: str) -> float: category = Categories.get_specific_category(category_id=category_id) activities = Activities.objects(user_id=user_id, category=category).exclude("id") sum_duration = sum([activity.duration for activity in activities]) return sum_duration
def get(self, goal_id): user = users.get_current_user() cats = Categories.all().filter('owner =', user).order('name') nickname = user.nickname() logging.info('************ ' + user.nickname() + ' on Edit Category *******') iden = int(goal_id) goal = db.get(db.Key.from_path('Goals', iden)) self.render_template('edit_goal.html', {'goal': goal,'cats':cats,'nickname':nickname},)
def web_get_article(aid): article = Articles.get_by_id(aid) if article is None or article.draft: raise notfound article.reads = counters.incr(aid) article.content = texts.md2html(texts.get(article.content_id)) category = Categories.get_by_id(article.category_id) return dict(article=article, category=category, comments=comments.get_comments(aid))
def api_delete_category(cid): cat = Categories.get_by_id(cid) if cat is None: raise APIValueError('_id', 'category not found.') if len(Articles.select('where category_id=?', cat._id)) > 0: raise APIValueError('_id', 'cannot delete non-empty categories.') cat.delete() _clear_categories_cache() return dict(result=True)
def addCategory(request): try: text = "" user = request.session['username'] #session tracking if request.method == 'POST': catg = request.POST['category'] url = request.POST['url'] if 'http://in.reuters.com/news/archive/' in url: data = Categories(category=catg, link=url) data.save( ) #save the category details if the link is of reuters archive type text = "Category added to the Mailing List" else: text = "Currently only 'http://in.reuters.com/news/archive/...' type of URL are allowed" return render(request, "CRM/Admin/addCategory.html", {'message': text}) except: return HttpResponseRedirect('/CRM/adminLogin')
def load_new_categories(self, site_updated, number=None): print "Loading a new category listing" try: jcat = self.tm.categories(category=number, with_counts="true") cat = json.loads(jcat) pcat = pickle.dumps(cat) c = Categories.objects.get(number=number) c.last_updated = site_updated c.categories=pcat c.save() except Categories.DoesNotExist as e: c = Categories(categories=pcat, last_updated=site_updated, name=cat["Name"],number=cat["Number"]) c.save() except: print "Couldn't fetch new categories", sys.exc_info()[0], number cat = None return cat
def delete_post(id): if users.is_current_user_admin(): posts = Posts() tags = Tags() categories = Categories() updating_post = BlogPost.get(int(id)) categories.delete(updating_post.category) posts.delete(updating_post.key) tags.update([]) return jsonify(msg="OK")
def delete_post(id): if users.is_current_user_admin(): posts = Posts() tags = Tags() categories = Categories() updating_post = BlogPost.get(int(id)) categories.delete(updating_post.category) posts.delete(updating_post.key) tags.update(updating_post.get_tag_names()) return jsonify(msg="OK")
def get(self): user = users.get_current_user() nickname = user.nickname() logging.info('************ ' + user.nickname() + ' on View Categories*******') if user: cats = Categories.all().filter('owner =', user).order('name') self.render_template('view_categories.html', {'cats': cats,'nickname':nickname},) else: self.redirect(users.create_login_url(self.request.uri))
def web_category(cid): category = Categories.get_by_id(cid) if category is None: raise notfound() page, articles = page_select(Articles, 'where category_id=? and publish_time<?', 'where category_id=? and publish_time<? order by publish_time desc', cid, time.time()) reads = counters.counts((a._id for a in articles)) for a, r in zip(articles, reads): a.reads = r return dict(category=category, page=page, articles=articles)
def pregame(): """Let the user choose one out of two random categories.""" # "GET" method if request.method == "GET": # if table is empty, insert values if Categories.query.get(1) is None: # generate two different random categories firstcat = randomcategory() secondcat = randomcategory() while firstcat == secondcat: secondcat = randomcategory() # update database with new categories randomcats = Categories(firstcat, secondcat) db.session.add(randomcats) db.session.commit() # update the table otherwise else: # generate two different random categories Categories.query.get(1).firstcat = randomcategory() Categories.query.get(1).secondcat = randomcategory() while Categories.query.get(1).firstcat == Categories.query.get(1).secondcat: Categories.query.get(1).secondcat = randomcategory() db.session.commit() # query for categories cats = Categories.query.get(1) return render_template("pregame.html", cats=cats) # "POST" method else: # if the first category was chosen if request.form.get("cat") == "1": if Choice.query.get(1) is None: keuze = Choice(Categories.query.get(1).firstcat) db.session.add(keuze) db.session.commit() Choice.query.get(1).choice = Categories.query.get(1).firstcat db.session.commit() return redirect(url_for("question")) # if the second category was chosen if request.form.get("cat") == "2": if Choice.query.get(1) is None: keuze = Choice(Categories.query.get(1).secondcat) db.session.add(keuze) db.session.commit() Choice.query.get(1).choice = Categories.query.get(1).secondcat db.session.commit() return redirect(url_for("question"))
def itemAdd(): if request.method == 'GET': items = session.query(Categories).all() return render_template('take.html', items=items) elif request.method == 'POST': category = request.form['category'] newCategory = Categories(name=category) session.add(newCategory) session.commit() return redirect(url_for('itemAdd'))
def product_view(): this_route = url_for('.product_view') if 'email' not in session: app.logger.info("Must have session key to view {}".format(this_route)) return redirect(url_for('login')) form = SearchForm() c = Categories() categories = c.return_categories() p = Product_details() id = request.args.get('id', '') product_details = p.return_product(id) return render_template('product.html', product_info=product_details, form=form, categories=categories)
def createCategory(): if request.method == 'POST': category = Categories(category=request.form['category'], user_id=login_session['id']) session.add(category) session.commit() flash('succesfully added category %s' % request.form['category']) return redirect(url_for('showItems', category=request.form['category'])) # if get request return render_template('newCategory.html')
def web_category(cid): category = Categories.get_by_id(cid) if category is None: raise notfound() page, articles = page_select( Articles, 'where category_id=? and publish_time<?', 'where category_id=? and publish_time<? order by publish_time desc', cid, time.time()) reads = counters.counts((a._id for a in articles)) for a, r in zip(articles, reads): a.reads = r return dict(category=category, page=page, articles=articles)
def newCategory(): """add new category""" categories = session.query(Categories).all() if request.method == 'POST': newCategory = Categories(name=request.form['name'], user_id=login_session['user_id']) session.add(newCategory) session.commit() flash("New category is added %s " % newCategory.name) return redirect(url_for('showCatalog')) else: return render_template('addCategory.html', categories=categories)
def api_create_category(): ''' Create a new category. ''' i = ctx.request.input(name='', description='') name = assert_not_empty(i.name, 'name') description = i.description.strip() c = Categories(name=name, description=description, display_order=len(_get_categories())).insert() _clear_categories_cache() return c
def addCategory(): # to add a new category if login_session.get('username'): if request.method == "POST": category = Categories(name=request.form.get('name')) session.add(category) session.commit() return redirect(url_for('showMain')) else: return render_template('newCategory.html') else: return redirect(url_for('showLogin'))
def post(self, goal_id): user = users.get_current_user() iden = int(goal_id) cats = Categories.all().filter('owner =', user).order('name') goal = db.get(db.Key.from_path('Goals', iden)) goal.name = self.request.get('name') goal.category = self.request.get('id_cat') goal.amount = float(self.request.get('amount')) goal.updated = datetime.now() goal.put() logging.info('************ ' + user.nickname() + ' Updated Goal ' + goal.name + ' *******') return webapp2.redirect('/view_goals')
def addCategoryDB(category): print("Inside add category, the category object received:", category) print("Name of the category object:", category.getCategoryName()) existing = Categories.query.filter_by( categoryName=category.getCategoryName()).first() print("Any existing category of same name:", existing) if (existing): return False newCategory = Categories(category.getCategoryName(), 0) db.session.add(newCategory) db.session.commit() return True
def add_records_to_database(app, database_path): ''' function to add data to the database ''' # generate randomness seed(1) # set up database setup_db(app, database_path) # add data to Categories categories = ['Verb', 'Substantiv', 'Adjektive', 'Adverb'] for category in categories: new_cate = Categories(category) new_cate.insert() # add data to Dictionary user_ids = [ 'google-oauth2|104536530909866680796', 'auth0|5ff8909c8efe020068c0c1d5', 'google-oauth2|104536530909866680796' ] example_words = ['Stockholm', 'nifiken', 'Svenska', 'lathunde', 'Studera'] example_cate = [2, 3, 2, 2, 1] for user_id in user_ids: for word, category in zip(example_words, example_cate): A_random_value = 'random value' + str(randint(0, 100)) new_word = Dictionary(user_id, word, category, meaninginenglish=A_random_value) new_word.insert() # for each user, add a random answer record for user_id in user_ids: answer = True questions_user = Dictionary.query.\ filter(Dictionary.user_id == user_id).all() for question in questions_user: newanswer_record = AnswerRecords(question.id, user_id, answer) newanswer_record.insert()
def main(): if users.is_current_user_admin(): if request.method=='GET': #all entitites posts = Posts() return jsonify(posts.to_json()) elif request.method == "POST": form = PostForm() if form.validate_on_submit(): #new entity posts = Posts() categories = Categories() tags = Tags() raw_post = request.get_json() raw_category = raw_post["category"] editing_tags = raw_post["tags"] raw_summary = raw_post["summary"] tag_keys = tags.update(editing_tags) category_key = categories.update(raw_category) post_id = posts.add(raw_title=raw_post["title"], raw_body=raw_post["body"], category_key=category_key, tags_ids=tag_keys, summary=raw_summary, answers=raw_post["answers"]).id() post = BlogPost.get(post_id) return jsonify(post.to_json()) # Needs check else: return jsonify(msg="missing token") else: return jsonify({})
def add_category(): form = CategoryAddForm() if form.validate_on_submit(): new_category = Categories(name=form.category_name.data) # Add to retrieve the category ID. db.session.add(new_category) db.session.commit() # With this ID, write the thumbnail. write_category_thumbnail(new_category.category_id, form.thumbnail.data.read()) return redirect(url_for("list_categories")) return render_template("category_add.html", form=form)
def api_update_category(cid): cat = Categories.get_by_id(cid) if cat is None: raise APIValueError('_id', 'category not found.') i = ctx.request.input() update = False if 'name' in i: cat.name = assert_not_empty(i.name.strip(), 'name') update = True if 'description' in i: cat.description = i.description.strip() update = True if update: cat.update() _clear_categories_cache() return dict(result=True)
def _get_specific_category(category_id: str) -> str: try: (category,) = Categories.objects(public_id=category_id) except ValueError as e: if ( len(e.args) > 0 and e.args[0] == "not enough values to unpack (expected 1, got 0)" ): raise ValueError( f"Category with id={category_id} does not exist in the Database" ) from e else: raise e return category
def get_single_category(id): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute( """ SELECT c.id, c.label FROM Categories c WHERE c.id = ? """, (id, )) dataset = db_cursor.fetchone() category = Categories(dataset['id'], dataset['label']) return json.dumps(category.__dict__)
def get_all_categories(): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT c.id, c.label FROM Categories c ORDER by label """) categories = [] dataset = db_cursor.fetchall() for row in dataset: category = Categories(row['id'], row['label']) categories.append(category.__dict__) return json.dumps(categories)
def home(): user = login_session.get('user', None) # user = session.merge(user) categories = session.query(Categories).all() category = Categories() items = session.query(Items).all() if user is None: return render_template('categories.html', categories=categories, items=items, category=category, login=loginLabel['login']) else: return render_template('categories.html', categories=categories, items=items, category=category, login=loginLabel['logout'])
def save(): category = request.form['category'] old_category = Categories.query.filter(Categories.name == category).first() #validation error = None if category is None: error = 'Category field is required.' elif old_category is not None: error = '{} already exist in database'.format(category) print(error) if error is None: c = Categories(name=category) db_session.add(c) db_session.commit() return redirect(url_for('category.new')) return "ERROR"
def create_activity(token_info: dict) -> Tuple[Response, int]: data = request.get_json() start = _parse_to_utc_iso8610(data["activity_start"]) end = _parse_to_utc_iso8610(data["activity_end"]) activity_id = str(uuid.uuid4()) category = Categories.get_specific_category(data["category_id"]) duration = _calculate_duration_in_mins(start, end) Activities( activity_id=activity_id, name=data["name"], user_id=token_info["public_id"], activity_start=start, activity_end=end, category=category, duration=duration, ).save() return jsonify({"activity_id": activity_id}), 200
def _get_categories(): return Categories.select('order by display_order')
def _check_category_id(cat_id): if cat_id: cat = Categories.get_by_id(cat_id) if cat: return cat_id raise APIValueError('category_id', 'Invalid category id.')
def get(self): user = users.get_current_user() cats = Categories.all().filter('owner =', user).order('name') logging.info('************ ' + user.nickname() + ' on Add Goal *******') nickname = user.nickname() self.render_template('add_goal.html', {'cats':cats,'nickname':nickname})
def save(request, form, image, saveType, url = None): #Loads an instace of FileSystemStorage store = FileSystemStorage(paths.SITE_ROOT + '/images/') if image: #Checks if an image already exists #If it does, use that image as the url #Else save the image, and create a url if store.exists(image.name): imageURL = '/images/' + image.name featuredImage = imageURL logging.basicConfig(filename=paths.SITE_ROOT + '/output.log', level=logging.DEBUG) logging.debug("EXISTS") else: storedImage = store.save(image.name, image) imageURL = "/images/" + storedImage featuredImage = imageURL else: imageURL = None featuredImage = None if form.is_valid(): if saveType == "Post": if url: #If the post is being edited, delete the older version published = Post.objects.get(pk=url).published Post.objects.get(pk=url).delete() posts = Categories.objects.filter(Post__id = url) for i in posts: i.delete() featured = Featured.objects.filter(Post__id = url) if featured: featured.delete() else: published = datetime.datetime.now() month = published.month if month < 10: newmonth = '0' + str(month) else: newmonth = str(month) #Create a post with the correct information title = request.POST['title'] linkTitle = title.replace(' ', '-').lower() exclude = ['$', '#', '&', ';', ',', '"', '?'] linkTitle = ''.join(ch for ch in linkTitle if ch not in exclude) link = str(published.year) + '/' + newmonth + '/' + linkTitle + '/' if not 'imageInPost' in request.POST: imageURL = None else: if not imageURL: return "You didn't upload an image.", None post = Post(title = request.POST['title'], sourceUrl = request.POST['sourceUrl'], image = imageURL, content = request.POST['content'], published = published, link = link) post.save() if 'featured' in request.POST: if not featuredImage: return "You need an image", post featured = Featured(Post = post, box = 1, imageURL = featuredImage) featured.save() if 'categories' in request.POST: categories = request.POST.getlist('categories') for category in categories: newCategory = Categories(Post = post, category = category) newCategory.save() return None, post else: return "Something is amiss", post elif saveType == "Page": if url: #If the post is being edited, delete the older version Page.objects.get(title=url).delete() #Create a post with the correct information page = Page(title = request.POST['title'], image = imageURL, content = request.POST['content']) page.save() return None else: return "Something is amiss...", None