def post(self): if self.checkAdminCookie(): categoryname = self.request.get("name") Category.addCategory(categoryname) self.redirect("/admin/index") else: self.redirect("/admin/login")
def get(self,product_id_string): if product_id_string.isdigit(): product_id = int(product_id_string) product = Product.getProductById(product_id) category = Category.getCategoryById(product.category.id()) categories = Category.getAllCategories() self.adminrender("admineditproduct.html", product = product, category = category, categories = categories) else: self.redirect("/admin/index")
def addCategory(): # Only the admin account of the website is allowed to add a category # The if statement prevents a user to get direct access through url if 'username' not in login_session: return redirect('/login') if login_session['email'] != site_admin: # Access denied. Render access denied page return render_template('accessDenied.html') admin = True # Default image for category located in static folder default_img = '/static/category_default.jpg' if request.method == 'POST': # If the user does not provide a url for the image, load default if not (request.form['pic_url']): url = default_img else: url = request.form['pic_url'] # Add info to new category newCat = Category(name=request.form['itemName'], description=request.form['description'], url=url, user_id=login_session['user_id']) # Add catefory to database session.add(newCat) session.commit() return redirect(url_for('catalog')) else: return render_template('addCategory.html', login=login_session, admin=admin)
def news_cate(): if request.method == 'POST': msg = {} #Ajax调用时的返回结果 name = request.form.get('name') id = request.form.get('id') if name: cate = Category.query.filter( Category.name == name).first() #判断是否有同名 if cate: #同名返回失败 msg['code'] = RET.DATAEXIST msg['message'] = error_map[RET.DATAEXIST] else: if not id: #通过ID来判断,操作类型(新增,修改) c = Category(name=name) apps.db.session.add(c) else: #更新新闻分类 Category.query.filter(Category.id == id).update( {'name': name}) msg['code'] = RET.OK msg['message'] = error_map[RET.OK] else: msg['code'] = RET.NODATA msg['message'] = error_map[RET.NODATA] return jsonify(msg) cate = Category.query.all() return render_template('admin/news_type.html', category=cate)
def category_new(): if not is_loggedin() and USING_AUTH: flash(MSG_NOT_AUTHORIZED.format('add a new category')) return redirect('/') if request.method == 'POST': # Checking the CSRF token if not correct_csrf(): return redirect(url_for('category_new')) name = request.form['name'] description = request.form['description'] category = Category( name=name, description=description, gplus_id=get_userid() ) dbsession.add(category) dbsession.commit() flash('New Category added!') return redirect(url_for('index')) # New CSRF token csrf_token = update_csrf_token() # Google Auth session['state'] = get_state_token() return render_template('category/new.html', csrf_token=csrf_token)
def userrender(self, template, **kw): categories = Category.getAllCategories() cart = self.session.get('cart') iconnumber = 0 if cart: for position in cart: iconnumber = iconnumber + position[1] self.render(template, categories = categories, iconnumber = iconnumber, **kw)
def newCategory(): """ Add a new category within the catalog. This page will provide a form for the user to create a new catalog category. This page is only accessible once logged in, and the created category will be owned by the logged in user. """ state = generateState(login_session, 'state') if request.method == 'GET': try: user = login_session['username'] return render_template('newCategory.html', STATE=state) except KeyError: flash("Please log in!") return redirect(url_for('showCatalog')) else: email = login_session['email'] user = session.query(User).filter_by(email=email).one() user_id = user.id name = request.form['name'] image = request.files['image'] # check if the post request has the file part if not image: if name: newCategory = Category(name=name, user_id=user_id) session.add(newCategory) session.commit() flash("New category added!") return redirect(url_for('showCatalog')) flash("Please choose a name!") return redirect(url_for('newCategory')) file = request.files['image'] if file and allowed_file(file.filename): if name: filename = secure_filename(file.filename) file.save(app.config['UPLOAD_FOLDER'] + filename) newCategory = Category(name=name, image=filename, user_id=user_id) session.add(newCategory) session.commit() flash("New category added!") return redirect(url_for('showCatalog')) flash("Please choose a name!") return redirect(url_for('newCategory'))
def add_category(payload): body = request.get_json() try: category = body.get("category", None) if exist(Category, category, "category"): abort(422) else: new = Category(category=category) new.insert() except: abort(422) return (jsonify({ "success": True, "added_category_id": new.id, "added_category": new.category }))
def saveCategory(): categoryName = request.form.get('c_name') if session.query(Category).filter_by(name=categoryName).count() != 0: flash("Category already added, you can add items to it.", 'info') else: category = Category( name=categoryName, user_id=login_session.get('user_id') ) session.add(category) session.commit() flash("Category %s successfully added." % (categoryName), 'success') return redirect(url_for('index'))
def new_category(): if 'name' in request.form: try: new_category = Category(name=request.form['name'], user_id=1) db_session.add(new_category) db_session.commit() return redirect(url_for('get_items', category_id=new_category.id)) except Exception as e: print('Error: ') print(e) return abort(Response('An unexpected error occurred', 500)) else: return abort(Response('Required form parameters are missing', 400))
def choose_category(cnx): """ Prints a list of categories and asks the user to choose between them. """ cats = Category.get_categories(cnx, 30) print("Choisissez une catégorie :") for num, cat in enumerate(cats): print("[{}] {}".format(str(num + 1).zfill(2), cat.name)) # A number has to be chosen between 0 and 30 (excluded) chosen_cat = get_number("? ", range(1, 31)) - 1 return cats[chosen_cat]
def scrape(self, cnx): """ This function scrapes all it can scrape from the API, first the categories then all the usable products in them. It removes the category if it turns out to be empty once all the useless products weeded out (like the ones without a nutriscore or a name). """ logging.info("Getting and adding category info") categories, categories_name = self.scrape_categories() Category.add_bulk(cnx, categories_name) logging.info("Getting and adding product info.") for category_json in categories: category = Category.from_name(cnx, category_json["name"]) products = self.scrape_products(category_json, category.id) # We only register the products if there is 2 or more products # after they have been filtered, or else there is no point. # If there is no point we might as well remove the category. if len(products) > 1: Product.add_products(cnx, products) else: category.remove(cnx)
def addCategory(): if session.get('id', 0) != 0: id = session['id'] name = request.json['name'] desc = request.json['description'] c = Category(name=name, description=desc, created_by=id) db_session.add(c) db_session.commit() res = make_response(json.dumps({'id': c.id, 'msg': "category added"}), 200) res.headers['Content-Type'] = 'application/json' return res else: res = make_response(json.dumps("forbidden"), 403) res.headers['Content-Type'] = 'application/json' return res
def news_cate(): if request.method == 'POST': msg = {} name = request.form.get('name') if name: c = Category(name=name) apps.db.session.add(c) msg['code'] = '200' msg['message'] = '添加成功' else: msg['code'] = '500' msg['message'] = '不能为空' return jsonify(msg) cate = Category.query.all() return render_template('/admin/news_type.html', category=cate)
def create_category(): if request.method == 'POST': name = request.form.get('catname') description = request.form['cat_desc'] user_session = login_session['username'] if name is None or description is None: print 'Missing arguments' abort(400) user_id = session.query(User).\ filter_by(username=user_session).first() catInfo = Category(name=name, description=description, user_id=user_id.id) session.add(catInfo) session.commit() flash('Your category is added successfully') return redirect(url_for('index')) else: return render_template('newcat.html', pagename='Add New Category')
def make(self): with open("data/categories.csv") as inCategories: for line in inCategories: objLine = line.split(",") category = Category(objLine[1].strip(" "), objLine[2].strip("\n").strip(" ")) db.session.add(category) db.session.commit() with open("data/words.csv") as inWords: for line in inWords: objLine = line.strip("\n").strip("\r").split("\t") if objLine[2].strip(" ") != "": print objLine[2].strip("\n").strip(" ") category = db.session.query(Category).filter( Category.id == int(objLine[2].strip("\n").strip( " "))).first() # print objLine[4] word = Word(objLine[0].strip(" "), objLine[1].strip(" "), objLine[3].strip(" "), objLine[4].strip(" ")) category.words.append(word) db.session.commit()
def addCategory(): user = getUserByEmail(login_session['email']) if user: # POST method add category if request.method == 'POST': name = request.form['name'] category = Category(name=name, user_id=user.id) session.add(category) session.commit() flash('Successfully added category!') categories = session.query(Category).filter_by( user_id=user.id).all() return render_template('showusercategory.html', categories=categories, user=user) # GET method add category return render_template('addcategory.html', user=user) else: return redirect(url_for('login'))
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # 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() # items for Soccer category1 = Category(name="Soccer") session.add(category1) session.commit() Item1 = Items(name="soccer shin Gaurd", description="xzcvxzv", price="$2.99", category=category1) session.add(Item1) session.commit() Item2 = Items(name="soccer ball", description="fsgsd", price="$5.50", category=category1) session.add(Item2)
from sqlalchemy import create_engine engine = create_engine('sqlite:///catalog.db', echo=True) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() from database import Category, Item breads = Category(name='Breads') dairy = Category(name='Dairy') veggies = Category(name='Vegetables') poultry = Category(name='Poultry') fruits = Category(name='Fruits') cereal = Category(name='Cereal') jam = Category(name='Jams') sauce = Category(name='Sauces') flour = Category(name='Flour') spices = Category(name='Spices') poultry = Category(name='Poultry') beans = Category(name='Beans') tea = Category(name='Tea') coffee = Category(name='Coffee') cats = [] cats.extend([ breads, dairy, veggies, poultry, fruits, cereal, jam, sauce, flour, spices, poultry, beans, tea, coffee ])
DBSession = sessionmaker(bind = engine) session = DBSession() user1 = User(name = "Ariana Lopez", email = "*****@*****.**") session.add(user1) user2 = User(name = "Alaina Lopez", email = "*****@*****.**") session.add(user2) user3 = User(name = "Mike Wayne", email = "*****@*****.**") session.add(user3) user4 = User(name = "Thomas Nyguen", email = "*****@*****.**") session.add(user4) category1 = Category(name = "WWE") session.add(category1) category2 = Category(name = "Ring of Honor") session.add(category2) category3 = Category(name = "TNA") session.add(category3) item1 = Item(name = "T-shirt", description="New day booty'Os shirt", user_id = 1, category_id = 2) session.add(item1) item2 = Item(name = "Tickets", description="ROH show on Tuesday", user_id = 4, category_id = 3) session.add(item2) session.commit()
# Bind the engine to the metadata of the Base class so that the # declaratives can be accessed through a DBSession instance Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # 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() category1 = Category( name="Snowboarding", picture="https://static.pexels.com/photos/376697/pexels-photo-376697.jpeg") session.add(category1) session.commit() item1 = Item( name="Goggles", description= "High performance anti-fog and UV400 protection - The X4 ski goggles featured with double lens made of solid PC material which came with unique lagopus anti-fogging treatment and 100% UV400 protection that cuts the glare.", category_id=category1.id) session.add(item1) session.commit() item2 = Item( name="Snowboard", description= "The Timeless is a snowboard guaranteed to live up to it's name! Built around the strongest core System has, the 3D Core with Edgelock is full tip to tail poplar with high density stringers running just outside the center of the board as well as down each rail, easily driving and holding your edge in to any snow conditions! Then an artisan grade heartwood stringer is set in the center of the board creating explosive power and response from the park to big mountain carves!",
def get(self): args = listV.parse_args() result = Category.getPaginated(args) return result['data'], result['code']
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database import Base, Category, Items, Users engine = create_engine('sqlite:///catalog.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Categories Soccer = Category(name="Soccer") session.add(Soccer) session.commit() Basketball = Category(name="Basketball") session.add(Basketball) session.commit() Baseball = Category(name="Baseball") session.add(Baseball) session.commit() Frisbee = Category(name="Frisbee") session.add(Frisbee) session.commit() Snowboarding = Category(name="Snowboarding") session.add(Snowboarding) session.commit() Rockclimbing = Category(name="Rockclimbing")
from orator import DatabaseManager, Model import csv from database import Business, Category DATA_SET = 'sfRestaurants' with open(f'data/{DATA_SET}.csv', 'r') as csvfile: reader = csv.DictReader(csvfile) for b in reader: business = Business.first_or_new(remote_id=b['id']) business.name = b['name'] business.review_count = b['review_count'] business.rating = b['rating'] business.latitude = b['latitude'] business.longitude = b['longitude'] business.location = b['location'] business.price = b['price'] business.phone = b['phone'] business.save() for c in b['categories'].split(';'): category = Category.first_or_create(name=c) business.categories().save(category)
async def post(self): body = self.loads_request_body() self.session.add(Category(idUser=self.user_id, label=body["label"], icon=body["icon"])) self.session.commit()
DBSession = sessionmaker(bind=engine) # A DBSession() instance establishes all conversations with the database # 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(email="*****@*****.**") session.add(user1) session.commit() category1 = Category(name="Ball") session.add(category1) session.commit() item1 = Item(name="Footbal", description="A football, \ soccer ball, or association football ball is the ball \ used in the sport of association football.", category=category1, auth=user1) session.add(item1) session.commit() item1 = Item(name="Basketball",
engine = create_engine("sqlite:///catalog.db") Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Creating a user jaspion = User(name="Jaspion", email="jaspion.gmail.com", picture="http://modomeu.com/wp-content/" "uploads/2015/05/23-jaspion.jpg") session.add(jaspion) session.commit() # Creating all the categories and items soccer = Category(name="Soccer") session.add(soccer) session.commit() frisbee = Category(name="Frisbee") session.add(frisbee) session.commit() basketball = Category(name="Basketball") session.add(basketball) session.commit() baseball = Category(name="Baseball") session.add(baseball) session.commit()
def get(self): result = Category.getAll() return result['data'], result['code']
# Create dummy user picture = 'https://lh5.googleusercontent.com/-YlxROPOjjOQ/AAAAAAAAAAI/AAAAA' picture += 'AAAAAA/ACHi3rfbjGFyUZp8LRwsJewv7h7q08ELzQ/s96-c/photo.jpg' User1 = User(name="Arun Godwin Patel", email="*****@*****.**", picture=picture) session.add(User1) session.commit() User2 = User(name="Testy McTester", email="*****@*****.**") session.add(User2) session.commit() # Items for Football category = Category(name="Football", image="football.jpg", user_id=1) session.add(category) session.commit() description = "Protective pads to be worn on your shins, essential for " description += "competitive football matches. Created from a mix of carbon " description += "fibre and polythene, these shin pads can take the equivalent " description += "of 5G of force before breaking." Items = Item(title="Shin Pads", description=description, category_id=1, user_id=1) session.add(Items) session.commit() description = "Soft and sturdy gloves that will protect and reinforce saving " description += "the ball, whilst providing incomparable warmth and touch " description += "when distributing to your team."
def bulk_add_example_data(payload): categories = pd.read_csv("initialdata/categories.csv", sep=";") movies = pd.read_csv("initialdata/movies.csv", sep=";") questions = pd.read_csv("initialdata/questions.csv", sep=";") movie_answers = pd.read_csv("initialdata/question_movie_mapping.csv", sep=";", decimal=",") #Add example categories for i, row in categories.iterrows(): new = Category(category=row["Category"]) new.insert() #Add example movies for i, row in movies.iterrows(): new = Movie(title=row["title"], description=row["description"], category_id=row["category_id"]) new.insert() #Add example questions for i, row in questions.iterrows(): new = Question(question=row["question"], category_id=row["category_id"], Type=row["Type"]) new.insert() #Add Question Answers for i, row in movie_answers.iterrows(): for question_id in movie_answers.columns[1:]: new = QuestionMovie(question_id=question_id, movie_id=row["movie_id"], answer=row[question_id]) new.insert() return (jsonify({"success": True}))
def get(self): categories = Category.getAllCategories() self.adminrender("adminnewproduct.html", categories = categories)
def populate_db(): """Populate the DB with some initial data. It will be added an example user, some categories and items. """ catalog_json = json.loads(""" {"Catalog": [{"Item": [{"description": "An inflated ball used in playing soccer.", "name": "Soccer ball" }, {"description": "Item of clothing worn on the feet and often covering the ankle or part of the calf.", "name": "Socks" }], "category": "Soccer" }, {"Item": [], "category": "Basketball" }, {"Item": [{"description": "A smooth wooden or metal club used to hit the ball after it's thrown by the pitcher", "name": "Bat" }], "category": "Baseball" }, {"Item": [{"description": "A frisbee disc with size of 175 gram disc.", "name": "Disc" }], "category": "Frisbee" }, {"Item": [{"description": "Best for any terrain conditions", "name": "Snowboard" }], "category": "Snowboarding" }, {"Item": [], "category": "Rock Climbing" }, {"Item": [], "category": "Foosball" }, {"Item": [], "category": "Skating" }, {"Item": [{"description": "Made with metal blades attached underfoot and used to propel the bearer across a sheet of ice while ice skating.", "name": "Hockey Skates" }], "category": "Hockey" }] }""") user = User(username='******', email='*****@*****.**', picture='mypicture') user.hash_password('123456') db_session.add(user) db_session.commit() for c in catalog_json['Catalog']: category = Category(name=c['category']) db_session.add(category) db_session.commit() for i in c['Item']: item = Item(name=i['name'], description=i['description'], category_id=category.id, user_id=user.id) db_session.add(item) db_session.commit() print('Database populated.')
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database import Base from database import Category from database import CategoryItem engine = create_engine('sqlite:///categoryItems.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() # Items for Apple company1 = Category(name="Apple") session.add(company1) session.commit() CategoryItem1 = CategoryItem(name="iPhone XR", description="""All-screen design. Longest battery life ever in an iPhone. Fastest performance. And studio-quality photos. Trade in your current iPhone and upgrade to iPhone XR.""", price="$449", category=company1) session.add(CategoryItem1) session.commit() # Items for Samsung company2 = Category(name="Samsung")
def delete(self, categoryId): result = Category.delete(categoryId) return result['data'], result['code']