def create_category(data): name = data.get('name') category_id = data.get('id') category = Category(name) if category_id: category.id = category_id db.session.add(category) db.session.commit()
def create_category_submission(): try: # Create Category instance with user inputs category = Category(name=request.form["name"].lower(), description=request.form["description"]) # Insert the instance into the db category.insert() flash(request.form['name'] + ' category was successfully listed!') return redirect(url_for('web_app.get_categories')) except BaseException: abort(422)
def post(self): body = request.get_json() user_id = get_jwt_identity() user = User.objects.get(id=user_id) if not user.privilege: return {'error': 'Elevated privilege required'}, 403 new_cat = Category(**body) try: new_cat.save() except ValidationError: return {'error': 'Missing required values or duplicate names'}, 400 else: id = new_cat.id return {'id': str(id)}, 200
def add_category(token): data = request.get_json() try: category = Category(type=data.get('type'), description=data.get('description')) category.insert() return jsonify({ 'success': True, 'category': category.format() }),200 except: print(sys.exc_info()) db.session.rollback() abort(401) finally: db.session.close()
def get(self): all_category = Category.objects() categories = json.loads(all_category.to_json()) data = wrap_category_info(categories) return Response(json.dumps(data), mimetype="application/json", status=200)
def category(): """Menu to choose the music gnere we want to listen to.""" # Define user_input to enter the loop user_input = None # Get all categories in database categories = Category.select() # Show all categories available print("Styles de musique disponibles :") for category in categories: print("\t%i %s" % (category.id, category.name)) while user_input is None: user_input = input("Choisisez maintenant votre style : ") try: user_input = int(user_input) except ValueError: print(settings.errors['NOT_A_NUMBER']) if user_input in range(1, len(categories) + 1): play.play(user_input) else: user_input = None print(settings.errors['CHOICE_NOT_EXISTS'])
def post(self): json_data = request.get_json(force=True) if not json_data: return {'message': 'No input data provided'}, 400 data, errors = category_schema.load(**json_data) if errors: return errors, 422 category = Category.query.filter_by(name=data['name']).first() if category: return { 'message': 'The category ' + data['name'] + 'already exists' }, 409 category = Category( name=data['name'] ) db.session.add(category) db.session.commit() response = category_schema.dump(category).data return { 'status': 'sucessful', 'response': response }, 201
def create_category(payload): body = request.get_json() # If the request doesn't contain the below keys return 400 if not ('name' in body and 'description' in body): abort(400) try: # Create Category instance category = Category( name=body.get('name'), description=body.get('description') ) # Insert the instance into the db category.insert() return jsonify({ "success": True, "category": category.format() }) except BaseException: abort(422)
def add_category(): try: name = request.json['name'] new_category = Category(name) db.session.add(new_category) db.session.commit() except IntegrityError: return jsonify({'message': 'This category already exist'}) return category_schema.jsonify(new_category)
def init_database(): db.create_all() # create image categories with open("imagenet.txt", "r") as f: dict_categories = ast.literal_eval(f.read()) categories = [] for k, v in dict_categories.items(): categories.append(Category(label=k, description=v)) db.session.bulk_save_objects(categories) db.session.commit()
def create_Article(jwt): json = request.get_json() print(f" json arrived is {json}") title = json['title'] image = json['image'] category = json['category'].lower() article = json['contet'] is_found = Category.query.filter_by(category_name=category).all() if len(is_found) > 0: print(f" stored before {is_found}") items = Category.query.filter_by(category_name=category).all() print(f"Length of categories {len(items)}") if (len(items) > 0): print(f" category {items[0].id}") article_item = Article(title=title, image_url=image, category_id=items[len(items) - 1].id, content=article, likes=0) article_item.insert() return jsonify({"success": True, "article": "article_item"}) category_item = Category(category_name=category.lower()) category_item.flush() article_item = Article(title=title, image_url=image, category_id=category_item.id, content=article, likes=0) category_item.insert() article_item.insert() print("POSTED ") return jsonify({"success": True, "article": "article_item"})
async def addcat(self, ctx: commands.Context, *, cat: str): category = session.query(Category).filter( func.lower(Category.name) == cat.lower()).first() if category: await ctx.send( f"<{EMOJIS['XMARK']}> '{cat}' is already a category in the Melons!" ) else: category = Category(name=cat) session.add(category) session.commit() await ctx.send( f"<{EMOJIS['CHECK']}> Successfully added '{cat}' as a category in the Melons!" )
def post(self, id): body = request.form args = self.reqparse.parse_args() event = Event(**body) event.is_public = args['is_public'] event.category_id = Category.objects().get(id=id).id event.save() if 'image' in request.files: file = request.files['image'] s3 = session.client s3.put_object(Body=file, Bucket="devbucket0", ContentType=file.content_type, Key=str(event.id)) event.img_src = '/api/events/{}/image'.format(str(event.id)) event.save() return {'id': str(event.id)}, 200
from server_app import db from database.models import Offer, Category c = [ 'общепит', 'магазины', 'услуги', 'мероприятия', 'администрация', 'транспорт', 'образование', 'развлечения', 'спорт' ] d = {c.index(name): Category(name) for name in c} for numb in d: db.session.add(d[numb]) db.session.add( Offer('ПМ-ПУ', 'ПН,ВТ,СР,ЧТ,ПТ,СБ|9:00-15:00|12:50-13:50\nВС', d[6], 'Факультет Прикладной Математики - Процессов Управления', { 'lat': 29.8305631, 'lng': 59.8821827 }, 'https://apmath.spbu.ru', 'пм вуз факультет')) db.session.add( Offer('К-Руока', 'ПН,ВТ,СР,ЧТ,ПТ,СБ,ВС|00:00-00:00|\n', d[1], 'Финский супермаркет', { 'lat': 29.8258102, 'lng': 59.8694873 }, 'http://www.k-ruoka.ru/', 'магазин продукты супермаркет финский бухло еда')) # db.session.add(Offer('Говно с дымом', # 'ПН,ВТ,СР,ЧТ,ПТ,СБ,ВС|00:00-00:00|\n', # d[1], # 'Плюхи у Илюхи', # {'lat': 29.828242, 'lng': 59.8741827}, # 'http://fbi.com', # 'бухло кальян содомия современное искусство vape'))
def play(category): """ Play the blindtest itself, save and show score and ask a rating for the project.""" # Get Category try: category = Category.get(id=category) except Exception: print("Impossible de récupérer la catégorie dans la base de données.") # Execute rest of code only if category exists if category is not None: # Convert musics from this category to a list musics = list(category.musics) # Generate a shuffled list shuffled_musics = list(musics) shuffle(shuffled_musics) # Initialize score points = 0 # Generate a string with the non-shuffled list of musics musics_list = "" for music in musics: musics_list = musics_list + ("\n\t%i %s" % (reduce_id(music.id), music.name)) # Play musics one by one and ask user what music is it for i, music in enumerate(shuffled_musics): # Define the right answer answer = reduce_id(music.id) # Initialize user_input user_input = None # Show answers list print("Propositions :%s\n" % musics_list) # Play music music_to_play = Music(music) # Execute code only if the music exists if music_to_play is not None: if music_to_play.is_exists(): music_to_play.play() # Ask user for the answer while user_input is None: user_input = input("Votre réponse : ") try: user_input = int(user_input) except ValueError: print(settings.errors['NOT_A_NUMBER']) if user_input in range(1, 11): if user_input == answer: print("Votre réponse était JUSTE.") points = points + 1 else: print("Votre réponse était FAUSSE.") else: user_input = None print("Veuillez entrer un nombre entre 1 et 10.") # Save and show score score = Score(points) score.save() score.show() # Ask for a rating thanks() # Go back to main menu menus.main()
def create_category(db: Session, name: str): category = Category(name=name) db.add(category) db.commit() db.refresh(category) return category
def post(self): body = request.get_json() category = Category(**body).save() id = category.id return {'id': str(id)}, 201
def get(self): categories = Category.objects().to_json() return Response(categories, mimetype="application/json", status=200)
async def addmelon(self, ctx: commands.Context, *, arg: str = ""): def check(m): return m.author == ctx.author and m.channel == ctx.channel if arg and ctx.author.id in AUTHORIZED_USERS: category = session.query(Category).filter( func.lower(Category.name) == arg.lower()).first() if not category: msg = await ctx.send( f"<{EMOJIS['XMARK']}> Category '{arg}' doesn't exist! Would you like to create it?" ) await msg.add_reaction(f"<{EMOJIS['CHECK']}>") await msg.add_reaction(f"<{EMOJIS['XMARK']}>") try: reaction = await bot.wait_for("reaction_add", check=check, timeout=2 * 60) if reaction[0].custom_emoji and reaction[ 0].emoji.id == int(EMOJIS['CHECK'].split(":")[2]): category = Category(name=arg) session.add(category) await ctx.send( f"<{EMOJIS['CHECK']}> Category '{arg}' successfully created!" ) except asyncio.exceptions.TimeoutError: await ctx.send( f"<{EMOJIS['XMARK']}> That took too long! " + "You can restart the process by calling this command again." ) return key = await self.ask_prompt( ctx, "❓ What should the key of the Melon be?") if not key: return else: key = key.lower() melon = session.query(Melon).filter( and_( func.lower(Melon.key) == key, Melon.category_id == category.category_id)).first() if melon: await ctx.send( f"❗ A Melon with that key already exists in {arg}! " + "You can edit it with `!editmelon`.") return await ctx.send(f"❓ What should the value of {key} be?") message = await self.bot.wait_for("message", check=check) melon = Melon(key=key, category=category, value=message.content, created_by=ctx.author.id) session.add(melon) session.commit() await ctx.send( f"<{EMOJIS['CHECK']}> Successfully added Melon '{key}' to the global Melons!" ) else: guild = self.bot.get_db_guild(ctx.guild.id) if not guild.melon_role: await ctx.send( f"<{EMOJIS['XMARK']}> Custom Melons for this guild haven't been enabled!" ) return roles = [role.id for role in ctx.author.roles] if guild.melon_role not in roles: await ctx.send( f"<{EMOJIS['XMARK']}> You aren't authorized to edit Melons in this guild!" ) return if not arg: key = await self.ask_prompt( ctx, "❓ What should the key of the Melon be?") if not key: return else: key = key.lower() else: key = arg.lower() melon = session.query(Melon).filter( and_( func.lower(Melon.key) == key, Melon.guild_id == guild.guild_id)).first() if melon: await ctx.send( f"❗ A Melon with that key already exists in this guild! " + "You can edit it with `!editmelon`.") return await ctx.send(f"❓ What should the value of {key} be?") message = await self.bot.wait_for("message", check=check) melon = Melon(key=key, guild=guild, value=message.content, created_by=ctx.author.id) session.add(melon) session.commit() await ctx.send( f"<{EMOJIS['CHECK']}> Successfully added Melon '{key}' to the guild Melons!" )