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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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()
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import Base, Categories, Items # Connect to Database and create database session engine = create_engine('sqlite:///ItemCatalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() #Run this only once, to avoid repetition #You can Add more Categories category1 = Categories(name='food') category2 = Categories(name='clothes') category3 = Categories(name='sports') category4 = Categories(name='news') category5 = Categories(name='stories') category6 = Categories(name='movies') session.add(category1) session.add(category2) session.add(category3) session.add(category4) session.add(category5) session.add(category6) session.commit() print 'Categories Added!' categories = session.query(Categories).all()
def home(): this_route = url_for('.home') if 'email' not in session: app.logger.info( "Can't visit home page without session key {}".format(this_route)) return redirect(url_for('login')) form = SearchForm() c = Categories() categories = c.return_categories() p = Products() pagination = request.args.get('query') category = request.args.get('category') if pagination != None: page = request.args.get('page') catid = request.args.get('catid') products = p.search_query(pagination, catid, page) pages = products.pop(-1) app.logger.info("Viewed pagination {}, {}".format(page, cat_id)) return render_template('home.html', form=form, products=products, categories=categories, pages=pages, query=pagination, cat_id=catid) elif category != None: #products = p.search_query("", ) count = 0 for cat in categories: for each in cat: if count == 0: if category == each['category']: products = p.search_query("", each['cat_id'], 0) pages = products.pop(-1) app.logger.info("Category select({})".format(category)) return render_template('home.html', form=form, products=products, categories=categories, pages=pages, cat_id=each['cat_id']) else: if category == each['subcat']: products = p.search_query("", each['sub_id'], 0) pages = products.pop(-1) app.logger.info("Category select({})".format(category)) return render_template('home.html', form=form, products=products, categories=categories, pages=pages, cat_id=each['sub_id']) count += 1 count = 0 if request.method == "POST": if form.validate() == False: app.logger.info( "Logging a test message from {}".format(this_route)) return render_template("home.html", form=form, categories=categories) else: query = form.query.data cat_id = request.form.get("choices-single-defaul") products = p.search_query(query, cat_id, 0) #categories = c.return_categories() pages = products.pop(-1) app.logger.info( "Logging a test message from {}product_search({})".format( this_route, query)) return render_template('home.html', form=form, products=products, categories=categories, pages=pages, query=query, cat_id=cat_id) elif request.method == 'GET': app.logger.info("Logging a test message from {}".format(this_route)) return render_template('home.html', form=form, categories=categories)
# Criação do banco de dados para o APP from __future__ import absolute_import, unicode_literals from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from models import Base, Categories, Items, Users engine = create_engine("sqlite:///catalog.db", connect_args={"check_same_thread": False}) DBSession = sessionmaker(bind=engine) session = DBSession() # Categorias que serão criadas no banco de dados categories = ["TVs", "Smartphones", "Notebooks", "Games"] results = session.query(Categories).all() if not results: for c in categories: category = Categories(name=c) session.add(category) session.commit() print "Sessões Criadas" else: print "Sessão já existente" results = session.query(Categories).all() print "\nCategories:\n" for r in results: print "%s - %s" % (r.id, r.name)
category = Categories.query.get(id) return render_template("category.html", category=category) @app.route("/product/<id>") def product(id): try: id = int(id) except: flash("No Such Product Found") return redirect(url_for("index")) if not Products.query.get(id): flash("No Such Product Found") return redirect(url_for("index")) product = Products.query.get(id) return render_template("product.html", product=product) if __name__ == "__main__": if not os.path.exists('main.db'): db.create_all() db.session.add(Users("Hassaan Ali Wattoo", "test", "test")) for i in range(0, 20): db.session.add(Categories(faker.company())) db.session.commit() port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
# -*- coding: utf-8 -*- from models import Categories, Product, db from visitnorwaydata import visitnorway, categories for x in categories: cat = Categories() cat.id = x['id'] cat.name = x['name'] db.session.add(cat) db.session.commit() for x in visitnorway: if x['geoLocation'] != None: cat = Categories.query.filter_by( name=x['categories'][0]['name']).first() prod = Product() prod.id = x['id'] prod.name = x['name'] prod.lat = x['geoLocation']['latitude'] prod.long = x['geoLocation']['longitude'] prod.image = None prod.alternativeText = None if x['image'] != None: prod.image = x['image']['url'] prod.alternativeText = x['image']['alternativeText'] prod.categories = cat db.session.add(prod) db.session.commit()
# and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() User1 = User(name="Fake User", email="*****@*****.**", picture='https://www.communitylandtrust.ca/' 'wp-content/uploads/2015/10/placeholder.png') session.add(User1) session.commit() category1 = Categories(user_id=1, season="Winter") session.add(category1) session.commit() winter_sport1 = Sports( user_id=1, name="Slope Style", description= "Slopestyle is a winter sport in which athletes ski or snowboard down a course including a variety of obstacles.", description_link="https://en.wikipedia.org" "/wiki/Slopestyle", image_link="https://images.unsplash.com" "/photo-1508244898853-0ceb7788a86a" "?ixlib=rb-1.2.1" "&ixid=eyJhcHBfaWQiOjEyMDd9"
def __init__(self, database_path: str) -> None: self.engine = create_engine(f"sqlite:///{database_path}") self.session = sessionmaker(bind=self.engine)() Repository.create_database(self.engine) @staticmethod def create_database(engine: Engine) -> None: Base.metadata.create_all(engine) if __name__ == "__main__": repository = Repository(DATABASE_PATH) repository.session.add( Categories(name="Продукты", description="Категория продуктов")) repository.session.add(Units(unit="pcs")) repository.session.add(Units(unit="kg")) repository.session.add(Units(unit="lb")) repository.session.add(Positions(position="Manager")) repository.session.add(Positions(position="Admitistrator")) repository.session.add(Ownerships(ownership="Sole")) repository.session.add(Ownerships(ownership="General")) repository.session.add(Ownerships(ownership="Corporation")) repository.session.add(Ownerships(ownership="Limited Liability Company")) repository.session.add(Ownerships(ownership="Limited Partnership")) repository.session.add( Ownerships(ownership="Limited Liability Partnership"))
def add_categories(): body = json.loads(request.data) category_name = body.get('name', None) category = Categories(name=category_name) db.add(category) return jsonify({'result': category._dump()}) , 200
session = DBSession() # Delete Categories if exisitng. session.query(Categories).delete() # Delete Items if exisitng. session.query(Items).delete() # Delete Users if exisitng. session.query(User).delete() User1 = User(name="Ibrahim Ashraf", email="*****@*****.**", picture='http://dummyimage.com/200x200.png/ff4444/ffffff') session.add(User1) session.commit() category1 = Categories(name='Soccer', user_id=1) session.add(category1) session.commit() Category2 = Categories(name="Football", user_id=1) session.add(Category2) session.commit() item1 = Items(name='Soccer Cleats', date=datetime.datetime.now(), description="""Soccer shoes, soccer cleats, soccer boots whatever the name, most of the time a soccer shoe is a firm ground soccer shoe. Firm ground is the classic soccer shoe with cleats/studs designed to provide traction and stability on most natural grass, outdoor soccer fields""",
# and represents a "staging zone" for all the objects loaded into the # database session object. Any change made against the objects in the # session won't be persisted into the database until you call # session.commit(). If you're not happy about the changes, you can # revert all of them back to the last commit by calling # session.rollback() session = DBSession() # Create dummy user User1 = User(username="******", email="*****@*****.**") User1.password_hash = User1.hash_password('Pan') session.add(User1) session.commit() # Category Soccer category1 = Categories(user_id=1, name="Soccer") session.add(category1) session.commit() category1_item1 = CategoryItem( name="Balls", description="A football is a ball inflated with air that is used to " "play one of the various sports known as football.", price="$9.99", category_id=1, categories=category1, user_id=1, user=User1) session.add(category1_item1)
def fetch_everything_from_db(): return Posts(), Tags(), Categories()